Files
lucisv/crates/vlog_formatter/src/printer.rs
T
lucioandClaude Fable 5 02f68655b5 Add error-recovery and format-fences (jointly: entangled in format.rs)
error-recovery (vlog_parser): parse_source_tolerant never fails —
errors become positioned ParseDiagnostics and ItemKind::Error /
StmtKind::Error leaves (raw text + span, nesting invariant intact),
with recovery at documented sync tokens, bracket-balanced skipping,
and stray-closer collapse. Strict parse_source is byte-identical in
behavior (shared grammar, tolerant flag). Guarantees tested:
tolerant==strict on 500 valid sources; depth/links budgets neither
reset nor leak across recovery (mutation-tested); no panic across
27k+ truncation cuts, every single-char fixture deletion, 1MB of
semicolons (500k recoveries, 344ms). The future LSP parses mid-edit
code; the formatter still refuses on the first error.

format-fences (vlog_formatter): // verilog_format: off|on and
// vfmt: off|on emit fenced item ranges as exact source bytes via
spans (Doc::Verbatim), Verible-style item-level regions per scope,
unmatched off to end of scope, byte-exact including indentation and
idempotent at every join (24 adversarial probes). ~2000 corpus fence
injections: zero region byte changes, zero new verification
failures. verify.rs untouched; with no fences output is
byte-identical (corpus TSV md5 unchanged).

Also surfaced and queued in TODO: comment-in-list refusals
(112/1868 injection trials) and the double-blank leading-comment
nit — the next comments round.

Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{error-recovery,format-fences}/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-19 05:23:05 -07:00

211 lines
7.1 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::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::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)");
}
#[test]
fn hard_line_forces_break() {
let d = group(vec![text("a"), Doc::HardLine, text("b")]);
assert_eq!(p(80, d), "a\nb");
}
}