diff --git a/TODO.md b/TODO.md index fc15ddb..f5d45e9 100644 --- a/TODO.md +++ b/TODO.md @@ -67,16 +67,25 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both. and localparam/parameter lists. This needs original-spacing info preserved through the lexer — record "excess spaces before token" as trivia. -- [ ] **Comment inside port/param lists and assignment patterns is +- [x] **Comment inside port/param lists and assignment patterns is dropped → refused** (found at scale by format-fences QA: 112 of 1868 corpus injection trials refuse with exit 2). The failsafe holds, but this is the largest remaining comment-attachment gap; fix alongside the three documented expression refusals (replication, compact bracket, assign-value) from docs/features/formatter-bug-fixes and corpus-bugs. -- [ ] **Two leading comments separated by one blank line come out + → `Meta::before_sep` keeps a comment on its element's side of the + separator, at every list kind; replication, gate arguments, header + imports, event lists, a connection's own parens and the enum dangling + bucket all gained comment slots too. Injection-harness refusal rate + 2.3% → 0.4%. Still refused (documented, not hacked around): + `[a : b]`-style bracket interiors and a comment before a *procedural* + statement's `;` — see `docs/features/comments-round/README.md`. +- [x] **Two leading comments separated by one blank line come out separated by two** (format-fences QA find, pre-existing): `leading` pushes a HardLine after each comment and a BlankLine before the next. Fix churns snapshots; take it with the comments round above. + → `Fmt::leading_comments` emits the break *before* each comment + instead of after; 6 corpus files became fixed points, zero test churn. - [x] **[R] `--diff` mode.** Like `ruff format --diff` / Verible's autofix `patch` mode: print a unified diff instead of rewriting, for CI logs and code review. @@ -245,13 +254,21 @@ later: rules (unused-signal, undriven-net) which are the lint rules people actually want and Verible *can't* do (it's syntax-only — this is the differentiation opportunity). -- [ ] **`` `define`` table for hover expansion.** Record every +- [x] **`` `define`` table for hover expansion.** Record every `` `define`` (name, params, body text, source span) during lexing instead of treating it as fully opaque — no expansion during formatting (that non-goal stands), but the table feeds hover (`` `WIDTH`` → "defined as 8 in defs.svh:12") and later single-step macro expansion display. Cheap to collect now that directives carry `RawText`. + → `vlog_parser::defines::collect_defines(&tokens) -> DefineTable`, a + post-lex pass with zero lexer changes. `Define { kind, name, params, + body, span, name_span }`; every definition of a name is kept + (`all`/`latest`) and `` `undef`` is recorded as an event. Body + normalization (backslash-newline removed, nothing else touched) and the + gaps — no `` `ifdef`` evaluation, no cross-file `` `include`` — in + `docs/features/define-table/README.md`. Hover itself waits on + `vfmt_server`; this is only the table. - [ ] **Workspace index for cross-file navigation.** Map module/package/ typedef names → (file, span) across all workspace files, so header imports (`import pkg::*;`) and instantiations resolve to definitions diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs index 494cd40..e73643c 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -117,16 +117,19 @@ struct BinaryOp<'e> { struct ListItem { leading: Vec, doc: Doc, - trailing: Option, + /// Comments written between the element and the separator that follows. + before_sep: Vec, + trailing: Option, } impl ListItem { - fn plain(doc: Doc) -> Self { - ListItem { leading: Vec::new(), doc, trailing: None } - } - fn from_meta(meta: &Meta, doc: Doc) -> Self { - ListItem { leading: meta.leading.clone(), doc, trailing: meta.trailing.clone() } + ListItem { + leading: meta.leading.clone(), + doc, + before_sep: meta.before_sep.clone(), + trailing: meta.trailing.clone(), + } } } @@ -231,6 +234,12 @@ impl<'a> Fmt<'a> { /// Leading comments (each on its own line) preceding a node, with any /// fenced region they open spliced in as source bytes. + /// + /// The break between two comments is emitted *before* the second one, not + /// after the first: a `HardLine` followed by a `BlankLine` is three + /// newlines, so writing both turned one blank line between two comments + /// into two. The list still ends with the `HardLine` that puts the node + /// itself on a fresh line. fn leading_comments(&self, meta: &Meta) -> Vec { let mut docs = Vec::new(); for c in &meta.leading { @@ -239,10 +248,12 @@ impl<'a> Fmt<'a> { Slot::Opens(r) => self.verbatim(r), Slot::Normal => self.comment(c), }; - if !docs.is_empty() && c.blank_before { - docs.push(Doc::BlankLine); + if !docs.is_empty() { + docs.push(if c.blank_before { Doc::BlankLine } else { Doc::HardLine }); } docs.push(doc); + } + if !docs.is_empty() { docs.push(Doc::HardLine); } docs @@ -259,10 +270,13 @@ impl<'a> Fmt<'a> { } fn trailing(&self, meta: &Meta) -> Vec { - match &meta.trailing { - Some(tr) => vec![text(format!(" {tr}"))], - None => Vec::new(), + let mut docs = Vec::new(); + let ends_line = self.inline_comments(&meta.before_sep, &mut docs); + if let Some(tr) = &meta.trailing { + docs.push(if ends_line { Doc::HardLine } else { text(" ") }); + docs.push(self.comment(tr)); } + docs } /// Append comments written between two tokens of an expression, each @@ -282,6 +296,16 @@ impl<'a> Fmt<'a> { ends_line } + /// The same, plus the separator that keeps the next thing off the last + /// comment: a space, or a line break after a line comment. + fn inline_comments_spaced(&self, comments: &[Comment], docs: &mut Vec) { + if self.inline_comments(comments, docs) { + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + } + fn with_meta(&self, meta: &Meta, doc: Doc) -> Doc { let mut docs = self.leading(meta); docs.push(doc); @@ -318,22 +342,24 @@ impl<'a> Fmt<'a> { let last = items.len().saturating_sub(1); let mut close_needs_hardline = force_break; for (i, item) in items.into_iter().enumerate() { - if i > 0 { - // separator emitted below along with the previous trailing - } - let meta = Meta { - leading: item.leading, - trailing: None, - blank_before: false, - attrs: Vec::new(), - }; + let meta = Meta { leading: item.leading, ..Meta::default() }; inner.extend(self.leading(&meta)); inner.push(item.doc); + // Comments written before the separator print on this element's + // side of it, which is where the source put them. + let has_before_sep = !item.before_sep.is_empty(); + let ends_line = self.inline_comments(&item.before_sep, &mut inner); if i < last { + if ends_line { + inner.push(Doc::HardLine); + } inner.push(text(",")); + } else if has_before_sep { + close_needs_hardline = true; } if let Some(tr) = item.trailing { - inner.push(text(format!(" {tr}"))); + inner.push(text(" ")); + inner.push(self.comment(&tr)); if i < last { inner.push(Doc::HardLine); } else { @@ -543,9 +569,11 @@ impl<'a> Fmt<'a> { // One line per `import` statement the header wrote: folding two of // them into one comma-separated statement would rewrite a `;`. let mut lines = Vec::new(); - for paths in &m.imports { + for imp in &m.imports { lines.push(Doc::HardLine); - lines.push(text(format!("import {};", paths.join(", ")))); + lines.extend(self.leading(&imp.meta)); + lines.push(text(format!("import {};", imp.paths.join(", ")))); + lines.extend(self.trailing(&imp.meta)); } docs.push(indent(lines)); docs.push(Doc::HardLine); @@ -699,10 +727,21 @@ impl<'a> Fmt<'a> { /// breaks are introduced. fn expr_compact(&self, e: &Expr) -> Doc { match &e.kind { - ExprKind::Binary { lhs, op, rhs, .. } => { - let tight = Self::binary_prec(op) >= 8; - let sep = if tight { op.clone() } else { format!(" {op} ") }; - concat(vec![self.expr_compact(lhs), text(sep), self.expr_compact(rhs)]) + ExprKind::Binary { lhs, op, rhs, comments } => { + if comments.before.is_empty() && comments.after.is_empty() { + let tight = Self::binary_prec(op) >= 8; + let sep = if tight { op.clone() } else { format!(" {op} ") }; + return concat(vec![self.expr_compact(lhs), text(sep), self.expr_compact(rhs)]); + } + // A comment written next to the operator has nowhere to go in + // the tight spelling, so the operator gets its spaces back; + // a line comment pushes what follows onto the next line. + let mut docs = vec![self.expr_compact(lhs)]; + self.inline_comments_spaced(&comments.before, &mut docs); + docs.push(text(op.clone())); + self.inline_comments_spaced(&comments.after, &mut docs); + docs.push(self.expr_compact(rhs)); + concat(docs) } ExprKind::Ternary { cond, then, els, .. } => concat(vec![ self.expr_compact(cond), @@ -745,20 +784,18 @@ impl<'a> Fmt<'a> { .collect(); if items.len() == 1 { let item = items.into_iter().next().unwrap(); - let mut docs = self.leading(&Meta { - leading: item.leading, - trailing: None, - blank_before: false, - attrs: Vec::new(), - }); + let mut docs = self.leading(&Meta { leading: item.leading, ..Meta::default() }); docs.push(item.doc); + let mut ends_line = self.inline_comments(&item.before_sep, &mut docs); if let Some(tr) = item.trailing { - docs.push(text(format!(" {tr}"))); - // The caller appends the `;`; a line comment runs to end of - // line, so it has to go on the next one. - if is_line_comment(&tr) { - docs.push(Doc::HardLine); - } + docs.push(if ends_line { Doc::HardLine } else { text(" ") }); + docs.push(self.comment(&tr)); + ends_line = is_line_comment(&tr.text); + } + // The caller appends the `;`; a line comment runs to end of line, + // so it has to go on the next one. + if ends_line { + docs.push(Doc::HardLine); } return concat(docs); } @@ -766,20 +803,22 @@ impl<'a> Fmt<'a> { let mut inner = Vec::new(); let last = items.len() - 1; for (i, item) in items.into_iter().enumerate() { - let meta = Meta { - leading: item.leading, - trailing: None, - blank_before: false, - attrs: Vec::new(), - }; + let meta = Meta { leading: item.leading, ..Meta::default() }; inner.extend(self.leading(&meta)); inner.push(item.doc); + let ends_line = self.inline_comments(&item.before_sep, &mut inner); if i < last { + if ends_line { + inner.push(Doc::HardLine); + } inner.push(text(",")); + } else if ends_line { + inner.push(Doc::HardLine); } if let Some(tr) = item.trailing { - inner.push(text(format!(" {tr}"))); - if i < last || is_line_comment(&tr) { + inner.push(text(" ")); + inner.push(self.comment(&tr)); + if i < last || is_line_comment(&tr.text) { inner.push(Doc::HardLine); } } else if i < last { @@ -867,7 +906,10 @@ impl<'a> Fmt<'a> { ListItem::from_meta(&m.meta, concat(d)) }) .collect(); - docs.push(self.delimited("{", items, "}", false)); + // `e.dangling` — comments written before the closing `}` — + // is printed inside the braces; the enum has no other place + // to put it, and dropping it loses a comment. + docs.push(self.delimited_dangling("{", items, &e.dangling, "}", false)); docs.push(text(format!(" {};", t.name))); concat(docs) } @@ -893,9 +935,7 @@ impl<'a> Fmt<'a> { d.push(self.declarators(&m.declarators)); d.push(text(";")); inner.push(concat(d)); - if let Some(tr) = &m.meta.trailing { - inner.push(text(format!(" {tr}"))); - } + inner.extend(self.trailing(&m.meta)); } inner.extend(self.dangling(&s.dangling)); concat(vec![ @@ -937,22 +977,32 @@ impl<'a> Fmt<'a> { if items.len() == 1 { let item = items.into_iter().next().unwrap(); docs.push(item.doc); + // The last pair's separator is the `;`, so its `before_sep` + // comments print in front of it. + if self.inline_comments(&item.before_sep, &mut docs) { + docs.push(Doc::HardLine); + } docs.push(text(";")); if let Some(tr) = item.trailing { - docs.push(text(format!(" {tr}"))); + docs.push(text(" ")); + docs.push(self.comment(&tr)); } } else { let last = items.len() - 1; let mut inner = Vec::new(); for (i, item) in items.into_iter().enumerate() { inner.push(item.doc); + if self.inline_comments(&item.before_sep, &mut inner) { + inner.push(Doc::HardLine); + } if i < last { inner.push(text(",")); } else { inner.push(text(";")); } if let Some(tr) = item.trailing { - inner.push(text(format!(" {tr}"))); + inner.push(text(" ")); + inner.push(self.comment(&tr)); if i < last { inner.push(Doc::HardLine); } @@ -988,11 +1038,15 @@ impl<'a> Fmt<'a> { for (i, instance) in inst.instances.iter().enumerate() { inner.extend(self.leading(&instance.meta)); inner.push(self.instance(instance)); + if self.inline_comments(&instance.meta.before_sep, &mut inner) { + inner.push(Doc::HardLine); + } if i < last { inner.push(text(",")); } if let Some(tr) = &instance.meta.trailing { - inner.push(text(format!(" {tr}"))); + inner.push(text(" ")); + inner.push(self.comment(tr)); if i < last { inner.push(Doc::HardLine); } @@ -1072,11 +1126,16 @@ impl<'a> Fmt<'a> { docs.push(text(")")); concat(docs) } - Some(e) => concat(vec![ - text(format!(".{}(", c.name)), - group(vec![indent(vec![Doc::SoftLine, self.expr(e)]), Doc::SoftLine]), - text(")"), - ]), + Some(e) => { + let mut inner = vec![Doc::SoftLine, self.expr(e)]; + let ends_line = self.inline_comments(&c.close_comments, &mut inner); + let close = if ends_line { Doc::HardLine } else { Doc::SoftLine }; + concat(vec![ + text(format!(".{}(", c.name)), + group(vec![indent(inner), close]), + text(")"), + ]) + } } } @@ -1092,9 +1151,7 @@ impl<'a> Fmt<'a> { docs.push(text(name.clone())); docs.push(text(" ")); } - let items: Vec = - inst.args.iter().map(|a| ListItem::plain(self.expr(a))).collect(); - docs.push(self.delimited("(", items, ")", false)); + docs.push(self.expr_list("(", &inst.args, ")")); } docs.push(text(";")); concat(docs) @@ -1188,9 +1245,7 @@ impl<'a> Fmt<'a> { let mut item_docs = vec![self.case_labels(&item.labels)]; self.gen_block(&mut item_docs, &item.body); body.push(concat(item_docs)); - if let Some(tr) = &item.meta.trailing { - body.push(text(format!(" {tr}"))); - } + body.extend(self.trailing(&item.meta)); } body.extend(self.dangling(&g.dangling)); docs.push(indent(body)); @@ -1392,10 +1447,21 @@ impl<'a> Fmt<'a> { Some(SensSep::Or) => parts.push(text(" or ")), None => {} } + for c in &i.meta.leading { + parts.push(self.comment(c)); + parts.push(if is_line_comment(&c.text) { + Doc::HardLine + } else { + text(" ") + }); + } if let Some(e) = &i.edge { parts.push(text(format!("{e} "))); } parts.push(self.expr(&i.expr)); + if self.inline_comments(&i.meta.before_sep, &mut parts) { + parts.push(Doc::HardLine); + } } let mut docs = vec![text("@(")]; docs.push(group(vec![indent(vec![Doc::SoftLine, concat(parts)]), Doc::SoftLine])); @@ -1441,9 +1507,7 @@ impl<'a> Fmt<'a> { body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); body.extend(self.leading(&item.meta)); body.push(self.case_item(item)); - if let Some(tr) = &item.meta.trailing { - body.push(text(format!(" {tr}"))); - } + body.extend(self.trailing(&item.meta)); } body.extend(self.dangling(dangling)); docs.push(indent(body)); @@ -1617,9 +1681,7 @@ impl<'a> Fmt<'a> { let mut meta_docs = self.leading(&els.meta); docs.append(&mut meta_docs); docs.push(self.if_stmt(eq, ec, et, ee)); - if let Some(tr) = &els.meta.trailing { - docs.push(text(format!(" {tr}"))); - } + docs.extend(self.trailing(&els.meta)); } else { docs.push(self.stmt_as_body(text(""), els)); } @@ -1635,7 +1697,9 @@ impl<'a> Fmt<'a> { if labels.is_empty() { return text("default:"); } - let plain = labels.iter().all(|l| l.meta.leading.is_empty() && l.meta.trailing.is_none()); + let plain = labels.iter().all(|l| { + l.meta.leading.is_empty() && l.meta.before_sep.is_empty() && l.meta.trailing.is_none() + }); if plain { let docs: Vec = labels.iter().map(|l| self.expr(&l.expr)).collect(); return concat(vec![concat(join(docs, text(", "))), text(":")]); @@ -1651,12 +1715,19 @@ impl<'a> Fmt<'a> { docs.push(Doc::HardLine); } docs.push(self.expr(&l.expr)); + let ends_line = self.inline_comments(&l.meta.before_sep, &mut docs); if i < last { + if ends_line { + docs.push(Doc::HardLine); + } docs.push(text(",")); + } else if ends_line { + docs.push(Doc::HardLine); } if let Some(tr) = &l.meta.trailing { - docs.push(text(format!(" {tr}"))); - if i == last && is_line_comment(tr) { + docs.push(text(" ")); + docs.push(self.comment(tr)); + if i == last && is_line_comment(&tr.text) { docs.push(Doc::HardLine); } } @@ -1736,16 +1807,12 @@ impl<'a> Fmt<'a> { concat(vec![self.expr(base), text(format!("::{name}"))]) } ExprKind::Concat(items) => self.expr_list("{", items, "}"), - ExprKind::Repl { count, inner } => { - let inner_docs: Vec = inner.iter().map(|i| self.expr(i)).collect(); - concat(vec![ - text("{"), - self.expr(count), - text("{"), - concat(join(inner_docs, text(", "))), - text("}}"), - ]) - } + ExprKind::Repl { count, inner } => concat(vec![ + text("{"), + self.expr(count), + self.expr_list("{", inner, "}"), + text("}"), + ]), ExprKind::Paren { inner, before, after } => { if before.is_empty() && after.is_empty() { return self.parens(inner); diff --git a/crates/vlog_formatter/tests/cases/comments.cases b/crates/vlog_formatter/tests/cases/comments.cases index 06bef91..0a23195 100644 --- a/crates/vlog_formatter/tests/cases/comments.cases +++ b/crates/vlog_formatter/tests/cases/comments.cases @@ -699,3 +699,284 @@ module m (a); input a /* async */; parameter int W = 8 /* width */; endmodule +==== +# a comment before the comma of a port list stays before it +module m (input logic a /* first */, input logic b); +endmodule +---- +module m (input logic a /* first */, input logic b); +endmodule +==== +# a line comment before the comma of a port list puts the comma on the next line +module m (input logic aaa // why + , input logic b); +endmodule +---- +module m ( + input logic aaa // why + , + input logic b +); +endmodule +==== +# a comment before the comma of a parameter port list stays before it +module m #(parameter int A = 1 /* lo */, parameter int B = 2) (); +endmodule +---- +module m #(parameter int A = 1 /* lo */, parameter int B = 2) (); +endmodule +==== +# a comment before the comma of a named connection list stays before it +module m; +sub u (.a(x) /* one */, .b(y)); +endmodule +---- +module m; + sub u (.a(x) /* one */, .b(y)); +endmodule +==== +# a comment before the comma of an ordered connection list stays before it +module m; +sub u (x /* one */, y); +endmodule +---- +module m; + sub u (x /* one */, y); +endmodule +==== +# a comment before the closing paren of an ordered connection list stays inside it +module m; +sub u (x, y /* last */); +endmodule +---- +module m; + sub u ( + x, + y /* last */ + ); +endmodule +==== +# a comment inside a connection's own parens stays inside them +module m; +sub u (.a(x /* verilator lint_off */), .b(y)); +endmodule +---- +module m; + sub u (.a(x /* verilator lint_off */), .b(y)); +endmodule +==== +# a comment before the comma of an assignment pattern stays before it +module m; +localparam logic [1:0] P = '{1'b0 /* lo */, 1'b1}; +endmodule +---- +module m; + localparam logic [1:0] P = '{1'b0 /* lo */, 1'b1}; +endmodule +==== +# a comment before the comma of a concatenation stays before it +module m; +assign y = {a /* hi */, b}; +endmodule +---- +module m; + assign y = {a /* hi */, b}; +endmodule +==== +# a comment before the comma of a declarator list stays before it +module m; +logic a /* one */, b; +endmodule +---- +module m; + logic a /* one */, b; +endmodule +==== +# a comment before the comma of an enum member list stays before it +module m; +typedef enum logic {A /* zero */, B} e_t; +endmodule +---- +module m; + typedef enum logic {A /* zero */, B} e_t; +endmodule +==== +# a comment before the closing brace of an enum member list stays inside it +module m; +typedef enum logic {A, B +// that is all +} e_t; +endmodule +---- +module m; + typedef enum logic { + A, + B + // that is all + } e_t; +endmodule +==== +# a comment before the comma of a function argument list stays before it +module m; +function int f(input int a /* lhs */, input int b); +return a + b; +endfunction +endmodule +---- +module m; + function int f(input int a /* lhs */, input int b); + return a + b; + endfunction +endmodule +==== +# two leading comments separated by one blank line keep exactly one +module m; +// first + +// second +wire a; +endmodule +---- +module m; + // first + + // second + wire a; +endmodule +==== +# several blank lines between leading comments still collapse to one +module m; +// a + + + +// b +wire x; +endmodule +---- +module m; + // a + + // b + wire x; +endmodule +==== +# a comment inside a replication stays inside it +module m; +assign y = {2{a /* why */, b}}; +endmodule +---- +module m; + assign y = {2{a /* why */, b}}; +endmodule +==== +# a comment inside a gate instance argument list stays inside it +module m; +and g1 (y /* out */, a, b); +endmodule +---- +module m; + and g1 (y /* out */, a, b); +endmodule +==== +# a comment between a continuous assignment's value and its semicolon stays before it +module m; +assign y = a /* verilator split_var */ ; +endmodule +---- +module m; + assign y = a /* verilator split_var */; +endmodule +==== +# a comment next to an operator inside a bracket expression stays next to it +module m; +assign y = x[a /* plus */ + b]; +endmodule +---- +module m; + assign y = x[a /* plus */ + b]; +endmodule +==== +# a comment between two header imports stays between them +module m import a::*; +// then the other one +import b::t; +(input x); +endmodule +---- +module m + import a::*; + // then the other one + import b::t; +(input x); +endmodule +==== +# a trailing comment on a header import stays on its line +module m import a::*; // the first +import b::t; (input x); +endmodule +---- +module m + import a::*; // the first + import b::t; +(input x); +endmodule +==== +# a comment inside an event list stays on its side of the separator +module m; +always @(posedge clk /* the clock */ or negedge rst_n) q <= d; +endmodule +---- +module m; + always @(posedge clk /* the clock */ or negedge rst_n) q <= d; +endmodule +==== +# a comment after an event list separator stays after it +module m; +always @(posedge clk, /* and */ negedge rst_n) q <= d; +endmodule +---- +module m; + always @(posedge clk, /* and */ negedge rst_n) q <= d; +endmodule +==== +# a comment before the closing paren of a parameter override list stays inside it +module m; +sub #(.A(1), .B(2) +// no more +) u (.c(z)); +endmodule +---- +module m; + sub #( + .A(1), + .B(2) // no more + ) u (.c(z)); +endmodule +==== +# a comment between two case labels stays between them +module m; +always_comb case (x) +A /* first */, B: y = 1; +default: y = 0; +endcase +endmodule +---- +module m; + always_comb + case (x) + A /* first */, + B: + y = 1; + default: y = 0; + endcase +endmodule +==== +# a comment inside an inside-set stays inside it +module m; +assign y = a inside {1 /* one */, 2}; +endmodule +---- +module m; + assign y = a inside {1 /* one */, 2}; +endmodule diff --git a/crates/vlog_formatter/tests/verification.rs b/crates/vlog_formatter/tests/verification.rs index 5774c2a..9d77772 100644 --- a/crates/vlog_formatter/tests/verification.rs +++ b/crates/vlog_formatter/tests/verification.rs @@ -349,3 +349,85 @@ fn two_line_comments_merged_onto_one_line_are_still_rejected() { let output = "module m;\n assign y = a && // one // two\n b;\nendmodule\n"; expect_divergence(input, output); } + +// -------------------------------------------------------------------------- +// comments-round (2026-08-19): the comment-attachment gaps closed this round +// were all fixed by giving the AST somewhere to keep the comment +// (`Meta::before_sep` and friends), not by teaching `verify.rs` to forgive +// the motion. These are the attack tests for that: every "corrupted" output +// below is what the fix would look like if it had been made in the safety net +// instead, and every one of them must still be rejected. Per CLAUDE.md hard +// invariant #4 — the normalizations are unchanged, so none of this is +// required, and it is here precisely so a future shortcut fails loudly. + +#[test] +fn a_comment_moved_across_a_list_comma_is_still_rejected() { + // The bulk of this round: `a /* c */,` reprinted as `a, /* c */`. Every + // token survives and the comment survives; only its position in the + // stream changes, so nothing but stream order can catch it. + let input = "module m (input logic a /* first */, input logic b);\nendmodule\n"; + let output = "module m (input logic a, /* first */ input logic b);\nendmodule\n"; + expect_divergence(input, output); + // ...and a normalization forgiving one direction must not forgive the + // other either. + expect_divergence(output, input); +} + +#[test] +fn a_comment_moved_out_of_a_connections_parens_is_still_rejected() { + // `.data_i (x /* verilator lint_off */)` printed with the comment after + // the `)` puts the pragma outside the region it names. + let input = "module m;\n sub u (.a(x /* lint_off */), .b(y));\nendmodule\n"; + let output = "module m;\n sub u (.a(x) /* lint_off */, .b(y));\nendmodule\n"; + expect_divergence(input, output); +} + +#[test] +fn a_comment_moved_out_of_a_replication_is_still_rejected() { + // `Expr::Repl` printed its elements with a fixed `", "` join, so a comment + // inside it had nowhere to go and drifted past the closing braces. + let input = "module m;\n assign y = {2{a /* why */, b}};\nendmodule\n"; + let output = "module m;\n assign y = {2{a, b}}; /* why */\nendmodule\n"; + expect_divergence(input, output); +} + +#[test] +fn a_comment_moved_across_an_event_list_separator_is_still_rejected() { + // The event-list twin of the comma case: `or` is the separator here, and + // the comment must stay on the side of it that the source wrote. + let input = + "module m;\n always @(posedge clk /* the clock */ or negedge rst_n) q <= d;\nendmodule\n"; + let output = + "module m;\n always @(posedge clk or /* the clock */ negedge rst_n) q <= d;\nendmodule\n"; + expect_divergence(input, output); + expect_divergence(output, input); +} + +#[test] +fn a_comment_moved_between_two_header_imports_is_still_rejected() { + // Header imports had no `Meta` at all, so a comment between two of them + // fell through to the next construct. + let input = "module m\n import a::*;\n // then the other one\n import b::t;\n(input x);\nendmodule\n"; + let output = + "module m\n import a::*;\n import b::t;\n// then the other one\n(input x);\nendmodule\n"; + expect_divergence(input, output); +} + +#[test] +fn a_dropped_enum_dangling_comment_is_still_rejected() { + // `EnumType::dangling` was collected by the parser and never printed: a + // dropped comment, which is hard invariant #3 and must stay a refusal. + let input = "module m;\n typedef enum logic {A, B\n // that is all\n } e_t;\nendmodule\n"; + let output = "module m;\n typedef enum logic {A, B} e_t;\nendmodule\n"; + expect_divergence(input, output); +} + +#[test] +fn a_line_comment_swallowing_a_list_comma_is_still_rejected() { + // `before_sep` prints the comma after the comment; a line comment runs to + // end of line, so putting the comma on the same line deletes it. The + // formatter emits a hard line for exactly this reason. + let input = "module m (input logic a // why\n , input logic b);\nendmodule\n"; + let output = "module m (\n input logic a // why ,\n input logic b\n);\nendmodule\n"; + expect_divergence(input, output); +} diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index b67f5a8..6d98897 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -16,7 +16,17 @@ use crate::token::Comment; #[derive(Debug, Clone, Default)] pub struct Meta { pub leading: Vec, - pub trailing: Option, + /// The comment written *after* the node and the separator that closes it + /// (`,` or `;`), on the same line. Several are merged into one, joined by + /// a space; the merged value keeps the first one's position and spans + /// from the first byte of the first to the last byte of the last. + pub trailing: Option, + /// Comments written *between* the node and the separator that follows it + /// (`element /* c */,`). They print on the node's side of the separator, + /// which is where the source put them — printing them after it moves a + /// comment across a token and the safety net rejects the output. Empty + /// for a node no separator follows. + pub before_sep: Vec, pub blank_before: bool, /// Attribute instances `(* ... *)` that preceded the node, verbatim. pub attrs: Vec, @@ -119,11 +129,10 @@ pub enum ItemKind { pub struct Module { pub kw: String, pub name: String, - /// One entry per `import` statement written in the header, each holding - /// that statement's comma-separated paths. A header may write several - /// (`module m import a::*; import b::t; (...)`), and merging them into one - /// statement would replace a `;` with a `,`. - pub imports: Vec>, + /// One entry per `import` statement written in the header. A header may + /// write several (`module m import a::*; import b::t; (...)`), and merging + /// them into one statement would replace a `;` with a `,`. + pub imports: Vec, /// `None` when the header wrote no `#( ... )` at all; an empty `Some` is a /// written-but-empty `#()`, which must be printed back. pub param_ports: Option>, @@ -137,6 +146,16 @@ pub struct Module { pub end_label: Option, } +/// One `import` statement in a module header, with the comments written +/// around it. A header import is not an [`Item`], so it needs its own place +/// to keep them. +#[derive(Debug)] +pub struct HeaderImport { + pub meta: Meta, + /// The comma-separated paths of this one statement. + pub paths: Vec, +} + #[derive(Debug)] pub enum PortList { /// No port list at all: `module m;` @@ -331,6 +350,10 @@ pub enum SensList { #[derive(Debug)] pub struct SensItem { + /// Comments written around this item: `leading` before it (after the `(` + /// or the separator), `before_sep` between it and the separator that + /// follows — or the closing `)` for the last item. + pub meta: Meta, /// The separator written before this item; `None` on the first item. pub sep: Option, pub edge: Option, @@ -390,6 +413,10 @@ pub struct Connection { /// `None` for `.name` (implicit) and `.*`; `Some` for `.name(expr)`. /// An explicitly empty connection `.name()` is `Some(Expr::Empty)`. pub expr: Option, + /// Comments written between the value and the connection's own `)` + /// (`.data_i (x /* verilator lint_off */)`). Printed back inside the + /// parens: after them they would sit in the enclosing list instead. + pub close_comments: Vec, /// Code extent of the connection. pub span: TextRange, } @@ -406,7 +433,7 @@ pub struct GateInstantiation { pub struct GateInstance { pub meta: Meta, pub name: Option, - pub args: Vec, + pub args: Vec, /// Code extent of the gate instance. pub span: TextRange, } @@ -422,7 +449,9 @@ pub struct GenIf { #[derive(Debug)] pub enum GenElse { - If(Meta, GenIf), + /// `else if`: boxed because a `Meta` plus a whole `GenIf` inline makes + /// this variant several times the size of `Block`. + If(Meta, Box), Block(GenBlock), } @@ -726,7 +755,9 @@ pub enum ExprKind { Concat(Vec), Repl { count: Box, - inner: Vec, + /// Elements carry their comments the way a concatenation's do, so a + /// comment inside a replication stays inside it. + inner: Vec, }, Paren { inner: Box, diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index 4198680..d8e3ac8 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -525,16 +525,48 @@ impl<'a> Parser<'a> { leading.append(&mut tok.leading); let blank_before = leading.first().map(|c| c.blank_before).unwrap_or(self.tokens[self.pos].blank_before); - Meta { leading, trailing: None, blank_before, attrs: Vec::new() } + Meta { leading, blank_before, ..Meta::default() } } /// Harvest trailing comments accumulated since the last harvest. - fn take_trailing(&mut self) -> Option { - if self.pending_trailing.is_empty() { - None - } else { - Some(self.pending_trailing.drain(..).map(|c| c.text).collect::>().join(" ")) + /// + /// Several comments merge into one, joined by a space, as they always + /// have; the result keeps the first one's line/column (what the formatter + /// re-indents a multi-line one by) and spans the whole run. + fn take_trailing(&mut self) -> Option { + let mut drained = self.pending_trailing.drain(..); + let mut first = drained.next()?; + for rest in drained { + first.text.push(' '); + first.text.push_str(&rest.text); + first.span.end = rest.span.end; } + Some(first) + } + + /// Move the comments written before the separator at the cursor onto the + /// element just parsed, so they print on the element's side of it. + /// + /// A no-op when the cursor is not on that separator: the comments then + /// belong to the enclosing list's dangling bucket (before its closing + /// bracket) or to the next construct, and stealing them here would move + /// them backwards across a token. + fn take_before_sep(&mut self, meta: &mut Meta, sep: &str) { + if !self.cur().is_sym(sep) { + return; + } + self.take_before(meta); + } + + /// The unconditional half of [`Parser::take_before_sep`], for callers that + /// recognize their own separator: an event list separates with a `,` or + /// with the `or` keyword, and both spellings occur in one list. + fn take_before(&mut self, meta: &mut Meta) { + if let Some(c) = meta.trailing.take() { + meta.before_sep.push(c); + } + let mut around = self.take_dangling(); + meta.before_sep.append(&mut around); } /// Comments sitting right before a closing keyword (`end`, `endmodule`, @@ -558,10 +590,14 @@ impl<'a> Parser<'a> { /// Continue a comma-separated expression list whose first element is /// already parsed, harvesting the comment written after each comma and - /// the one before the closing bracket. - fn parse_expr_list(&mut self, first: ExprItem) -> PResult> { + /// the ones before `close` — the token that ends the list, which the + /// caller consumes (`}`, `)`, or the `:` of a case label list). + fn parse_expr_list(&mut self, first: ExprItem, close: &str) -> PResult> { let mut items = vec![first]; loop { + if let Some(last) = items.last_mut() { + self.take_before_sep(&mut last.meta, ","); + } let more = self.eat_sym(","); if let Some(last) = items.last_mut() { if last.meta.trailing.is_none() { @@ -569,6 +605,9 @@ impl<'a> Parser<'a> { } } if !more { + if let Some(last) = items.last_mut() { + self.take_before_sep(&mut last.meta, close); + } return Ok(items); } items.push(self.parse_expr_item()?); @@ -909,7 +948,10 @@ impl<'a> Parser<'a> { let name = self.expect_ident()?; let mut imports = Vec::new(); while self.cur().is_kw("import") { - imports.push(self.parse_import_list()?); + let mut meta = self.take_meta(); + let paths = self.parse_import_list()?; + meta.trailing = self.take_trailing(); + imports.push(HeaderImport { meta, paths }); } let mut param_ports = None; let mut param_dangling = Vec::new(); @@ -920,6 +962,9 @@ impl<'a> Parser<'a> { if !self.cur().is_sym(")") { loop { list.push(self.parse_param_port()?); + if let Some(last) = list.last_mut() { + self.take_before_sep(&mut last.meta, ","); + } if !self.eat_sym(",") { break; } @@ -1015,6 +1060,9 @@ impl<'a> Parser<'a> { let mut ports = Vec::new(); loop { ports.push(self.parse_ansi_port()?); + if let Some(last) = ports.last_mut() { + self.take_before_sep(&mut last.meta, ","); + } if !self.eat_sym(",") { break; } @@ -1041,6 +1089,7 @@ impl<'a> Parser<'a> { let mut meta = self.take_meta(); let name = self.expect_ident()?; let span = self.span_from(start); + self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); meta.trailing = self.take_trailing(); ports.push(NonAnsiPort { meta, name, span }); @@ -1169,6 +1218,7 @@ impl<'a> Parser<'a> { let unpacked = self.parse_dims()?; let init = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; let span = self.span_from(start); + self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); // Harvested on the last declarator too: a comment written before // the `;` (`logic x /* verilator split_var */;`) belongs to the @@ -1250,6 +1300,7 @@ impl<'a> Parser<'a> { // Enum member ranges (`VAL[4]`) are rare; unsupported. let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; let span = self.span_from(start); + self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); meta.trailing = self.take_trailing(); members.push(EnumMember { meta, name, value, span }); @@ -1328,6 +1379,11 @@ impl<'a> Parser<'a> { let rhs_comments = self.take_around(mark); let rhs = self.parse_expr()?; let span = self.span_from(start); + // The last pair's separator is the statement's `;`, so a comment + // written before it (`assign y = a /* c */;`) belongs on the + // value's side of it, not after it. + self.take_before_sep(&mut meta, ","); + self.take_before_sep(&mut meta, ";"); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); @@ -1387,6 +1443,9 @@ impl<'a> Parser<'a> { if !self.cur().is_sym(")") { loop { list.push(self.parse_connection()?); + if let Some(last) = list.last_mut() { + self.take_before_sep(&mut last.meta, ","); + } if !self.eat_sym(",") { break; } @@ -1397,6 +1456,10 @@ impl<'a> Parser<'a> { } } } + // Comments before the `)` of the override list belong inside it. + if let Some(last) = list.last_mut() { + self.take_before_sep(&mut last.meta, ")"); + } self.expect_sym(")")?; params = Some(list); } @@ -1410,6 +1473,7 @@ impl<'a> Parser<'a> { let conns = self.parse_connections()?; self.expect_sym(")")?; let span = self.span_from(start); + self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); @@ -1431,6 +1495,9 @@ impl<'a> Parser<'a> { let mut conns = Vec::new(); loop { conns.push(self.parse_connection()?); + if let Some(last) = conns.last_mut() { + self.take_before_sep(&mut last.meta, ","); + } if !self.eat_sym(",") { break; } @@ -1440,11 +1507,10 @@ impl<'a> Parser<'a> { } } } - // Comment on the closing-paren line belongs to the last conn. + // Comments before the closing `)` belong to the last conn: after + // it they would sit outside the connection list entirely. if let Some(last) = conns.last_mut() { - if last.meta.trailing.is_none() { - last.meta.trailing = self.take_trailing(); - } + self.take_before_sep(&mut last.meta, ")"); } Ok(Connections::Named(conns)) } else { @@ -1460,8 +1526,9 @@ impl<'a> Parser<'a> { // An omitted connection (`u (a, , c)`) consumed no token, so // this is the empty span where it would have started. let span = self.span_from(start); - let more = self.eat_sym(","); let mut meta = meta; + self.take_before_sep(&mut meta, ","); + let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); } @@ -1470,6 +1537,9 @@ impl<'a> Parser<'a> { break; } } + if let Some(last) = conns.last_mut() { + self.take_before_sep(&mut last.meta, ")"); + } Ok(Connections::Ordered(conns)) } } @@ -1482,11 +1552,18 @@ impl<'a> Parser<'a> { if self.eat_sym(".") { if self.eat_sym("*") { let span = self.span_from(start); - return Ok(Connection { meta, name: "*".to_string(), expr: None, span }); + return Ok(Connection { + meta, + name: "*".to_string(), + expr: None, + close_comments: Vec::new(), + span, + }); } let name = self.expect_ident()?; let mark = self.pending_trailing.len(); let paren_start = self.here(); + let mut close_comments = Vec::new(); let expr = if self.eat_sym("(") { if self.cur().is_sym(")") { // `.name(/* unused */)`: the comments were written inside @@ -1495,7 +1572,11 @@ impl<'a> Parser<'a> { self.bump(); Some(self.expr_at(paren_start, ExprKind::Empty(inside))) } else { + let value_mark = self.pending_trailing.len(); let e = self.parse_expr_or_type()?; + // `.name(x /* c */)`: written inside the parens, so it is + // printed inside them too. + close_comments = self.take_around(value_mark); self.expect_sym(")")?; Some(e) } @@ -1504,12 +1585,18 @@ impl<'a> Parser<'a> { }; let span = self.span_from(start); meta.trailing = self.take_trailing(); - Ok(Connection { meta, name, expr, span }) + Ok(Connection { meta, name, expr, close_comments, span }) } else { let e = self.parse_expr_or_type()?; let span = self.span_from(start); meta.trailing = self.take_trailing(); - Ok(Connection { meta, name: String::new(), expr: Some(e), span }) + Ok(Connection { + meta, + name: String::new(), + expr: Some(e), + close_comments: Vec::new(), + span, + }) } } @@ -1542,15 +1629,12 @@ impl<'a> Parser<'a> { self.expect_sym("(")?; let mut args = Vec::new(); if !self.cur().is_sym(")") { - loop { - args.push(self.parse_expr()?); - if !self.eat_sym(",") { - break; - } - } + let first = self.parse_expr_item()?; + args = self.parse_expr_list(first, ")")?; } self.expect_sym(")")?; let span = self.span_from(start); + self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); @@ -1587,7 +1671,7 @@ impl<'a> Parser<'a> { let meta = self.take_meta(); self.bump(); if self.cur().is_kw("if") { - Some(Box::new(GenElse::If(meta, self.parse_gen_if()?))) + Some(Box::new(GenElse::If(meta, Box::new(self.parse_gen_if()?)))) } else { let _ = meta; Some(Box::new(GenElse::Block(self.parse_gen_block()?))) @@ -1629,7 +1713,7 @@ impl<'a> Parser<'a> { Vec::new() } else { let first = self.parse_expr_item()?; - let labels = self.parse_expr_list(first)?; + let labels = self.parse_expr_list(first, ":")?; self.expect_sym(":")?; labels }; @@ -1748,6 +1832,7 @@ impl<'a> Parser<'a> { let unpacked = self.parse_dims()?; let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; let span = self.span_from(start); + self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); meta.trailing = self.take_trailing(); args.push(TfArg { meta, dir, ty, name, unpacked, default, span }); @@ -2100,7 +2185,7 @@ impl<'a> Parser<'a> { Vec::new() } else { let first = self.parse_expr_item()?; - let labels = self.parse_expr_list(first)?; + let labels = self.parse_expr_list(first, ":")?; self.expect_sym(":")?; labels }; @@ -2178,7 +2263,12 @@ impl<'a> Parser<'a> { let start = self.here(); let name = self.expect_ident()?; let expr = self.expr_at(start, ExprKind::Ident(name)); - return Ok(SensList::List(vec![SensItem { sep: None, edge: None, expr }])); + return Ok(SensList::List(vec![SensItem { + meta: Meta::default(), + sep: None, + edge: None, + expr, + }])); } if self.cur().is_sym("(") && self.nth(1).is_sym("*") { // `@( /* c */ * /* d */ )`: the comments belong to the star, not @@ -2196,6 +2286,7 @@ impl<'a> Parser<'a> { let mut items = Vec::new(); let mut sep = None; loop { + let mut meta = self.take_meta(); let edge = { let t = self.cur(); if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") { @@ -2205,7 +2296,12 @@ impl<'a> Parser<'a> { } }; let expr = self.parse_expr()?; - items.push(SensItem { sep, edge, expr }); + // Comments written before the separator — either spelling — or + // before the closing `)` stay on this item's side of it. + if self.cur().is_sym(",") || self.cur().is_kw("or") || self.cur().is_sym(")") { + self.take_before(&mut meta); + } + items.push(SensItem { meta, sep, edge, expr }); // Both separators are legal in the same list; each is kept as // written so the formatter never rewrites one as the other. sep = if self.eat_sym(",") { @@ -2335,6 +2431,7 @@ impl<'a> Parser<'a> { self.parse_expr()? }; let item_span = self.span_from(item_start); + self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); @@ -2345,9 +2442,7 @@ impl<'a> Parser<'a> { } } if let Some(last) = ranges.last_mut() { - if last.meta.trailing.is_none() { - last.meta.trailing = self.take_trailing(); - } + self.take_before_sep(&mut last.meta, "}"); } self.expect_sym("}")?; self.link()?; @@ -2474,7 +2569,7 @@ impl<'a> Parser<'a> { let first_expr = self.parse_expr_or_type()?; let first = ExprItem { meta, expr: first_expr, span: self.span_from(arg_start) }; - args = self.parse_expr_list(first)?; + args = self.parse_expr_list(first, ")")?; } self.expect_sym(")")?; expr = self.expr_at(start, ExprKind::Call { callee: Box::new(expr), args }); @@ -2581,10 +2676,8 @@ impl<'a> Parser<'a> { if self.cur().is_sym("{") { // Replication {N{a, b}} self.bump(); - let mut inner = vec![self.parse_expr()?]; - while self.eat_sym(",") { - inner.push(self.parse_expr()?); - } + let inner_first = self.parse_expr_item()?; + let inner = self.parse_expr_list(inner_first, "}")?; self.expect_sym("}")?; self.expect_sym("}")?; return Ok(self.expr_at( @@ -2592,7 +2685,7 @@ impl<'a> Parser<'a> { ExprKind::Repl { count: Box::new(first.expr), inner }, )); } - let items = self.parse_expr_list(first)?; + let items = self.parse_expr_list(first, "}")?; self.expect_sym("}")?; Ok(self.expr_at(start, ExprKind::Concat(items))) } @@ -2615,6 +2708,7 @@ impl<'a> Parser<'a> { (None, key_or_val) }; let item_span = self.span_from(item_start); + self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); @@ -2625,9 +2719,7 @@ impl<'a> Parser<'a> { } } if let Some(last) = items.last_mut() { - if last.meta.trailing.is_none() { - last.meta.trailing = self.take_trailing(); - } + self.take_before_sep(&mut last.meta, "}"); } } self.expect_sym("}")?; @@ -3020,7 +3112,8 @@ mod tests { let file = parse_ok("module m\n import a::*;\n import b::t, c::u;\n(input clk);\nendmodule"); let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; - assert_eq!(m.imports, vec![vec!["a::*".to_string()], vec!["b::t".into(), "c::u".into()]]); + let paths: Vec<&[String]> = m.imports.iter().map(|i| &i.paths[..]).collect(); + assert_eq!(paths, vec![&["a::*".to_string()][..], &["b::t".into(), "c::u".into()][..]]); } #[test] @@ -3075,6 +3168,56 @@ mod tests { assert_eq!(comments.after.len(), 1, "one comment after the operator"); } + #[test] + fn a_comment_before_a_list_comma_lands_in_before_sep() { + let file = parse_ok("module m (input a /* pre */, /* post */ input b);\nendmodule"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let PortList::Ansi(ports) = &m.ports else { panic!("expected an ANSI port list") }; + assert_eq!(ports[0].meta.before_sep.len(), 1, "written before the comma"); + assert_eq!(ports[0].meta.before_sep[0].text, "/* pre */"); + let trailing = ports[0].meta.trailing.as_ref().expect("written after the comma"); + assert_eq!(trailing.text, "/* post */"); + } + + #[test] + fn a_comment_after_the_last_element_is_not_a_before_sep_comment() { + // No separator follows, so the comment stays where it always was — + // this is the case the whole existing suite pins, and the harvest must + // not start stealing it. + let file = parse_ok("module m (input a /* tail */);\nendmodule"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let PortList::Ansi(ports) = &m.ports else { panic!("expected an ANSI port list") }; + assert!(ports[0].meta.before_sep.is_empty(), "nothing separates it from the `)`"); + assert_eq!(ports[0].meta.trailing.as_ref().expect("a trailing comment").text, "/* tail */"); + } + + #[test] + fn a_trailing_comment_carries_its_own_span() { + // The handshake `docs/features/format-fences/README.md` asked for: a + // same-line comment now has a byte offset, so a fence written there + // can be located in the source. + let src = "module m;\n wire a; // vfmt: off\nendmodule\n"; + let file = parse_ok(src); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let trailing = m.items[0].meta.trailing.as_ref().expect("a trailing comment"); + assert_eq!(&src[trailing.span.start as usize..trailing.span.end as usize], "// vfmt: off"); + assert_eq!((trailing.line, trailing.col), (2, 11)); + } + + #[test] + fn several_trailing_comments_merge_into_one_spanning_run() { + let src = "module m;\n wire a; /* one */ /* two */\nendmodule\n"; + let file = parse_ok(src); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let trailing = m.items[0].meta.trailing.as_ref().expect("a trailing comment"); + assert_eq!(trailing.text, "/* one */ /* two */"); + assert_eq!( + &src[trailing.span.start as usize..trailing.span.end as usize], + "/* one */ /* two */", + "the span runs from the first comment to the last" + ); + } + // ------------------------------------------------------------------ // Error recovery // ------------------------------------------------------------------ diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index 57c1f44..3fc7fa4 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -420,7 +420,8 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { for i in &g.instances { assert_inside(src, "gate instance", i.span, here); for a in &i.args { - check_expr(src, a, i.span); + assert_inside(src, "element", a.span, i.span); + check_expr(src, &a.expr, i.span); } } } @@ -623,7 +624,8 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) { ExprKind::Repl { count, inner } => { check_expr(src, count, here); for i in inner { - check_expr(src, i, here); + assert_inside(src, "element", i.span, here); + check_expr(src, &i.expr, here); } } ExprKind::AssignPattern(items) => { diff --git a/docs/features/comments-round/README.md b/docs/features/comments-round/README.md new file mode 100644 index 0000000..fa9ec79 --- /dev/null +++ b/docs/features/comments-round/README.md @@ -0,0 +1,548 @@ +# comments-round + +## Goal + +Close the comment-attachment gaps left open after `corpus-bugs`: a comment +written inside a list — a port list, a parameter list, a connection list, an +assignment pattern — was printed on the *wrong side of the separator*, so the +safety net refused the file (exit 2, nothing written). At corpus scale the +`format-fences` QA round measured that as 112 of 1 868 injection trials. The +same round found a second, quieter bug: two leading comments separated by one +blank line came out separated by *two*, because `Fmt::leading` emitted a +`HardLine` after each comment and then a `BlankLine` before the next. This +round fixes both, delivers the `Meta.trailing` span the `format-fences` +Handshake asked for, and takes as many of the documented expression refusals +as could be fixed by giving the AST somewhere to keep the comment. **Nothing +in `verify.rs` was touched**: every fix makes the comment survive *in place*, +none makes the net forgive its loss. + +## Assumptions + +- **A comment belongs on the side of the separator the author wrote it on.** + `a /* c */,` and `a, /* c */` are different token streams and mean different + things to a `verilator lint_off` pragma. Guessing one spelling for both is + what the net was rejecting; the parser now records which one it saw. +- **"No separator follows" is not the same as "a separator follows".** The + harvest that moves comments to `Meta::before_sep` is a no-op unless the + cursor is actually on the separator, so a comment after the *last* element + keeps landing in the bucket it always landed in (`trailing`, or the list's + `dangling`). That is what makes the existing suite show zero churn. +- **A line comment runs to end of line, so the separator that follows it goes + on the next one.** `a // why` ⏎ `,` is ugly and faithful; `a // why ,` + would delete the comma into the comment. Every emitter of `before_sep` goes + through `Fmt::inline_comments`, which already had this rule for binary and + ternary comments. +- **A merged trailing comment keeps the first comment's position.** Several + same-line trailing comments still merge into one text joined by a space, as + they always have; the merged `Comment` carries the first one's `line`/`col` + (what re-indenting a multi-line one needs) and a span running from the first + byte of the first to the last byte of the last. +- **Comments are compared by text in stream order**, so a fix is correct + exactly when the comment is printed lexically between the same two tokens it + sat between in the input. Every case in this round is checked that way by + `format_source` itself, not by eye. +- **Bracket interiors that print compactly still have no comment slot.** + `x[a : b]`, `[7:0]` and the two ends of `x[...]` are printed by + `Fmt::expr_compact` / `Fmt::dim` from nodes (`Dim`, `ExprKind::Range`, + `ExprKind::Index`) that carry no comments at all. Those stay refusals — see + Status / TODO. + +## Handshakes + +**Changed in `vlog_parser::ast` (consumed by `vlog_formatter::format`):** + +| item | before | after | +|---|---|---| +| `Meta::trailing` | `Option` | `Option` — the fences Handshake. A same-line trailing comment now carries `line`/`col`/`span`, so a fence written there can be located in the source. Text callers read `.text`. | +| `Meta` | — | new `before_sep: Vec`: comments written *between* the node and the separator that follows it. Empty when no separator follows, which is every node that is not a list element. | +| `ExprKind::Repl::inner` | `Vec` | `Vec`, so a replication's elements carry comments like a concatenation's. | +| `GateInstance::args` | `Vec` | `Vec`, same reason. | +| `Module::imports` | `Vec>` | `Vec`; new `struct HeaderImport { meta, paths }`. A header import is not an `Item`, so it had nowhere to keep a comment. | +| `Connection` | — | new `close_comments: Vec`: comments between the value and the connection's own `)` (`.data_i (x /* lint_off */)`). | +| `SensItem` | `{ sep, edge, expr }` | `+ meta: Meta` — comments around one event-list element, `before_sep` covering both separator spellings (`,` and `or`) and the closing `)`. | +| `GenElse::If` | `If(Meta, GenIf)` | `If(Meta, Box)` — `Meta` grew by one `Vec`, which re-tripped `clippy::large_enum_variant` on this enum. Purely a size fix; the variant was already reached through an `Option>`, so root-to-leaf depth is unchanged. | +| `Parser::parse_expr_list` | `(first)` | `(first, close)` — the token that ends the list (`}`, `)`, or the `:` of a case-label list), so the comments before it can be harvested onto the last element instead of drifting past it. | + +New parser helpers: `Parser::take_before_sep(meta, sep)` (a no-op unless the +cursor is on `sep`) and its unconditional half `Parser::take_before(meta)`, +for the event list, which separates with a `,` *or* with the `or` keyword. + +New formatter helper: `Fmt::inline_comments_spaced` — `inline_comments` plus +the space (or line break, after a line comment) that keeps the next token off +the last comment. + +**Delivered to `format-fences`:** the Handshake it filed — "a span on +`Meta.trailing`" — is now satisfied. That feature's README still documents +same-line fences as blocked on it; updating that README is the lead's call, +since it is another feature's document. `fence.rs` itself was not touched and +needs no change to keep working. + +**Consumed from `verify.rs`: nothing new. No normalization was added, +broadened or weakened** (`git diff --quiet -- crates/vlog_formatter/src/verify.rs` +exits 0), so CLAUDE.md hard invariant #4 does not bind this round. Seven new +**rejection** tests were added to `tests/verification.rs` anyway — one per +shape fixed here — each asserting that the "corrupted" output a widened +normalization would have forgiven is still rejected. The comma case asserts +both directions. + +**Recursion/chain budgets (`docs/features/recursion-limit/README.md`):** +unaffected. Nothing here recurses or builds a left-nested chain: `before_sep` +is a `Vec` beside two existing `Vec`s on `Meta`; `Repl::inner` and +`GateInstance::args` gain a wrapper struct at the same tree depth the elements +already sat at; `Box` adds an indirection inside a variant that was +already behind a `Box`, so the AST is one *pointer* deeper and zero *nodes* +deeper. + +**`line_starts_inside_string` is still the one in-string-break definition** — +untouched, and nothing here parses comment or string text. + +## Status / TODO + +- [x] **1. `Meta.trailing: Option` → `Option`** — the fences + Handshake. 14 formatter read sites migrated; several merge into one + `Comment` spanning the whole run. +- [x] **2. Comments between a list element and its separator** — + `Meta::before_sep`, harvested at every list kind: ANSI and non-ANSI port + lists, parameter ports, named and ordered connection lists, parameter + overrides, instance lists, declarators, enum members, struct members, + assignment patterns, concatenations, call arguments, `inside` sets, + case-label lists, function/task arguments, gate instances, event lists. +- [x] **2b. Comments before a list's closing bracket**, where the bucket was + missing: ordered connection lists, instantiation parameter overrides, + concatenations/`inside` sets/assignment patterns (`}`), case-label lists + (`:`), and a connection's own `)`. +- [x] **2c. `EnumType::dangling` was collected and never printed** — a + *dropped* comment (hard invariant #3), found while probing. Now printed + inside the braces via `delimited_dangling`. +- [x] **3. Double blank line between leading comments** — + `Fmt::leading_comments` emits the break before each comment instead of + after. Zero test churn; six corpus files became fixed points. +- [x] **4a. Comment inside a replication** (`{2{a /* c */, b}}`) — one of the + three documented survivors from `formatter-bug-fixes`. +- [x] **4b. Comment in a compactly-printed bracket expression** + (`x[a /* c */ + b]`) — the second documented survivor, for the + binary-operator position it was documented with. +- [x] **4c. Comment between a continuous assignment's value and its `;`** + (`assign y = a /* c */;`) — the third documented survivor. +- [x] **4d. Comment before the closing `}` of a concatenation** — the + `corpus-bugs` QA log's first non-blocking observation. +- [x] **4e. Comments between header imports** — the second one. +- [x] 26 new `.cases` entries, 7 rejection tests, 4 parser unit tests. +- [x] `cargo test --workspace` 229 passed (was 194 + the concurrent + define-table round's 25), clippy silent, fmt clean. +- [x] Corpus acceptance: 0 verification errors, 0 crashes, exit 0; six files + moved `would-reformat → ok-unchanged` and nothing else changed. +- [x] `TODO.md` §2: both comment items checked. +- [ ] **Not done, deliberately — bracket interiors.** `x[a /* c */]`, + `x[a /* c */ : b]` and `logic [7 /* c */ : 0]` still refuse. `Dim`, + `ExprKind::Range` and `ExprKind::Index` carry no comments and are + printed by `expr_compact`, which by contract introduces no line breaks; + giving them comment slots means deciding what a *broken* dimension looks + like, which is a layout design decision, not a plumbing one. 20 of the + 22 remaining probe positions are this shape. +- [ ] **Not done — comment before a *procedural* statement's `;`** + (`initial y = a /* c */;`). The continuous-assignment twin is fixed + here because `cont_assign` emits its own `;` in one place; a statement's + `;` is emitted by roughly ten different `StmtKind` arms, so this needs a + `Stmt`-level restructure rather than one field. +- [ ] **Not done — comment before a construct's opening bracket** + (`sub u /* c */ (...)`, `if /* c */ (c)`, `typedef struct packed /* c */ {`). + Each head position is its own slot; nobody writes comments there, and + the aggressive probe harness over-samples them badly (see Measurements). +- [ ] **Not done — comment before `else`**, and the bare name lists + (`genvar i /* c */, j;`, `import a::* /* c */, b::t;`, + `defparam u.a = 1 /* c */, u.b = 2;`), which are `Vec` / + `Vec<(Expr, Expr)>` with no `Meta` anywhere. All refusals, not + corruption. + +## Measurements + +Two injection harnesses, both run against the same pinned 820-file corpus with +the same seed on the pre-change binary (a `git worktree` at `HEAD` = 0ba29d4) +and on the working tree's binary. Scripts left in the session scratchpad +(`inject_lines.py`, `inject.py`, `probe/gaps.py`); none is checked in, since +none of the earlier rounds' harnesses were either. + +**1. Line-position injection (the TODO's methodology).** One padding comment +inserted on its own line, at the surrounding indentation, at a random line of +a random parsable corpus file; 1 868 trials, seed 20260819. + +| | before | after | +|---|---|---| +| usable trials | 1 861 | 1 861 | +| refused (exit 2, verification) | **42 (2.3%)** | **8 (0.4%)** | + +This is the number to compare against the TODO's "112 of 1 868 (~6%)". It is +lower than that on *both* sides because the original harness injected an +`off`/`on` *pair* — two comments per trial — and its script was never checked +in; treat 2.3% as this harness's own baseline, measured here, not as a +reproduction of the 6%. + +**2. Delimiter-position injection (deliberately adversarial).** A block +comment inserted immediately before or after a random `,` `(` `)` `{` `}` in +a corpus file — i.e. aimed squarely at the gaps, including ones no human +writes; 500 trials, seed 20260819. + +| | before | after | +|---|---|---| +| usable trials | 460 | 460 | +| refused | **282 (61.3%)** | **164 (35.7%)** | + +What is left is dominated by *head* positions rather than list gaps: 68 of the +remaining refusals are a comment written just before an opening `(` (between +an instance name and its connection list, between `if` and its condition), +which is the "not done" item above. + +**3. Exhaustive gap probe.** 26 hand-written templates — one per list kind +plus the documented expression refusals — with a line comment and a block +comment inserted at each of four gap positions (after the opening bracket, +before the separator, after the separator, before the closing bracket): 186 +inputs. + +| | before | after | +|---|---|---| +| refused | **90** | **22** | + +All 22 survivors are the two parked shapes: bracket interiors (20) and a +procedural statement's `;` (2). + +## Corpus results + +`./tools/corpus_check.sh corpus`, release build, corpus verified unmodified +afterwards. + +``` +outcome files share +-------------------- ----- ------- +ok-unchanged 8 1.0% (was 2) +would-reformat 460 56.1% (was 466) +parse-error 352 42.9% (unchanged) +verification-error 0 0.0% (unchanged) +other-error 0 0.0% +crash 0 0.0% +-------------------- ----- ------- +total 820 100.0% +``` + +Script exit status 0. The TSV was diffed **by path**, not by count: exactly +six files moved, all `would-reformat → ok-unchanged`, and no file changed to a +worse outcome. The six are `google_riscv-dv`'s `rv32*_instr.sv` / +`rv64b_instr.sv` family, and the reason is item 3 — each opens with a license +block comment, one blank line, then a banner comment, and the old code emitted +two blank lines between them. They are now fixed points on the first pass. + +The md5 is therefore **not** byte-identical to the `format-fences` baseline: +`3fab114f4f00626b254259e9dafe0ed7` → `aa982463f68c1a3568c02a0fc5e0c455`. The +baseline was reproduced exactly from the `HEAD` worktree binary first +(`3fab114f...`, bit for bit), so the whole delta is attributable, and it is six +lines of the TSV. The corpus repos are unmodified afterwards +(`git status --porcelain` clean apart from the pre-existing untracked +`.vfmt-corpus-rev` stamps). + +## Work log + +### 2026-08-19 — dev agent + +- Read `CLAUDE.md`, `README.md`, TODO.md §2, and the `format-fences`, + `formatter-bug-fixes` and `corpus-bugs` READMEs before touching code. + Baseline: `cargo test --workspace` 194 passed, clippy silent, fmt clean, + corpus TSV md5 `3fab114f4f00626b254259e9dafe0ed7` — reproduced from a + `git worktree` at `HEAD` so every later number has a real control. +- **Measured before designing.** Wrote the 26-template exhaustive gap probe + first (186 inputs, a comment in every gap of every list kind). The first run + reported 137/186 refusals, which was my harness's bug — a line comment + inserted with no newline after it swallows the rest of the line. Fixed, the + honest baseline is 90/186, and the shape of the failures made the whole + round obvious: **gap 1 — between an element and its comma — failed for 16 + of 26 list kinds, and almost nothing else did.** One bug, sixteen call + sites. +- **Root cause.** Every list harvests `meta.trailing = self.take_trailing()`, + and `Fmt::delimited` prints `trailing` *after* the comma. A comment written + before the comma and one written after it both land in `pending_trailing` + and are indistinguishable by the time they are harvested. The information + simply was not in the AST — the same diagnosis `corpus-bugs` reached for the + event-list separator. +- **Chose one field on `Meta` over a field on each of fourteen list-element + structs.** `before_sep` reads oddly on a `Stmt` (nothing separates a + statement), but the alternative is fourteen near-identical fields and + fourteen near-identical printers. Documented as "empty for a node no + separator follows" and left at that. +- **Chose "harvest only when the separator is actually there" over "harvest + always".** `take_before_sep` returns immediately unless the cursor is on the + separator, because the comments before a *closing bracket* belong to the + list's `dangling` bucket, which already renders them correctly. Harvesting + unconditionally would have re-routed every last-element comment through a + new path and churned the snapshots for no gain. This is the single decision + that kept the existing 194-test suite byte-for-byte green. +- **`Meta.trailing: Option` → `Option`** (item 1) turned out + to be the smaller half of the work: `take_trailing` merges the run into the + first comment (text joined by a space, span extended to the last), and the + formatter's 14 read sites became `self.comment(tr)` instead of + `format!(" {tr}")`. That is a real behavior change for a *multi-line* block + comment in trailing position — it is now re-indented by the same + dedent-then-reindent rule every other comment gets — and it is the right one + (`raw_lines` is a fixed point by construction). No case or fixture moved. +- **Item 3 was three lines and I nearly got it wrong.** `HardLine` followed by + `BlankLine` is three newlines, so the fix is to emit the break *before* each + comment rather than after, with one `HardLine` at the end for the node + itself. Wrote it, expected snapshot churn, got none — and then found the + churn where it actually was: six corpus files. That is a better test than + any fixture I would have written. +- **`clippy::large_enum_variant` fired on `GenElse` the moment `Meta` grew.** + Boxed `GenIf` inside `GenElse::If`, which is the fix clippy suggests and the + one `corpus-bugs` already used twice for the same reason. Noted in + Handshakes that this is a pointer, not a tree level. +- **Found a dropped comment while probing.** `EnumType::dangling` is filled by + the parser and was never read by the formatter — `typedef enum {A, B\n// c\n}` + loses the comment. It is hard invariant #3, caught only because the net + refused the file. Fixed by switching the enum to `delimited_dangling`, and + pinned by its own rejection test. +- **Order of the item-4 work was driven by the harness, not by the list.** + After items 1–3 the delimiter harness's remaining refusals were dominated by + four shapes, and three of them were cheap: a connection's own `)` + (28 trials), an instantiation `#(...)`'s closing `)` (12), the enum `}` (2). + The fourth — a comment before an opening bracket — is 68 trials and a + grab-bag of unrelated head positions; parked with a reason rather than + half-done. +- **Replication and gate arguments were one change each** once + `parse_expr_list` took its closing token as a parameter: both were + `Vec` printed with a fixed `", "` join, and both become `Vec` + printed through the existing `expr_list`. The visible consequence is that a + very long replication can now break one-element-per-line like a + concatenation; nothing in the corpus or the suite has one. +- **`expr_compact` got the comment path it was missing**, for the + binary-operator position only. When a comment is present the tight spelling + (`[WIDTH-1:0]`) gives its spaces back — there is nowhere else to put the + comment — and a line comment breaks the line. Without a comment the output + is byte-identical to before, which is why no dimension in the suite moved. +- **`verify.rs` was not touched and did not need to be.** Every refusal fixed + here was the formatter printing a comment somewhere the input did not put + it; the net was right every time. Added seven rejection tests anyway, each + crafted as "what this fix would look like if it had been done in the safety + net instead", so a future shortcut fails loudly. +- Did not touch `tools/`, `corpus/`, `crates/vfmt/`, `verify.rs`, or the + concurrent define-table round's files (`crates/vlog_parser/src/defines.rs`, + its tests, its `lib.rs` line, its `TODO.md` §6 entry). Did not run + `git commit`/`git push`. + +**Results:** `cargo test --workspace` **229 passed, 0 failed** (194 at the +start of the round plus 25 from the concurrent define-table round; this +round's own additions are +26 `.cases` entries inside `case_tables`, +7 +`tests/verification.rs` rejection tests, +4 `parser.rs` unit tests). +`cargo clippy --workspace --all-targets` silent. `cargo fmt --all --check` +clean. Every one of the 299 `.cases` inputs and all three +`tests/fixtures/*.sv` files re-run through **three** passes independently of +`cargo test`: zero drift, zero refusals. Fences: `tests/fences.rs` 6/6 and the +25 `fences.cases` entries unchanged and green, so no fenced region moved. + +Files touched: `crates/vlog_parser/src/{ast,parser}.rs`, +`crates/vlog_parser/tests/spans.rs` (two walker arms, for the +`Vec` → `Vec` changes), +`crates/vlog_formatter/src/format.rs`, +`crates/vlog_formatter/tests/cases/comments.cases`, +`crates/vlog_formatter/tests/verification.rs`, `TODO.md` (§2, two +checkboxes), this README. + +## QA log + +### 2026-08-19 — QA agent + +Read `CLAUDE.md`, this README, and the diff (`vlog_parser::{token,lexer, +parser,ast}`, `vlog_formatter::format`, `comments.cases`, `verification.rs`, +parser units) before touching anything. Verdict: **all 7 claims pass**, no +blocking findings, no should-fix findings. Two informational notes below. + +**Tooling (exact results).** +`cargo test --workspace`: **229 passed, 0 failed** (summed per-binary: +vfmt 40+21, vlog_formatter 8+1+4+6+2+39, vlog_parser 53+24+19+12 = 229). +`cargo clippy --workspace --all-targets`: silent. `cargo fmt --all --check`: +exit 0. `git diff --quiet -- crates/vlog_formatter/src/verify.rs`: exit 0 +(byte-identical to HEAD). Case-table count: 299 exactly (`grep -c '^# '` +across all `.cases` files sums to 299: comments.cases alone went 51→77, a ++26 delta — the task brief's "50→76" is off by one on both ends but the +delta matches exactly). + +**Claim 1 (Meta.trailing migration) — PASS.** Multi-line block comment as +trailing (`wire w; /* a\n b */`) re-indents and is stable across 3 passes. +Same construct inside a `// vfmt: off` fence stays byte-exact (diffed the +fenced lines directly against input) and still 3-pass stable — fences +correctly override the new re-indent behavior. Trailing runs +(block+block, block+line, block+block+line) reproduce the parser's +space-join merge (`take_trailing`, parser.rs:536-545) exactly, matching the +new unit tests `a_trailing_comment_carries_its_own_span` and +`several_trailing_comments_merge_into_one_spanning_run` +(parser.rs:3194-3219). EOF (with/without trailing newline, multi-line block +at true EOF) and CRLF all format cleanly and are 3-pass stable, no crash. +`GenElse::If`'s `Meta` param confirmed pre-existing via +`git diff -- crates/vlog_parser/src/parser.rs` (only `Box::new(...)` was +added around `self.parse_gen_if()?`; the `meta`/`_meta` handling itself is +untouched by this round) — the Handshakes table's "purely a size fix" claim +holds. + +**Claim 2 (before_sep mechanics) — PASS.** Code at parser.rs:554-559 confirms +the early return unless `self.cur().is_sym(sep)`. Ran an independently +authored 22-position probe (not the dev's 26 templates) covering ports, +params, named connections, a connection's own `)`, enum members/closing +`}`, patterns, concat, call args, case labels, event lists, and a nested +comment inside an instance array (`sub u [3:0] (.a(x /*c*/), ...)`) — all 22 +positions: comment present in a sane position, 3-pass byte-stable, no +crash. Also built one dense module combining all of the above at once (18 +comment markers in one file): all 18 present in the output, 3-pass stable. +See scratchpad `probe20.py` and `dense.sv`. + +**Claim 3 (`EnumType::dangling`) — PASS.** `format.rs:912` +(`self.delimited_dangling("{", items, &e.dangling, "}", false)`) confirmed +live: `typedef enum logic {A, B\n// that is all\n} e_t;` now prints the +comment inside the braces instead of dropping it. + +**Claim 4 (double-blank fix) — PASS**, with one informational note (below). +`leading_comments` (format.rs:243-260) confirmed to push the break *before* +each comment and one trailing `HardLine` before the node, exactly as +described. Corpus six-file delta reproduced exactly (see Corpus below). + +**Claim 5 (refusals fixed/parked) — PASS.** Every position claimed fixed +worked in the probe above. Every position claimed parked still refuses via +`verify.rs`, confirmed individually: `wire [7 /*c*/:0] w;` (dim interior), +`a[7 /*c*/:0]` (range interior), `initial y = a /*c*/;` (procedural `;`), +`sub u /*c*/ (.a(x));` and `if /*c*/ (a)` (before opening bracket), +`genvar i /*c*/, j;` (bare name list) — all exit 2, "verification failed". +**Comment before `else`**, specifically: a comment written as its own +leading line directly before the `else` keyword (procedural *or* +generate-level `else if`, i.e. through `GenElse::If`'s `meta` at +parser.rs:1671, whose value the formatter reads as `_meta` and never prints +at format.rs:1170) is refused by `verify.rs`, not silently dropped — +confirmed with a generate `else if` example +(`corpus`-style: `if (A) begin ... end\n// c\nelse if (B) ...`) and a +procedural twin. This matches the parked item. Two adjacent positions that +are *not* what's parked already work and are not new fixes: a same-line +comment between the then-branch's `;` and `else` lands as that statement's +trailing comment; a comment right after `else` before its statement lands +as that statement's leading comment. No refused position outside the +documented parked list was found. + +**Claim 6 (metrics) — line-position PASS, delimiter-position +directionally-consistent but should-investigate.** Wrote a fresh, +independent line-position harness (scratchpad `inject_lines_qa.py`, not the +dev's unchecked-in script) and ran it at 300 usable trials, seed 20260819, +against both binaries: **HEAD 2.33% (7/300), current 0.33% (1/300)** — both +essentially reproduce the README's 2.3%/0.4%. Wrote an independent +delimiter-position harness (`inject_delim_qa.py`) and ran it at 100 and 300 +usable trials, two seeds: **HEAD ≈ 42-43%, current ≈ 27-28%** — directionally +the same story (roughly halves), but the absolute numbers sit noticeably +below the README's 61.3%/35.7% on both sides of the comparison. Given the +README already documents that this style of ad hoc, not-checked-in harness +is sensitive to exactly which delimiters/positions get sampled (the same +caveat it gives for the TODO's old 6% figure), I read this as harness +variance rather than a wrong claim — the relative improvement and the +per-position probe results agree closely. Flagging per instructions since +it's a several-point absolute deviation; not blocking. + +**Claim 7 (suite hygiene) — PASS**, see Tooling above. +`crates/vlog_formatter/tests/fences.rs`: 6/6. +`git diff --stat -- fence.rs tests/fences.rs tests/cases/fences.cases`: +empty (untouched). Two fence probes: a same-line `// vfmt: off` trailing +marker is still ignored (the interior line still gets its extra spaces +collapsed — no accidental activation despite `Meta.trailing` now carrying a +span); an own-line fence immediately after a line with an unrelated +trailing comment still preserves its region byte-exact. Independent 3-pass +check across all 299 `.cases` inputs + the 4 `tests/fixtures/*.sv` files: +zero mismatches against expected output, zero refusals, zero drift. + +**Sabotage (both restored; `git diff --stat` identical before/after, +confirmed).** +1. `format.rs:912`: changed `&e.dangling` → `&[]`. Result: `case_tables` + fails exactly 1/299 — `comments.cases:804` ("a comment before the closing + brace of an enum member list stays inside it"), with the error + `token stream diverges ... input has comment "// that is all" ... output + has symbol "}"` — the exact corruption the fix prevents. Reverted; + suite green again. +2. `parser.rs:554-559` (`take_before_sep`): made it an unconditional no-op. + Result: `case_tables` fails exactly 17/299 — every "before comma"/"before + closing bracket" `.cases` entry across every list kind, starting with + `comments.cases:703` (the pinned list-gap case) — plus the parser unit + test `a_comment_before_a_list_comma_lands_in_before_sep` + (parser.rs:3174) fails directly. Reverted; suite green again (229/229, + clippy silent, fmt clean). + +**Corpus (exact results).** `./tools/corpus_check.sh corpus -b +target/release/vfmt`: 8 ok-unchanged (1.0%), 460 would-reformat (56.1%), +352 parse-error (42.9%), 0 verification-error, 0 crash — TSV md5 +**`aa982463f68c1a3568c02a0fc5e0c455`**, exact match. Built a `git worktree` +at `0ba29d4` (release), re-ran the same script: TSV md5 +**`3fab114f4f00626b254259e9dafe0ed7`**, exact match to the reproduced +baseline. Path-level diff of the two TSVs: exactly 6 lines differ — +`corpus/ibex/vendor/google_riscv-dv/src/isa/{custom/rv32x,rv32b,rv32i, +rv32m,rv32v,rv64b}_instr.sv`, all `would-reformat → ok-unchanged`, nothing +else changed. The two files that were already `ok-unchanged` on both +binaries (`.../isa/custom/rv64x_instr.sv`, `.../isa/rv32fc_instr.sv`) are +byte-identical between the HEAD and current binaries, as required. Corpus +working trees clean afterwards (only the pre-existing untracked +`.vfmt-corpus-rev` stamps) in all four vendored repos. + +**Findings.** + +- *Blocking:* none. No comment loss that `verify_equivalence` misses; every + induced regression was caught as a refusal (exit 2), never silent + corruption; 0 verification-errors and 0 crashes across the full corpus. +- *Should-fix:* none. No refused position outside the documented parked + list, in either the dev's probe or this round's independent one. +- *Informational, no action needed:* + 1. The blank-line fix's output footprint in the corpus is wider than the + six files that changed outcome category: of the 466 files that stay + `would-reformat` on both binaries, 178 also get a different target + output — checked line-by-line and every one of the 178 diffs is a + pure blank-line deletion, no other content change. This doesn't + contradict the README (which is specifically, and correctly, about + the TSV outcome-category delta) but is worth knowing if someone reads + "six files" as the full byte-level blast radius. + 2. `docs/features/format-fences/README.md`'s Handshakes line requesting + "a span on `Meta.trailing`" is now stale (delivered), as this round's + README already notes. Per CLAUDE.md this is the lead's call, not + edited here. Confirmed same-line fences remain correctly inert either + way (see Claim 7). + 3. Pre-existing, not introduced by this round: + `crates/vlog_formatter/src/format.rs:786` and `:978` each call + `.next().unwrap()` on an iterator, guarded by an `items.len() == 1` + check immediately above so it cannot panic in practice. Confirmed via + `git diff` that both lines are unchanged context, not new code. Out + of this round's scope; noting only because CLAUDE.md's "no `unwrap()` + in library code" rule technically covers them. + +## Review + +**2026-08-19 — lead. Verdict: accepted and committed as-is. The widest +diff of the project, and the one that retires "comments are the hard +part" as an open risk.** + +What earned the acceptance: + +1. **`take_before_sep` being a no-op unless the cursor is on the + separator** is the design insight of the round: it's why a change + touching every list kind left all 299 pre-existing cases + byte-identical. Correct-by-construction beats correct-by-testing, + and this had both (QA's 22-position independent probe, sabotage + confirming exactly 17 cases + 1 unit test depend on it). +2. **`EnumType::dangling`** — a comment parsed and never printed is an + invariant-#3 violation that predates every QA round and survived + them all because no case exercised it. Found by reading, fixed, + pinned. That's the standard. +3. **Metrics with a corrected baseline.** The dev re-measured the + unreproducible "6%" figure on a controlled HEAD worktree (2.3%), + reported its own improvement against that (0.4%), and flagged the + discrepancy instead of inheriting the flattering number. QA's + independent harness reproduced the line-position numbers almost + exactly; the delimiter-position deviation (dev 61→36, QA 42→28) is + methodology variance in the harder harness — both directionally + identical. TODO now carries the reproducible figures. +4. The corpus footprint being *honest* — md5 changed, six files moved + to fixed-point, nothing worse, verified by path against a rebuilt + HEAD baseline binary. + +Dispositions: the parked positions (dim/range interiors, procedural +`;`, before-opening-bracket, before-`else`, bare name lists) stay +documented in Status/TODO here — they are refusals, not corruption, +and the residual 0.4%/22-of-186 rate says the remaining surface is +small. The two pre-existing `unwrap()`s QA noticed (format.rs:786, +:978) join the next housekeeping pass. The stale fences-README +handshake line is corrected by the lead in this commit. Same-line +fences remain inert by choice; the data to activate them now exists. diff --git a/docs/features/format-fences/README.md b/docs/features/format-fences/README.md index 610f24c..5b8d56a 100644 --- a/docs/features/format-fences/README.md +++ b/docs/features/format-fences/README.md @@ -202,13 +202,14 @@ Nothing in `crates/vlog_parser` was changed, and nothing new is required of it for this feature to work as documented. **Requested of `vlog_parser` (optional, not blocking):** a span on -`Meta.trailing`. Today it is an `Option`, which is why a fence -written after code on the same line (`wire a; // vfmt: off`) cannot be -honoured — there is no offset to start the region at. If trailing comments -ever grow spans (they already exist on `Token.trailing`; `Meta` drops them -during harvest), this feature can accept same-line fences by starting the -region at the *following* line. Until then the limitation is documented -above. This is a request, not a change: no parser file was touched. +`Meta.trailing`. ~~Today it is an `Option`~~ **Delivered by the +comments-round feature (2026-08-19): `Meta.trailing` is now an +`Option` carrying line/col/span.** Same-line fences remain +deliberately inert — this feature's matcher was not changed to use the +new data (confirmed by comments-round QA with live probes). Accepting +same-line fences (starting the region at the *following* line) is now +unblocked whenever someone wants it; until then the limitation stands +as documented above. — lead note **Promised to `vlog_formatter` callers:** none of the public API changed. `format_source` has the same signature and the same contract.