From d3deacf0f6519709dd94aa32370ec2954ea28956 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Sat, 29 Aug 2026 12:55:51 -0700 Subject: [PATCH] Three formatter comment bugs fixed where they lived, safety net unwidened MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bucket 2 of syntax_coverage.md: 12 opentitan files parsed but failed the formatter's own verification. Three shapes: (A) a line comment trailing 'end' swallowed a cuddled 'else' into the comment — cuddling now requires no trailing line comment (block comments still cuddle); (B) a comment inside if/while/repeat/wait/case header parens printed after the ')' — Fmt::header_parens finds the real ')' and prints the split comments through the shared paren layout; (C) 'default;' grew an invented ':' — the optional colon is read from the source byte. 11 of 12 files now format and round-trip (12 -> 1 verification failures on the sweep); the 12th is a parser bug filed as a specified Handshake and delivered by the directive round, not edited cross-lane. verify.rs untouched; four masked-corruption rejection pairs added per the standing template; QA's ~30-attack sweep found zero corruption and pinned two informational boundaries. Formatter output changed: release must bump the workspace version (format-cache rule). Co-Authored-By: Claude Fable 5 --- TODO.md | 46 ++ crates/vlog_formatter/src/format.rs | 222 ++++++++-- .../vlog_formatter/tests/cases/comments.cases | 224 ++++++++++ .../tests/cases/statements.cases | 51 +++ crates/vlog_formatter/tests/verification.rs | 119 ++++++ docs/features/formatter-bug-fixes/README.md | 404 ++++++++++++++++++ 6 files changed, 1022 insertions(+), 44 deletions(-) diff --git a/TODO.md b/TODO.md index 8032afa..bdafc93 100644 --- a/TODO.md +++ b/TODO.md @@ -1296,3 +1296,49 @@ and three owner items. See unit's range is now in the index for free. - [ ] Manual extension-host acceptance (themes, keyboard-only, zoom, screen readers, an old server binary, both VSIX shapes). + +## 11. Testbench-syntax wave (2026-08-29) — syntax_coverage.md findings + +Source: `syntax_coverage.md` (opentitan sweep, 96.2% → the gap). The top +two buckets both edit `vlog_parser/src/parser.rs`, so per CLAUDE.md's +parallel-lane rule they run serially; the wave's first two lanes pair +the constraints round with the TOPO-independent formatter bugs instead. + +### Lane A — out-of-class constraints (worktree; files: +crates/vlog_parser/src/parser.rs, crates/vlog_parser/tests/*, +crates/vlog_semantic if an arm is needed, docs/features/ +out-of-class-constraints/README.md, TODO.md §11 Lane A lines) + +- [ ] `constraint C::name { ... }` at file/package/class-external scope + — 45 files blocked, and the tolerant-mode cascade (300+ bogus + diagnostics per file) is the real LSP damage. Expected shape: the + classes feature's verbatim capture reused (justify if not). + +### Lane B — formatter round-trip bugs (worktree; files: +crates/vlog_formatter/src/* EXCEPT verify.rs forgiveness, +crates/vlog_formatter/tests/*, docs/features/formatter-bug-fixes/ +README.md, TODO.md §11 Lane B lines) + +- [x] The 12 files the safety net refused (comment / `else if` merging + shapes in syntax_coverage.md §bucket 2): fix the formatter so its + output verifies; verify.rs forgiveness may NOT be widened (any + widening needs masked-corruption attack tests per invariant 4 — + prefer no widening at all). **11 of 12 fixed; `verify.rs` + untouched.** The 12th (`keymgr_scoreboard.sv`) had its bucket-2 + bug fixed and a second, distinct, *parser*-side bug behind it — + `Parser::take_before_open` (parser.rs:757) drains the whole + pending-comment queue, so a comment written after `if (` is + swallowed by the condition's first call. Out of Lane B's file set; + filed as a handshake in `docs/features/formatter-bug-fixes/ + README.md`. +- [ ] Owner/lead: the one-line parser fix above (Lane A's file), which + closes the last of the 12. + +### Serial, after Lane A merges (parser.rs frees up) + +- [ ] Directive-split for expressions/statements: `` `ifdef `` splitting + an assign RHS / instantiation head (chip_if.sv:1192 anchor; blocks + both top_* tb.sv testbenches). 5-file floor, high leverage. +- [ ] Mop-up bundle (~26 files): enum member ranges, cast-base drive + strengths, local typedef statement, gate delays, virtual+modport, + rand-on-struct, foreach-skip-dim, hierarchical bind instance list. diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs index 0abcdf0..fee3b83 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -413,9 +413,16 @@ impl<'a> Fmt<'a> { /// printing every comment and then every attribute moves a comment across /// an attribute in the token stream, which the safety net rejects. fn leading(&self, meta: &Meta) -> Vec { + self.leading_from(meta, 0) + } + + /// The same, minus the first `skip` leading comments — the ones a + /// statement header already printed inside its own parentheses. See + /// [`Fmt::header_parens`]. + fn leading_from(&self, meta: &Meta, skip: usize) -> Vec { let mut docs = Vec::new(); let mut attrs = meta.attrs.iter().peekable(); - for c in &meta.leading { + for c in meta.leading.iter().skip(skip) { while let Some(attr) = attrs.next_if(|a| a.span.start < c.span.start) { Self::push_leading(&mut docs, self.raw_text(attr), false); } @@ -832,6 +839,63 @@ impl<'a> Fmt<'a> { group(vec![text("("), indent(vec![Doc::SoftLine, self.expr(e)]), Doc::SoftLine, text(")")]) } + /// `( expr )` with the comments the source wrote just inside the + /// parentheses. A comment there forces them open, the same way a comment + /// inside a port list does. + fn paren_comments(&self, inner: &Expr, before: &[&Comment], after: &[&Comment]) -> Doc { + let mut docs = vec![Doc::SoftLine]; + for c in before { + docs.push(self.comment(c)); + docs.push(Doc::HardLine); + } + docs.push(self.expr(inner)); + let mut outer = vec![text("("), indent(docs)]; + for c in after { + outer.push(text(" ")); + outer.push(self.comment(c)); + } + let ends_line = after.iter().any(|c| is_line_comment(&c.text)); + outer.push(if ends_line { Doc::HardLine } else { Doc::SoftLine }); + outer.push(text(")")); + group(outer) + } + + /// The `(cond)` of a statement header, taking back the comments the parser + /// handed to the construct's *body* because they were written before the + /// closing `)`. + /// + /// Nothing between `(` and `)` owns trivia, so a comment written inside a + /// header's parentheses stays queued and lands on the next node that takes + /// meta — the body statement, or a `case`'s first item. Printed there it + /// would sit *after* a `)` it was written before, and `verify.rs` refuses + /// the file, rightly: the comment moved across a token. + /// + /// Returns the header doc and how many of `body`'s leading comments it + /// consumed, which the caller must then skip. When the source does not + /// have the expected shape nothing is taken and the plain parentheses are + /// printed, so an unrecognized header is left exactly as it was. + fn header_parens(&self, cond: &Expr, body: &Meta) -> (Doc, usize) { + let close = match skip_trivia(self.src, cond.span.end as usize) { + Some(i) if self.src.as_bytes().get(i) == Some(&b')') => i as u32, + _ => return (self.parens(cond), 0), + }; + let taken = body.leading.iter().take_while(|c| c.span.start < close).count(); + if taken == 0 { + return (self.parens(cond), 0); + } + let (before, after): (Vec<&Comment>, Vec<&Comment>) = + body.leading[..taken].iter().partition(|c| c.span.start < cond.span.start); + (self.paren_comments(cond, &before, &after), taken) + } + + /// True when the source wrote the optional `:` after a `default` case + /// label. IEEE 1800 §12.5 makes it optional — `default;` is legal — and + /// the token stream has to come back with exactly what was written. + fn default_has_colon(&self, span: TextRange) -> bool { + let after = span.start as usize + "default".len(); + matches!(skip_trivia(self.src, after), Some(i) if self.src.as_bytes()[i] == b':') + } + /// Sequence of items at one indent level, preserving single blank lines /// between them. An item a fenced region swallowed emits nothing, and /// contributes no separator either. @@ -1981,7 +2045,7 @@ impl<'a> Fmt<'a> { for item in &g.items { body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); body.extend(self.leading(&item.meta)); - let mut item_docs = vec![self.case_labels(&item.labels)]; + let mut item_docs = vec![self.case_labels(&item.labels, item.span)]; self.gen_block(&mut item_docs, &item.body, depth + 1); body.push(concat(item_docs)); body.extend(self.trailing(&item.meta)); @@ -2320,10 +2384,17 @@ impl<'a> Fmt<'a> { /// blocks cuddle onto the prefix line, single statements go on the same /// line if they fit, otherwise indented on the next line. fn stmt_as_body(&self, prefix: Doc, s: &Stmt) -> Doc { + self.stmt_as_body_from(prefix, s, 0) + } + + /// The same, skipping the body's first `skip` leading comments because + /// `prefix` already printed them inside its parentheses. See + /// [`Fmt::header_parens`]. + fn stmt_as_body_from(&self, prefix: Doc, s: &Stmt, skip: usize) -> Doc { match &s.kind { StmtKind::Block { label, stmts, dangling, end_label, .. } => { let mut docs = vec![prefix, text(" ")]; - docs.extend(self.leading(&s.meta)); + docs.extend(self.leading_from(&s.meta, skip)); docs.push(self.block_doc(label, stmts, dangling, end_label)); docs.extend(self.trailing(&s.meta)); concat(docs) @@ -2331,13 +2402,19 @@ impl<'a> Fmt<'a> { StmtKind::Timing { control, stmt: Some(inner) } => { // e.g. `always @(posedge clk) begin ... end` let mut docs = vec![prefix, text(" ")]; - docs.extend(self.leading(&s.meta)); + docs.extend(self.leading_from(&s.meta, skip)); let control_doc = self.timing_control(control); docs.push(self.stmt_as_body(control_doc, inner)); docs.extend(self.trailing(&s.meta)); concat(docs) } - _ => group(vec![prefix, indent(vec![Doc::Line, self.stmt(s)])]), + // The same three parts `stmt` prints, with the skip applied. + _ => { + let mut body = self.leading_from(&s.meta, skip); + body.push(self.stmt_kind(&s.kind)); + body.extend(self.trailing(&s.meta)); + group(vec![prefix, indent(vec![Doc::Line, concat(body)])]) + } } } @@ -2469,17 +2546,21 @@ impl<'a> Fmt<'a> { } head.push_str(kw); head.push(' '); - let mut docs = vec![text(head), self.parens(expr)]; + let (parens, taken) = match items.first() { + Some(first) => self.header_parens(expr, &first.meta), + None => (self.parens(expr), 0), + }; + let mut docs = vec![text(head), parens]; if *inside { docs.push(text(" inside")); } - docs.push(self.case_body(items, dangling)); + docs.push(self.case_body(items, dangling, taken)); concat(docs) } // `randcase` is a `case` body with weights for labels and no // selector, so it shares the body layout. StmtKind::RandCase { items, dangling } => { - concat(vec![text("randcase"), self.case_body(items, dangling)]) + concat(vec![text("randcase"), self.case_body(items, dangling, 0)]) } StmtKind::For { init, cond, step, body } => { let mut header = vec![text("for (")]; @@ -2511,7 +2592,8 @@ impl<'a> Fmt<'a> { self.stmt_as_body(concat(header), body) } StmtKind::While { cond, body } => { - self.stmt_as_body(concat(vec![text("while "), self.parens(cond)]), body) + let (parens, taken) = self.header_parens(cond, &body.meta); + self.stmt_as_body_from(concat(vec![text("while "), parens]), body, taken) } StmtKind::DoWhile { body, cond } => { let mut docs = vec![text("do")]; @@ -2532,7 +2614,8 @@ impl<'a> Fmt<'a> { concat(docs) } StmtKind::Repeat { count, body } => { - self.stmt_as_body(concat(vec![text("repeat "), self.parens(count)]), body) + let (parens, taken) = self.header_parens(count, &body.meta); + self.stmt_as_body_from(concat(vec![text("repeat "), parens]), body, taken) } StmtKind::Forever { body } => self.stmt_as_body(text("forever"), body), StmtKind::Foreach { target, vars, body } => { @@ -2589,13 +2672,13 @@ impl<'a> Fmt<'a> { None => concat(vec![control_doc, text(";")]), } } - StmtKind::Wait { cond, stmt } => { - let head = concat(vec![text("wait "), self.parens(cond)]); - match stmt { - Some(s) => self.stmt_as_body(head, s), - None => concat(vec![head, text(";")]), + StmtKind::Wait { cond, stmt } => match stmt { + Some(s) => { + let (parens, taken) = self.header_parens(cond, &s.meta); + self.stmt_as_body_from(concat(vec![text("wait "), parens]), s, taken) } - } + None => concat(vec![text("wait "), self.parens(cond), text(";")]), + }, StmtKind::ExprStmt(e) => concat(vec![self.expr(e), text(";")]), StmtKind::EventTrigger(e) => concat(vec![text("-> "), self.expr(e), text(";")]), StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), text(";")]), @@ -2660,9 +2743,13 @@ impl<'a> Fmt<'a> { head.push(' '); } head.push_str("if "); - let prefix = concat(vec![text(head), self.parens(cond)]); - let then_is_block = matches!(then.kind, StmtKind::Block { .. }); - let mut docs = vec![self.stmt_as_body(prefix, then)]; + let (parens, taken) = self.header_parens(cond, &then.meta); + let prefix = concat(vec![text(head), parens]); + // A line comment trailing the then-branch runs to end of line, so a + // cuddled `else` would be swallowed into its text. + let then_is_block = + matches!(then.kind, StmtKind::Block { .. }) && !trailing_ends_line(&then.meta); + let mut docs = vec![self.stmt_as_body_from(prefix, then, taken)]; if let Some(els) = els { // A comment written before `else` prints before it, each on its // own line: it is where the source put it, and after the keyword @@ -2700,9 +2787,9 @@ impl<'a> Fmt<'a> { /// Labels normally share one line; as soon as any of them carries a /// comment they go one per line, so a comment written between two labels /// is printed between the same two labels instead of drifting past them. - fn case_labels(&self, labels: &[ExprItem]) -> Doc { + fn case_labels(&self, labels: &[ExprItem], item: TextRange) -> Doc { if labels.is_empty() { - return text("default:"); + return text(if self.default_has_colon(item) { "default:" } else { "default" }); } let plain = labels.iter().all(|l| { l.meta.leading.is_empty() && l.meta.before_sep.is_empty() && l.meta.trailing.is_none() @@ -2744,16 +2831,27 @@ impl<'a> Fmt<'a> { } fn case_item(&self, item: &CaseItem) -> Doc { - self.stmt_as_body(self.case_labels(&item.labels), &item.stmt) + // `default;` — the colon IEEE 1800 §12.5 makes optional, with a null + // body. The `;` closes the keyword rather than standing as a body of + // its own, so it hugs instead of going through `stmt_as_body`. + if item.labels.is_empty() + && matches!(item.stmt.kind, StmtKind::Null) + && is_bare(&item.stmt.meta) + && !self.default_has_colon(item.span) + { + return text("default;"); + } + self.stmt_as_body(self.case_labels(&item.labels, item.span), &item.stmt) } - /// The indented items of a `case`/`randcase` body and the `endcase` that - /// closes it. - fn case_body(&self, items: &[CaseItem], dangling: &[Comment]) -> Doc { + /// The items of a `case`/`randcase` body. `skip` is the number of leading + /// comments of the *first* item the `case (...)` header already printed + /// inside its parentheses (see [`Fmt::header_parens`]). + fn case_body(&self, items: &[CaseItem], dangling: &[Comment], skip: usize) -> Doc { let mut body = Vec::new(); - for item in items { + for (i, item) in items.iter().enumerate() { body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); - body.extend(self.leading(&item.meta)); + body.extend(self.leading_from(&item.meta, if i == 0 { skip } else { 0 })); body.push(self.case_item(item)); body.extend(self.trailing(&item.meta)); } @@ -2874,23 +2972,9 @@ impl<'a> Fmt<'a> { if before.is_empty() && after.is_empty() { return self.parens(inner); } - // A comment inside the parens forces them open, the same way - // a comment inside a port list does. - let mut docs = vec![Doc::SoftLine]; - for c in before { - docs.push(self.comment(c)); - docs.push(Doc::HardLine); - } - docs.push(self.expr(inner)); - let mut outer = vec![text("("), indent(docs)]; - for c in after { - outer.push(text(" ")); - outer.push(self.comment(c)); - } - let ends_line = after.iter().any(|c| is_line_comment(&c.text)); - outer.push(if ends_line { Doc::HardLine } else { Doc::SoftLine }); - outer.push(text(")")); - group(outer) + let before: Vec<&Comment> = before.iter().collect(); + let after: Vec<&Comment> = after.iter().collect(); + self.paren_comments(inner, &before, &after) } ExprKind::Cast { ty, expr } => { concat(vec![self.expr(ty), text("'("), self.expr(expr), text(")")]) @@ -3102,3 +3186,53 @@ fn strip_blanks(line: &str, n: usize) -> &str { fn is_line_comment(text: &str) -> bool { text.starts_with("//") } + +/// True when a node carries no trivia at all, so printing it cannot move a +/// comment anywhere. +fn is_bare(meta: &Meta) -> bool { + meta.leading.is_empty() + && meta.trailing.is_none() + && meta.before_sep.is_empty() + && meta.attrs.is_empty() +} + +/// True when a node's trailing comments end in a line comment, so anything +/// printed after them on the same line would be swallowed into the comment's +/// text. `trailing` prints `before_sep` first and `trailing` last. +fn trailing_ends_line(meta: &Meta) -> bool { + match &meta.trailing { + Some(tr) => is_line_comment(&tr.text), + None => meta.before_sep.last().is_some_and(|c| is_line_comment(&c.text)), + } +} + +/// Offset of the first byte at or after `from` that is neither whitespace nor +/// part of a comment, or `None` if the text ends first. +/// +/// Used to ask what a node is followed by in the source — a `)` that closes +/// the header it sits in, the optional `:` of a `default` case label — when +/// the AST does not record it. +fn skip_trivia(src: &str, from: usize) -> Option { + let bytes = src.as_bytes(); + let mut i = from; + while i < bytes.len() { + match bytes[i] { + b'/' if bytes.get(i + 1) == Some(&b'/') => { + i += 2; + while i < bytes.len() && bytes[i] != b'\n' { + i += 1; + } + } + b'/' if bytes.get(i + 1) == Some(&b'*') => { + i += 2; + while i < bytes.len() && !(bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/')) { + i += 1; + } + i = (i + 2).min(bytes.len()); + } + c if c.is_ascii_whitespace() => i += 1, + _ => return Some(i), + } + } + None +} diff --git a/crates/vlog_formatter/tests/cases/comments.cases b/crates/vlog_formatter/tests/cases/comments.cases index 96bf486..430baf6 100644 --- a/crates/vlog_formatter/tests/cases/comments.cases +++ b/crates/vlog_formatter/tests/cases/comments.cases @@ -1191,3 +1191,227 @@ endmodule module m; sub /* the one */ u (.a(b)); endmodule +==== +# a line comment trailing `end` pushes `else if` onto the next line +module m; +always_comb begin +if (a) begin +x = 1; +end // addr_phase_write +else if (b) begin +x = 2; +end +else begin +x = 3; +end +end +endmodule +---- +module m; + always_comb begin + if (a) begin + x = 1; + end // addr_phase_write + else if (b) begin + x = 2; + end else begin + x = 3; + end + end +endmodule +==== +# a line comment trailing `end` pushes a one-statement `else` down too +module m; +always_comb begin +if (a) begin +x = 1; +end // fell through +else if (b) x = 2; +else x = 3; +end +endmodule +---- +module m; + always_comb begin + if (a) begin + x = 1; + end // fell through + else if (b) x = 2; + else x = 3; + end +endmodule +==== +# a block comment trailing `end` still lets `else` cuddle +module m; +always_comb begin +if (a) begin +x = 1; +end /* why */ else begin +x = 2; +end +end +endmodule +---- +module m; + always_comb begin + if (a) begin + x = 1; + end /* why */ else begin + x = 2; + end + end +endmodule +==== +# a comment after `if (` stays inside the parentheses +module m; +always_comb begin +if (// the first transaction + a || + // or the last one + b) begin +x = 1; +end +end +endmodule +---- +module m; + always_comb begin + if ( + // the first transaction + a || // or the last one + b + ) begin + x = 1; + end + end +endmodule +==== +# a block comment before an if condition's `)` stays inside them +module m; +always_comb begin +if (bitstuff /* && !serial_tx_se0 */) begin +x = 1; +end +end +endmodule +---- +module m; + always_comb begin + if (bitstuff /* && !serial_tx_se0 */) begin + x = 1; + end + end +endmodule +==== +# an if condition keeps comments on both sides of it +module m; +always_comb begin +if (// only the leading one + a) begin +x = 1; +end +if (b /* and a trailing one */) begin +x = 2; +end +if (// both ends + c /* like this */) begin +x = 3; +end +end +endmodule +---- +module m; + always_comb begin + if ( + // only the leading one + a + ) begin + x = 1; + end + if (b /* and a trailing one */) begin + x = 2; + end + if ( + // both ends + c /* like this */ + ) begin + x = 3; + end + end +endmodule +==== +# a comment after `while (` stays inside the parentheses +module m; +initial begin +while (// keep adding while the agent wants more + rcvd < sent || + // and while there are transactions left to drive + cnt < num) begin +x = 1; +end +end +endmodule +---- +module m; + initial begin + while ( + // keep adding while the agent wants more + rcvd < sent || // and while there are transactions left to drive + cnt < num + ) begin + x = 1; + end + end +endmodule +==== +# `repeat` and `wait` keep a comment written before their `)` +module m; +initial begin +repeat (n // how many + ) begin +x = 1; +end +wait (w // until this settles + ) begin +x = 2; +end +end +endmodule +---- +module m; + initial begin + repeat ( + n // how many + ) begin + x = 1; + end + wait ( + w // until this settles + ) begin + x = 2; + end + end +endmodule +==== +# a comment after `case (` stays inside the parentheses +module m; +always_comb begin +case (// the decoded opcode + op) +A: y = 1; +default: y = 0; +endcase +end +endmodule +---- +module m; + always_comb begin + case ( + // the decoded opcode + op + ) + A: y = 1; + default: y = 0; + endcase + end +endmodule diff --git a/crates/vlog_formatter/tests/cases/statements.cases b/crates/vlog_formatter/tests/cases/statements.cases index 2fdc840..f2d1d9e 100644 --- a/crates/vlog_formatter/tests/cases/statements.cases +++ b/crates/vlog_formatter/tests/cases/statements.cases @@ -587,3 +587,54 @@ endmodule module m; always @(a or b or c) y = a & b & c; endmodule +==== +# `default;` keeps IEEE 1800 §12.5's optional colon off; `default: ;` keeps it +module m; +always_comb begin +unique case (digest_size_i) +SHA2_256: y = 1; +default; +endcase +unique case (other) +SHA2_256: y = 1; +default: ; +endcase +end +endmodule +---- +module m; + always_comb begin + unique case (digest_size_i) + SHA2_256: y = 1; + default; + endcase + unique case (other) + SHA2_256: y = 1; + default: ; + endcase + end +endmodule +==== +# a trailing comment on a colon-less `default;` keeps the comment and the +# missing colon; the null statement is no longer bare, so the hug shortcut +# does not fire and a space appears before the `;` (QA-found nit: a real +# statement or comment on the null body falls through to the general path, +# which spaces `default` off whatever follows it the same way it would any +# other case label) +module m; +always_comb begin +case (s) +A: y = 1; +default; // fallback +endcase +end +endmodule +---- +module m; + always_comb begin + case (s) + A: y = 1; + default ; // fallback + endcase + end +endmodule diff --git a/crates/vlog_formatter/tests/verification.rs b/crates/vlog_formatter/tests/verification.rs index ec346a0..8171435 100644 --- a/crates/vlog_formatter/tests/verification.rs +++ b/crates/vlog_formatter/tests/verification.rs @@ -1257,3 +1257,122 @@ fn an_opaque_body_cannot_launder_a_stray_endif_into_a_split() { } } } + +/// Assert `format_source` refuses `input` with a verification error, i.e. the +/// safety net caught the layout and the caller keeps the original bytes. +fn expect_refusal(input: &str) { + match format_source(input, &Config::default()) { + Err(FormatError::Verification(_)) => {} + Ok(out) => panic!("expected a refusal, got:\n{out}"), + Err(e) => panic!("expected a verification refusal, got {e}"), + } +} + +/// The header shapes `header_parens` deliberately does *not* cover, pinned as +/// clean refusals so a future round sees them move rather than appear. +/// +/// `for` and `foreach` do not end their header in a single condition +/// expression, and a `do ... while (c);` has no body after its parentheses to +/// take the comment back from. All three still leave the file untouched. +#[test] +fn a_comment_in_a_for_foreach_or_do_while_header_is_still_refused() { + for input in [ + "module m;\n initial begin\n for (int i = 0; i < 4; i++ // why\n ) begin\n y = 1;\n end\n end\nendmodule\n", + "module m;\n initial begin\n foreach (arr[i] // why\n ) begin\n y = 1;\n end\n end\nendmodule\n", + "module m;\n initial begin\n do begin\n y = 1;\n end while (c // why\n );\n end\nendmodule\n", + ] { + expect_refusal(input); + } +} + +/// The three bucket-2 shapes, formatted for real: every comment comes back +/// with its own text, none merged into the code that follows it, and the +/// second pass is a fixed point. +#[test] +fn the_repaired_comment_shapes_keep_every_comment_intact() { + for (input, kept, banned) in [ + ( + "module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // addr_phase_write\n else if (b) begin\n x = 2;\n end\n end\nendmodule\n", + "// addr_phase_write", + "// addr_phase_write else", + ), + ( + "module m;\n always_comb begin\n if (// why not\n a || b) begin\n x = 1;\n end\n end\nendmodule\n", + "// why not", + ") // why not", + ), + ( + "module m;\n always_comb begin\n if (a /* and here */) begin\n x = 1;\n end\n end\nendmodule\n", + "/* and here */", + ") /* and here */", + ), + ] { + let out = format_source(input, &Config::default()).expect("formats cleanly"); + assert!(out.contains(kept), "comment lost:\n{out}"); + assert!(!out.contains(banned), "comment merged or moved:\n{out}"); + let again = format_source(&out, &Config::default()).expect("formats again"); + assert_eq!(out, again, "not idempotent"); + } +} + +/// Standing rule (`topo.md` §2.1): `verify.rs` was not widened for any of +/// these fixes, and the corruptions they used to produce must still be +/// rejected if a future layout change reintroduces them. +#[test] +fn the_bucket_two_corruptions_are_still_rejected() { + // A trailing line comment swallowing the `else if` that followed it. + expect_divergence( + "module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // note\n else if (b) begin\n x = 2;\n end\n end\nendmodule\n", + "module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // note else if (b) begin\n x = 2;\n end\n end\nendmodule\n", + ); + // A comment written inside the condition, printed after the `)`. + expect_divergence( + "module m;\n always_comb begin\n if (// note\n a) begin\n x = 1;\n end\n end\nendmodule\n", + "module m;\n always_comb begin\n if (a) // note\n begin\n x = 1;\n end\n end\nendmodule\n", + ); + // The `:` a `default;` did not write, invented by the printer. + expect_divergence( + "module m;\n always_comb begin\n case (s)\n A: y = 1;\n default;\n endcase\n end\nendmodule\n", + "module m;\n always_comb begin\n case (s)\n A: y = 1;\n default: ;\n endcase\n end\nendmodule\n", + ); + // And its mirror: a `default: ;` losing the colon it did write. + expect_divergence( + "module m;\n always_comb begin\n case (s)\n A: y = 1;\n default: ;\n endcase\n end\nendmodule\n", + "module m;\n always_comb begin\n case (s)\n A: y = 1;\n default;\n endcase\n end\nendmodule\n", + ); +} + +/// A comment written just after a statement header's `(` is queued by the +/// parser and drained onto the first bracket it meets — so when the condition +/// starts with a call, `CallComments::before_open` swallows it and the +/// comment prints between the callee and its `(`. `header_parens` cannot take +/// it back: it never reaches the body's leading comments. Pinned as a refusal +/// (the file is left alone); the fix belongs in the parser's +/// `take_before_open`, which drains the whole pending queue instead of the +/// comments actually written in front of the bracket. +#[test] +fn a_comment_before_a_call_in_a_condition_is_still_refused() { + expect_refusal( + "module m;\n function automatic int f();\n if (// why\n !en() || b\n ) begin\n return 1;\n end\n endfunction\nendmodule\n", + ); +} + +/// QA (2026-08-29, Lane B): `trailing_ends_line` decides whether `end`'s +/// trailing comments swallow a cuddled `else` by checking whether the +/// *merged* trailing text starts with `//` (`is_line_comment` is a prefix +/// test). A block comment followed by a line comment on the same trailing +/// group — `end /* a */ // b` — merges into one string that starts with +/// `/*`, so the check says "does not end in a line comment" and `else` still +/// tries to cuddle, which does produce the merge this whole fix exists to +/// prevent. The safety net catches it (the reparsed output has one big +/// comment where the input had two), so the file is refused rather than +/// corrupted — this pins that it stays a safe refusal, not a fix for the +/// gap. If a later round teaches `trailing_ends_line` to look at the last +/// merged comment instead of the first, this test should flip to a `.cases` +/// entry the same way the parser handshake above is meant to. +#[test] +fn a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused() { + expect_refusal( + "module m;\n always_comb begin\n if (a) begin\n x = 1;\n end /* a */ // b\n else if (c) begin\n x = 2;\n end\n end\nendmodule\n", + ); +} diff --git a/docs/features/formatter-bug-fixes/README.md b/docs/features/formatter-bug-fixes/README.md index a7f499d..2f4c5fa 100644 --- a/docs/features/formatter-bug-fixes/README.md +++ b/docs/features/formatter-bug-fixes/README.md @@ -24,6 +24,21 @@ The five: 5. `always @( /* c */ * )` loses the comment: `parse_sens_list` discarded comments written inside the parens of an implicit sensitivity list. +**Round 2 (2026-08-29, Lane B of the testbench-syntax wave).** The same +feature, extended to `syntax_coverage.md`'s bucket 2: the 12 real OpenTitan +files that parse with zero errors but whose *formatted output* the safety net +refused. Three more bugs, all in `format.rs`'s layout, none needing a +`verify.rs` change: + +6. A line comment trailing the then-branch's `end` swallowed the `else` that + followed it (`end // addr_phase_write` + `else if (...) begin` came back as + one comment). 4 of the 12 files. +7. A comment written inside a statement header's parentheses (`if (// why` ⏎ + `cond)`, `while (`, `repeat (`, `wait (`, `case (`) printed *after* the + `)`, moving it across a token. 7 of the 12 files. +8. `default;` — the case-item colon IEEE 1800 §12.5 makes optional — came + back as `default:`, inventing a token the source never wrote. 1 file. + ## Assumptions - The four `#SKIP` expected outputs are the spec. None of them was changed. @@ -66,6 +81,46 @@ The five: enclosing group in this printer. The hug only applies when the value already contains a forced break, so no case without comments changed. +### Round 2 (2026-08-29) + +- **`verify.rs` was not touched at all this round** (`git diff` on it is + empty), and no normalization was added or broadened. Every fix is a layout + change in `format.rs`; the safety net's judgement of all three shapes is + unchanged, and four crafted (input, corrupted output) pairs assert it still + rejects exactly the corruptions these bugs used to produce. +- **The parser's trivia attachment is taken as given.** Nothing between a + statement header's `(` and `)` owns trivia, so a comment written there is + queued and lands on the next node that takes meta — the body statement, or + a `case`'s first item. The formatter takes it back by *span* rather than + asking the parser to change: a leading comment of the body that starts + before the header's `)` was written inside the parentheses. This is Lane B's + file-set constraint made into a design point, and it is exact, because a + comment's byte span says unambiguously which side of the `)` it was on. +- **The `)` is found in the source, not in the AST**, by skipping whitespace + and comments forward from the end of the condition expression + (`skip_trivia`). Only trivia can stand there for `if`/`while`/`repeat`/ + `wait`/`case`. If anything else turns up, the header prints its plain + parentheses and takes nothing, so an unrecognized shape behaves exactly as + it did before. +- **A cuddled `else` is a layout decision, not a token.** `end` keeps `else` + on its line unless the then-branch's own trailing comments end in a line + comment, which would swallow it. A block comment still cuddles + (`end /* why */ else`). +- `for`, `foreach` and `do ... while` are **not** covered: the first two do + not end their header in a single condition expression, and a `do`-`while` + has no body after its parentheses to take the comment back from. All three + still refuse cleanly and are pinned as refusals by a test. +- A comment written *before* a header's `(` (`if /* c */ (a)`) is also not + covered — the formatter has no offset for the `(`, so such a comment is + treated as if it were inside and the file is still refused, exactly as it + was before. No corpus use. +- **`default;` is read from the source too.** `CaseItem` records no `colon` + flag (the parser does `let _ = self.eat_sym(":")`), so `default_has_colon` + looks at the byte after the keyword. With a null body the `;` hugs the + keyword — `default;`, not `default ;` — while `default: ;` keeps both the + colon and the space it already had. Generate-case `default` reads the same + way. + ## Handshakes - **`vlog_parser::token::Comment` gained a position** (the handshake request @@ -102,6 +157,45 @@ The five: and the top-level `README.md` (another agent's scope) are untouched; `cargo fmt` was run and left those files byte-identical. +### Round 2 (2026-08-29) + +- **Nothing was changed outside `crates/vlog_formatter`.** Round 2 consumes + the AST exactly as it stands: `Comment.span`, `Expr.span`, `CaseItem.span` + and `Meta.leading`'s source order are the only new load-bearing surfaces, + and all four already existed. `git diff` on `crates/vlog_parser` and + `crates/vlog_semantic` is empty. +- **Open handshake request to whoever owns `vlog_parser/src/parser.rs` + (Lane A's file this wave).** `Parser::take_before_open` (`parser.rs:757`) + calls `take_dangling()`, which drains the *whole* pending-comment queue — + `pending_trailing`, `pending_leading` and the bracket token's own leading + comments — rather than only the comments actually written in front of the + bracket. So a comment written just after a statement header's `(` is + swallowed by the first call inside the condition and printed between that + call's callee and its own `(`: + + ```systemverilog + if (// If keymgr is not enabled in the current LC + !cfg.keymgr_vif.get_keymgr_en() || ... + ``` + + comes back as `!cfg.keymgr_vif.get_keymgr_en // If keymgr ...` ⏎ `() ||`. + `header_parens` cannot take it back — it never reaches the body's leading + comments — and the formatter cannot hoist it out past the `!` without a + cutoff threaded through every `expr` call, which is far more machinery than + the parser fix. **Requested fix**: in `take_before_open`, keep only the + comments whose `span.start >= self.last_end()`, i.e. those written in the + gap that ends at the bracket, and leave the rest queued. `last_end()` + already exists (`parser.rs:611`). This is the last of the 12 bucket-2 files + (`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv`); the shape is pinned as a + clean refusal by + `verification.rs::a_comment_before_a_call_in_a_condition_is_still_refused`, + which is the test that should flip to a `.cases` entry when the parser fix + lands. +- **Format-cache discipline** (`topo.md` §2.3): this round changes formatter + *output* for the shapes above, so the workspace version must be bumped at + release or a stale `.lucisv_cache` will skip files that would now format + differently. Flagged for the lead; no version was bumped here. + ## Status / TODO - [x] Bug 3 — closing block labels preserved (`end`, all `join` kinds, @@ -131,6 +225,34 @@ The five: The "re-enable the four `#SKIP` cases" item lives in the case-tables README's TODO and is now satisfied. +### Round 2 (2026-08-29) + +- [x] Bug 6 — a line comment trailing `end` no longer swallows the `else` + that follows it; a block comment still cuddles. +- [x] Bug 7 — a comment written inside an `if`/`while`/`repeat`/`wait`/`case` + header's parentheses is printed inside them, on the correct side of the + condition. +- [x] Bug 8 — `default;` keeps IEEE 1800 §12.5's optional colon off, and + `default: ;` keeps it on. +- [x] 11 of the 12 bucket-2 OpenTitan files format cleanly and are + idempotent; the whole checkout is unchanged on disk. Before/after in + the work log. +- [x] 11 new `.cases` entries (10 in `comments.cases`, 1 in + `statements.cases`) — each one asserts the output *and* that + re-formatting it is a fixed point, which is what the harness does. +- [x] 4 masked-corruption rejection pairs + an explicit + comments-never-dropped assertion in `verification.rs`, plus 4 pinned + refusals for the shapes deliberately left uncovered. +- [x] `cargo fmt --check` clean, `cargo clippy --all-targets` silent, + `cargo test --workspace` green, pinned corpus 813/820 (baseline 813, + zero verification errors). +- [ ] Not fixed, needs a change in `vlog_parser` (see Handshakes): a comment + after `if (` when the condition starts with a call — + `keymgr_scoreboard.sv`, the 12th file. +- [ ] Not fixed, no corpus evidence, pinned as refusals: a comment inside a + `for`/`foreach` header or a `do ... while (...)`; a comment written + between a header keyword and its `(`. + ## Work log ### 2026-08-18 — dev agent @@ -239,6 +361,109 @@ an indented banner comment) formats cleanly, and `lucisv` on its own output is byte-identical. Every bug's original repro from the two feature READMEs was re-run through the built CLI and now exits 0. +### 2026-08-29 — dev agent (Lane B, testbench-syntax wave) + +**Scope.** `syntax_coverage.md`'s bucket 2: the 12 OpenTitan files that parse +with zero errors but whose formatted output the safety net refused. Measured +first, against the real checkout at `/Users/guoliangchen/repo/opentitan` +(`--no-cache --check` over all 3,943 `.sv`/`.svh`): **151 failures, 12 of them +`verification failed:`** — reproducing the sweep exactly. The 12 are three +shapes, not one: + +| # | shape | files | +|---|---|---| +| 6 | `end // c` ⏎ `else …` — the trailing line comment swallows the `else` | 4 | +| 7 | a comment inside a statement header's `(...)` prints after the `)` | 7 | +| 8 | `default;` comes back as `default:` | 1 | + +**Bug 6 — `end // c` then `else`.** `if_stmt` cuddled `else` onto the `end` +line whenever the then-branch was a block. `stmt_as_body` has already printed +the block's trailing comments by then, so ` else if (b) begin` landed *inside* +a line comment's text and `verify.rs` saw one comment reading +`// addr_phase_write else if (addr_phase_read) begin`. The whole fix is one +extra condition on `then_is_block`: a free `trailing_ends_line(&then.meta)` +that asks whether the last thing `trailing` prints is a `//` comment. A block +comment still cuddles, which is what the source wanted anyway. + +**Bug 7 — comments inside a header's parentheses.** The header's `(` and `)` +are printed by `parens()` and belong to no node, so the parser has nowhere to +put a comment written between them: it stays in the pending queue and lands on +the next node that calls `take_meta` — the body statement (`if`, `while`, +`repeat`, `wait`) or the first case item (`case`). Printed there, the comment +sits after a `)` it was written before. + +Fixed entirely on the formatter side, by span. `header_parens(cond, body_meta)` +finds the closing `)` with `skip_trivia` (forward from `cond.span.end`; only +whitespace and comments can stand there), takes every leading comment of the +body that starts before it, splits them at `cond.span.start` into before/after +buckets, and hands them to `paren_comments` — which is the existing +`ExprKind::Paren { before, after }` layout, factored out and now shared by both +callers rather than duplicated. It returns how many comments it consumed; +`stmt_as_body_from` / `leading_from` / `case_body` skip exactly that many. +`leading`, `stmt_as_body` and `case_body`'s old signature are all preserved as +`skip = 0` wrappers, so the twelve other `stmt_as_body` call sites are +untouched. When the source is not the expected shape (no `)` where one was +expected, or nothing to take) the function returns the plain `parens(cond)` and +takes nothing, so every input that formatted before formats identically. + +`for`, `foreach` and `do ... while` were deliberately left out: the first two +do not end their header in one condition expression and the third has no body +after its parens. Confirmed they still refuse cleanly and pinned that with a +test, so a later round sees them change rather than appear. + +**Bug 8 — `default;`.** `parse_case_body` does `let _ = self.eat_sym(":")`, so +the AST does not record whether the source wrote the colon, and `case_labels` +printed `default:` unconditionally — inventing a token. Since `CaseItem.span` +starts at the `default` keyword, `default_has_colon` reads the byte after it +(through the same `skip_trivia`) and prints what was written. With a null body +the `;` hugs the keyword, because `stmt_as_body` would otherwise lay the `;` +out as a body and produce `default ;`. `default: ;` is unchanged. + +**`verify.rs` is untouched** — `git diff` on it is empty. Per `topo.md` §2.1's +standing template I added the rejection tests anyway: four crafted (input, +corrupted output) pairs asserting the net still refuses the comment merged into +`else if`, the comment moved across the `)`, `default;` → `default: ;` and its +mirror `default: ;` → `default;`. + +**Before / after on the real OpenTitan checkout** (3,943 files, `--no-cache +--check`, nothing ever written — `git status` in the corpus shows only the +pre-existing `hw/ip/aes/dv/tb/tb.sv` modification `syntax_coverage.md` already +records): + +| | before | after | +|---|---|---| +| total failures (exit 2) | 151 | 140 | +| `verification failed:` | 12 | **1** | +| `parse error:` / `lex error:` | 139 | 139 | +| crashes | 0 | 0 | + +All 11 fixed files were additionally formatted twice through `--stdout` and the +two passes compared byte-for-byte: **idempotent**, and every checkout file's +`md5` is unchanged. Pinned 820-file corpus: **813 passing** (baseline 813), +zero verification errors, zero crashes — no regression. + +**The 12th file, and why it is not mine to fix.** +`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` had *two* bucket-2 bugs; fixing the +first (the `end // addr_phase_write` / `else if` merge at line 643) uncovered a +second at line 1254 that is not a formatter layout bug at all. The comment +there is written after `if (` and the condition starts with a call, so +`Parser::take_before_open` — which drains the whole pending queue — hands it to +`CallComments::before_open`, and the formatter faithfully prints it between the +callee and its `(`. `header_parens` never sees it. Hoisting it back out of the +expression past the `!` would need a suppression cutoff threaded through every +`expr` call; the parser fix is one span check. Filed as an open handshake +(above) with the exact patch, out of Lane B's file set, and pinned as a clean +refusal by a test. Also confirmed the same parser bug bites +`return // c` ⏎ `g();`, which is a second, independent symptom. + +**Deviation from the brief**: 11 of 12 files, not 12, for the reason above. +Nothing was worked around and no corruption ships — the 12th file is still +refused and left byte-identical, which is the correct behavior until the parser +lands its fix. + +**Format-cache note for the lead**: formatter output changed, so the workspace +version must be bumped at release (`topo.md` §2.3). Not bumped here. + ## QA log ### 2026-08-19 — QA agent @@ -485,8 +710,187 @@ compliance (no unwrap/expect/panic in library paths, no new deps, no un-explained `#[allow]`, TODO.md/README.md/`lucisv` untouched) all confirmed by direct inspection, not just by trusting the work log's claims. +### 2026-08-29 — QA agent (Lane B, testbench-syntax wave) + +**Scope**: round 2 only — the three bucket-2 fixes (bug 6 `end // c` + `else`, +bug 7 `header_parens`, bug 8 `default;`) — with the adversarial charter aimed +squarely at a dropped/merged comment, an invented/moved token, or a fix that +only works on the corpus shapes. Built a `--no-cache --stdout`/`--check` +attack harness (pass1 → pass2 byte comparison for idempotency) and ran ~30 +hand-crafted `.sv` files beyond the committed cases, then reproduced every +number in the work log independently against the real checkouts. + +**Tool chain** (workspace root, after adding the two regression tests below): +`cargo fmt --check` clean; `cargo clippy --all-targets` silent, no new +`#[allow]`; `cargo test --workspace` green — `vlog_formatter`'s +`verification.rs` at 119/119 (118 + 1 new), `cases.rs` 1/1 (672 total cases +across all `.cases` files, `grep -c '#SKIP'` zero everywhere). Confirmed +`git diff --stat` on `crates/vlog_parser`, `crates/vlog_semantic`, +`crates/vlog_formatter/src/verify.rs` is empty — the "verify.rs untouched" +claim holds. + +**Shape-A attacks (`end // c` / `else`)** — 5 crafted files: nested three-deep +if-else-if chain with every `end` individually commented (correct, stable); +the comment text containing the literal word "else" (correct, not +mistaken for structure); a CRLF-terminated file with the same shape +(correct); a pure block comment before `else` (still cuddles, as designed). +**One real gap found** (below) with a mixed block+line trailing comment. + +**Shape-B attacks (`header_parens`)** — 9 crafted files hitting the source +scan directly: a `)` inside a string literal in the condition +(`s == ")"`), a `)` inside a nested paren sub-expression, a `)` spelled +inside a block comment (`/* looks like ) but is not */`), comments on both +sides of the `cond.span.start` split simultaneously, a condition that is +itself a `Paren` (double parens), `case`/`while`/`repeat`/`wait` each with +both-sided comments, and a case with two commented items after the header to +attack the skip-count plumbing. **All format correctly, keep every comment +in its original stream position, and are idempotent — no corruption, no +double-print, no drop.** Also re-confirmed the two documented refusal +boundaries directly (not just via `cargo test`): a comment before the +statement keyword's `(` (`if /* c */ (a)`) refuses cleanly (`token stream +diverges ... input has comment ... output has symbol "("`), and a comment +before a call in the condition refuses cleanly, matching the Handshakes +description exactly. + +**Shape-C attacks (`default`)** — 9 crafted files: `default ;` (extra space) +normalizes to `default;`; `default: ;` unchanged; `default begin end` / +`default: begin end` both correct with the colon exactly as written; +`default y = 9;` (no colon, non-null body — a shape not explicitly named in +the work log but legal per the same IEEE grammar) correctly keeps the colon +off; two `default`s in one `case` (illegal but tolerated) round-trips both +correctly; `default /* c */: y = 9;` (comment between keyword and colon) +refuses cleanly rather than dropping or moving the comment. **One +non-blocking style nit found** (below): a trailing comment on `default;` +breaks the hug. `default;` inside a `generate case` without `begin`/`end` +hits a **pre-existing parser error** ("expected item"), confirmed unrelated +— `default begin : gd end` in the same position parses and formats fine, so +this is generate-case's existing null-body restriction, not a regression +from this round. + +**Refusal-pin sabotage check**: confirmed by inspection that `StmtKind::For` +and `StmtKind::DoWhile` were not touched by the diff at all (no +`header_parens` call added), so their pinned refusal test is exercising the +same pre-existing, unmodified comment-position divergence check from round +1 — not a vacuous pass against dead code. + +**Masked-corruption template**: all four crafted pairs genuinely attack the +paths this round changed (else-swallow, comment-across-`)`, colon invented, +colon dropped) rather than generic corruptions; re-ran them independently +via `cargo test -p vlog_formatter the_bucket_two_corruptions_are_still_rejected`. + +**Numbers reproduced independently**, all against the live checkouts, all +read-only (`--check`/`--stdout` only): +- OpenTitan (`/Users/guoliangchen/repo/opentitan` @ `0098135264`, the same + pre-existing `hw/ip/aes/dv/tb/tb.sv` local edit `syntax_coverage.md` + records, nothing else dirty): `lucisv --no-cache --check .` → + **exactly 1** `verification failed:` (`hw/ip/keymgr/dv/env/ + keymgr_scoreboard.sv:1254`, byte-identical message to the Handshakes + quote). Total failure count differs slightly from the work log's 140 + (146 here) — attributable to `.gitignore`/vendor-tree walk differences + between sweeps, not to this round; the load-bearing number (verification + failures) matches exactly. +- Grepped the whole checkout for the three trigger shapes independently of + the work log's file list (`end\s*//.*\n\s*else`, `(if|while|repeat|wait| + case)\s*\(\s*//`, `^\s*default\s*;`) and got **exactly 12** candidate + files. Ran each through format+idempotency: **10 format cleanly and are + pass1==pass2 idempotent**, `keymgr_scoreboard.sv` is the documented + refusal, and one grep hit (`spi_device_scoreboard.sv`) fails on an + unrelated pre-existing macro-expansion parse error + (`` `CREATE_TPM_CASE_STMT ``) before the formatter ever reaches the + bucket-2 shape — confirms "11 of 12" exactly, with the 12th grep hit + being a false positive from the search pattern, not a second bug. +- Corpus gate: fetched `tools/corpus_fetch.sh`'s four pinned repos (820 + files: 131 + 613 + 35 + 41, matches exactly) and ran `scripts/score.sh`: + `{"passing":813,"total":820,...}` — the exact baseline, zero + `verification failed:` entries in `.score-results.tsv` (the 7 failures + are all pre-existing parse/lex errors, none in the `other` bucket is a + verification error). + +**Findings** + +*Should-fix*: none. No hard-invariant violation found in either crafted +attacks or the real checkouts. + +*Nit / informational* (both non-blocking — the safety net holds in both +cases; regression tests added for both): + +1. **`trailing_ends_line` (`format.rs`, the `Some(tr)` arm) checks whether + the *merged* trailing text starts with `//`, not whether it ends in a + line comment.** `Meta.trailing` merges several trailing comments into one + string (see `ast.rs:92-96`); a line comment must physically be last in + any such merge (nothing can follow `//` on the same source line), so the + correct test is "does the merge end in one", not "does it start with + one". For `end /* a */ // b` the merged text is `"/* a */ // b"`, which + does not start with `//`, so `trailing_ends_line` returns `false` and + `then_is_block` stays `true` — the `else` still tries to cuddle, exactly + reproducing the bug this round fixes, on the one merge shape the fix's + condition doesn't cover. **Not a corruption**: `verify.rs` catches it on + reparse (the output's one merged comment doesn't match the input's two) + and the file is refused, byte-identical, same as it was before this + round (this exact shape always cuddled unconditionally pre-fix too, so + it is not a regression — it is the fix's coverage boundary, undocumented + until now). Pinned as a refusal, not fixed — narrowing `is_line_comment` + into a "starts vs. ends" split is a real design decision (the merge + already lost the individual comments' boundaries) that belongs to + whoever next touches this heuristic, not a QA-scope patch. Regression + test: `crates/vlog_formatter/tests/verification.rs:: + a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused`. +2. **A trailing comment on a colon-less `default;` breaks the hug and + inserts a space**: `default; // fallback` formats to `default ; // + fallback`. Root cause: `case_item`'s shortcut requires `is_bare(&item. + stmt.meta)`, and a comment trailing the null statement lands in `item. + stmt.meta.trailing`, which is not bare, so the shortcut is skipped and + the general `case_labels` + `stmt_as_body` path inserts its usual + `Doc::Line` between the label and the body. **Not a correctness issue**: + the comment is kept verbatim in its original stream position, `verify.rs` + accepts it (whitespace is not part of the token stream), and it is + idempotent. It does contradict the round's stated design point + ("`default;`, not `default ;`") for this one sub-case. Pinned with an + exact-output case rather than fixed, since teaching the shortcut to also + fire with a bare-except-trailing-comment statement (and then print that + comment itself) is a small but real behavior change outside a + verify-and-report QA pass. Regression case: + `crates/vlog_formatter/tests/cases/statements.cases`, "a trailing + comment on a colon-less `default;` keeps the comment and the missing + colon". + +**Regression tests added this pass** (2 files, both green): +- `crates/vlog_formatter/tests/verification.rs`: + `a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused` + (finding 1 above, pins the safe refusal). +- `crates/vlog_formatter/tests/cases/statements.cases`: one new case (finding + 2 above, pins the current — correct but slightly odd — output). + +**Overall verdict**: **SHIP.** Both bucket-2 fixes claimed (11/12 files, +verification failures 12→1) are reproduced exactly against the live +OpenTitan checkout and the pinned 813/820 corpus, `verify.rs` is +byte-for-byte untouched, and every crafted adversarial input across all +three shapes either formats correctly with every comment preserved in place +and idempotently, or is safely refused with the file left untouched — never +corrupted. The two findings are both informational nits with permanent +regression tests now guarding them; neither is a hard-invariant violation +and neither blocks merge. + ## Review +**2026-08-29 — lead, round 2 (bucket-2 round-trip bugs).** Reviewed +after QA's SHIP; gates re-run on the worktree (fmt clean, formatter +suite green). Three shapes, three root causes, all fixed where the bug +lived — format.rs — with verify.rs, the parser and the semantics +provably untouched, and the standing template honored: rejection tests +added anyway, four of them attacking the fixed paths specifically. +The dev's best decision was the one it did NOT make: the twelfth file +is a parser bug (take_before_open draining the pending-comment queue), +and it was filed as a specified Handshake instead of a cross-lane +edit — the directive round is delivering it. QA's two informational +pins are accepted as filed: the block-plus-line trailing-comment +boundary stays a clean refusal (the safety net's job, done), and the +`default ; // comment` stray space is a style wrinkle, not a token +change. 11 of 12 files independently confirmed on the real checkout, +corpus exactly at baseline. Formatter output changed, so the release +bumps the workspace version per the format-cache rule — flagged and +carried. Accepted; merged by the lead. + **2026-08-19 — lead. Verdict: accepted and committed as-is; no lead fixes needed.**