Files
lucisv/crates/vlog_formatter/src/printer.rs
T
lucioandClaude Fable 5 53f226981f printer: multi-line raw text keeps the column honest
Raw text carrying a string literal across a line break, and the #( ... )
of a parameterized type, were emitted as a single Doc::Text with embedded
newlines -- violating that variant's contract and leaving the printer's
column tracker stale, so every later fits() on the line broke
conservatively. Both now emit Doc::Inline, whose printer arm resumes
measuring from the text's own last line. Output bytes are identical
except where the stale column forced a spurious break: one corpus file
(id_queue_tb.sv) improves, pass set unchanged at 813/820, verify.rs
untouched. Found by QA in the directive-split round; pinned by a printer
test and a classes.cases entry.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 02:10:10 -07:00

279 lines
10 KiB
Rust

//! The printer: renders a [`Doc`] tree to text within a target line width.
//!
//! This is the classic "strictly pretty" algorithm (also at the heart of
//! prettier and ruff_formatter): a work stack of (indent, mode, doc) triples
//! plus a lookahead `fits` check deciding whether each group prints flat.
use crate::doc::Doc;
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
Flat,
Break,
}
pub struct Printer {
pub max_width: usize,
pub indent_width: usize,
}
impl Printer {
pub fn print(&self, doc: &Doc) -> String {
let mut out = String::new();
let mut col = 0usize;
// Stack of (indent_level, mode, doc).
let mut stack: Vec<(usize, Mode, &Doc)> = vec![(0, Mode::Break, doc)];
while let Some((ind, mode, d)) = stack.pop() {
match d {
Doc::Text(s) => {
out.push_str(s);
col += s.chars().count();
}
Doc::Inline(s) => {
out.push_str(s);
// The text brought its own line breaks: keep measuring
// from the last one it wrote.
col = match s.rsplit_once('\n') {
Some((_, last)) => last.chars().count(),
None => col + s.chars().count(),
};
}
Doc::Concat(items) => {
for item in items.iter().rev() {
stack.push((ind, mode, item));
}
}
Doc::Indent(items) => {
for item in items.iter().rev() {
stack.push((ind + 1, mode, item));
}
}
Doc::Group(items) => {
let flat = !contains_hard_line(items) && self.fits(col, items, &stack);
let m = if flat { Mode::Flat } else { Mode::Break };
for item in items.iter().rev() {
stack.push((ind, m, item));
}
}
Doc::Line => {
if mode == Mode::Flat {
out.push(' ');
col += 1;
} else {
self.newline(&mut out, &mut col, ind);
}
}
Doc::SoftLine => {
if mode == Mode::Break {
self.newline(&mut out, &mut col, ind);
}
}
Doc::HardLine => {
self.newline(&mut out, &mut col, ind);
}
Doc::BlankLine => {
// Trim trailing spaces from the current line, add a blank.
while out.ends_with(' ') {
out.pop();
}
out.push('\n');
self.newline(&mut out, &mut col, ind);
}
Doc::IfBreak(s) => {
if mode == Mode::Break {
out.push_str(s);
col += s.chars().count();
}
}
Doc::Verbatim(s) => {
// Undo the indent the preceding line break wrote: these
// bytes carry their own.
while out.ends_with(' ') {
out.pop();
}
out.push_str(s);
col = s.rsplit('\n').next().map_or(0, |last| last.chars().count());
}
}
}
out
}
fn newline(&self, out: &mut String, col: &mut usize, ind: usize) {
while out.ends_with(' ') {
out.pop();
}
out.push('\n');
let spaces = ind * self.indent_width;
out.extend(std::iter::repeat_n(' ', spaces));
*col = spaces;
}
/// Would `items` (flat) followed by the rest of the work stack fit on
/// the current line?
fn fits(&self, col: usize, items: &[Doc], rest: &[(usize, Mode, &Doc)]) -> bool {
let mut width = self.max_width as isize - col as isize;
if width < 0 {
return false;
}
// Local stack: the group's own content in flat mode, then the
// remainder of the outer stack (in its own modes) until a newline.
let mut stack: Vec<(Mode, &Doc)> = Vec::new();
for (_, mode, d) in rest.iter() {
stack.push((*mode, d));
}
// rest is a stack (top = last); keep order: we pushed bottom-first,
// so reverse to keep top of stack at the end.
// (rest's last element is the next to be processed.)
for item in items.iter().rev() {
stack.push((Mode::Flat, item));
}
while width >= 0 {
let Some((mode, d)) = stack.pop() else { return true };
match d {
Doc::Text(s) => width -= s.chars().count() as isize,
Doc::Inline(s) => {
// Only the first line shares the current line, and it has
// to fit on it. What follows the text keeps writing on
// the line its *last* line ends on (that is what `print`
// does), so measuring continues from there rather than
// stopping here — otherwise a group whose tail overflows
// would be judged to fit.
if let Some((head, _)) = s.split_once('\n') {
if width < head.chars().count() as isize {
return false;
}
let last = s.rsplit_once('\n').map_or(0, |(_, l)| l.chars().count());
width = self.max_width as isize - last as isize;
} else {
width -= s.chars().count() as isize;
}
}
Doc::Concat(items) | Doc::Indent(items) => {
for it in items.iter().rev() {
stack.push((mode, it));
}
}
Doc::Group(items) => {
// Nested groups are measured flat unless they contain a
// hard line, which ends the line anyway.
if contains_hard_line(items) {
// Everything up to the hard line still has to fit.
for it in items.iter().rev() {
stack.push((Mode::Break, it));
}
} else {
for it in items.iter().rev() {
stack.push((Mode::Flat, it));
}
}
}
Doc::Line => {
if mode == Mode::Flat {
width -= 1;
} else {
return true;
}
}
Doc::SoftLine => {
if mode == Mode::Break {
return true;
}
}
Doc::HardLine | Doc::BlankLine | Doc::Verbatim(_) => return true,
Doc::IfBreak(s) => {
if mode == Mode::Break {
width -= s.chars().count() as isize;
}
}
}
}
false
}
}
pub(crate) fn contains_hard_line(items: &[Doc]) -> bool {
items.iter().any(|d| match d {
Doc::HardLine | Doc::BlankLine | Doc::Verbatim(_) => true,
Doc::Concat(inner) | Doc::Indent(inner) | Doc::Group(inner) => contains_hard_line(inner),
_ => false,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::doc::*;
fn p(width: usize, doc: Doc) -> String {
Printer { max_width: width, indent_width: 2 }.print(&doc)
}
#[test]
fn flat_when_fits() {
let d = group(vec![text("foo("), Doc::SoftLine, text("bar"), Doc::SoftLine, text(")")]);
assert_eq!(p(80, d), "foo(bar)");
}
#[test]
fn breaks_when_too_wide() {
let d = group(vec![
text("foo("),
indent(vec![Doc::SoftLine, text("barbarbar")]),
Doc::SoftLine,
text(")"),
]);
assert_eq!(p(8, d), "foo(\n barbarbar\n)");
}
/// A multi-line `Inline` does not end the line: whatever follows it keeps
/// writing on the line its last line ends on, so the group's fit check has
/// to keep measuring past it — from that line's width, not from the
/// indent. QA round-1 finding.
fn inline_group(tail: &str) -> Doc {
group(vec![
text("if ("),
Doc::Inline("with {\n x == 1;\n} ".into()),
indent(vec![Doc::SoftLine, text(tail)]),
text(")"),
])
}
#[test]
fn group_stays_flat_when_the_tail_after_an_inline_fits() {
assert_eq!(p(20, inline_group("&& ok")), "if (with {\n x == 1;\n} && ok)");
}
#[test]
fn group_breaks_when_the_tail_after_an_inline_overflows() {
assert_eq!(
p(20, inline_group("&& far_too_long_to_fit")),
"if (with {\n x == 1;\n}\n && far_too_long_to_fit)"
);
}
/// After a multi-line `Inline` is *printed*, `col` is the width of its
/// last line — so a group that follows it on that line is measured from
/// there, not from an accumulated character count. Raw text that carries
/// a string literal across a line break rides this arm; when it was
/// emitted as `Doc::Text` (whose printer arm never resets `col` on the
/// embedded newlines it is not supposed to contain), the stale column
/// forced every later fit check on the line into a conservative break.
#[test]
fn a_group_after_a_multi_line_inline_measures_from_its_last_line() {
let d = concat(vec![
Doc::Inline("x = \"aaaaaaaaaaaaaaaaaaaaaaaa\nbbb\" ".into()),
group(vec![text("+"), indent(vec![Doc::Line, text("yyyy")]), text(";")]),
]);
assert_eq!(p(20, d), "x = \"aaaaaaaaaaaaaaaaaaaaaaaa\nbbb\" + yyyy;");
}
#[test]
fn hard_line_forces_break() {
let d = group(vec![text("a"), Doc::HardLine, text("b")]);
assert_eq!(p(80, d), "a\nb");
}
}