From 3325905f21e7b1cb7238298c04d4c28ca914bbe4 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 19 Aug 2026 03:22:13 -0700 Subject: [PATCH] Add macro-items: macro invocations at item/statement position The corpus-measured #1 blocker (~60% of RTL parse errors). Macro invocations (`NAME, `NAME(args), optional trailing ;) now parse wherever a module item or statement can appear; the invocation is an AST leaf (MacroCall{RawText, semi}) emitted verbatim with column- aware re-indent, semicolon reproduced only if written. Disambiguation is safe by construction: both readings emit identical token streams. The lexer's balanced-arg scan is hardened (strings, comments, 256-cap nesting counter, iterative). Corpus parse rate: 35.2% -> 57.1% (179 files gained, 0 regressed). Round 1 was rejected in review: QA proved the new verify.rs normalization could mask real corruption -- a string literal spanning lines inside a macro arg had its bytes changed by re-indent, with exit 0. The rework widened the finding to `define bodies and attributes (same pre-existing defect, same shared root) and fixed both sides: line_starts_inside_string, a lexer-mirroring scanner, is the single shared definition of "which line breaks are data" -- the verifier trims only outside strings, and the formatter emits any token with an in-string line break fully verbatim (idempotent by construction). Re-QA attacked the scanner on ten edge shapes and found no hole; corpus TSV byte-identical pre/post fix. Process consequence, codified as CLAUDE.md hard-invariant #4: any widening of verify.rs forgiveness ships with masked-corruption attack tests, dev-written and QA-re-attacked. Dev + rework: Opus agent; QA + re-QA: Sonnet agent; full history in docs/features/macro-items/README.md. Co-Authored-By: Claude Fable 5 --- CLAUDE.md | 7 + README.md | 26 +- crates/vlog_formatter/src/format.rs | 39 +- crates/vlog_formatter/src/verify.rs | 117 ++- .../vlog_formatter/tests/cases/macros.cases | 265 ++++++ crates/vlog_formatter/tests/verification.rs | 63 ++ crates/vlog_parser/src/ast.rs | 17 + crates/vlog_parser/src/lexer.rs | 168 +++- crates/vlog_parser/src/parser.rs | 115 +++ crates/vlog_parser/src/token.rs | 12 + docs/features/macro-items/README.md | 868 ++++++++++++++++++ 11 files changed, 1642 insertions(+), 55 deletions(-) create mode 100644 crates/vlog_formatter/tests/cases/macros.cases create mode 100644 docs/features/macro-items/README.md diff --git a/CLAUDE.md b/CLAUDE.md index 07718fc..b0b7957 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,6 +10,13 @@ doing anything. output or emits the input unchanged with an error. No partial output. 2. **Idempotent.** `format(format(x)) == format(x)`, always. 3. **Comments are never dropped.** +4. **Any widening of `verify.rs`'s forgiveness is guilty until proven + innocent.** Every new or broadened normalization in the safety net + ships WITH masked-corruption attack tests (crafted (input, corrupted + output) pairs the normalization could plausibly forgive, asserted + rejected) — written by the dev, re-attacked by QA. History: the one + real corruption vfmt ever produced (macro-items, 2026-08-19) slipped + through a normalization added without such tests. ## Simplicity first diff --git a/README.md b/README.md index 149a4d6..3110332 100644 --- a/README.md +++ b/README.md @@ -95,21 +95,33 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset: - Expressions: the full operator precedence table, ternaries, concatenation/replication, slices (`+:`/`-:`), casts (`int'(x)`), assignment patterns (`'{...}`), `inside`, hierarchical and package-scoped - names, macro usages in expression position + names +- Macro invocations (`` `NAME ``, `` `NAME(args) ``, with or without a + trailing `;`) in expression position **and** wherever a module item or a + statement can appear — module and package bodies, generate regions and + blocks, `begin`/`end` and `fork`/`join`, case-item and `if`/`else` bodies, + function and task bodies. The invocation is passed through verbatim (a + multi-line argument list keeps its own line structure, re-indented); a + trailing `;` is reproduced only if the source wrote one Not yet supported (parse errors). Roadmap ordered by measured impact on real RTL — see `docs/features/corpus-check/README.md` for the 820-file corpus baseline this ordering comes from: -1. Macro invocation at module-item / statement position - (`` `ASSERT_INIT(...) `` style) — ≈60% of RTL parse errors in the corpus -2. `bind` directives -3. Classes/constraints (mostly blocks DV/UVM code, not RTL) +1. ~~Macro invocation at module-item / statement position + (`` `ASSERT_INIT(...) `` style)~~ — **done**; see + `docs/features/macro-items/README.md`. Unblocked 179 corpus files and + moved the parse rate from 35.2% to 57.1% +2. Classes/constraints (mostly blocks DV/UVM code, not RTL) — now the top + blocker at 142 files, all `extends` +3. `bind` directives 4. Dynamic arrays and queues 5. Declarations with identifier (typedef'd) types in some positions (`my_t [N-1:0] x;`) -6. DPI, concurrent assertions (`assert property`), non-simple casts -7. Interfaces/modports, `case ... inside`, streaming operators, specify +6. `` `ifdef``/`` `define``/`` `include`` inside a port, parameter or enum + list (they are accepted at item and statement position already) +7. DPI, concurrent assertions (`assert property`), non-simple casts +8. Interfaces/modports, `case ... inside`, streaming operators, specify blocks, `let`/`checker`, sequences — rare in the corpus RTL Like ruff, `vfmt` refuses to output anything for a file it cannot fully diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs index 16f4b6e..1a66d1c 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -6,7 +6,9 @@ use crate::doc::*; use crate::printer::{contains_hard_line, Printer}; -use crate::verify::{verify_convergence, verify_equivalence, VerificationError}; +use crate::verify::{ + line_starts_inside_string, verify_convergence, verify_equivalence, VerificationError, +}; use vlog_parser::ast::*; use vlog_parser::token::Comment; @@ -109,11 +111,35 @@ impl<'a> Fmt<'a> { // Shared helpers // ------------------------------------------------------------------ - /// Verbatim text (a directive or an attribute), ready to be re-indented. + /// Verbatim text — a directive, an attribute, or a macro invocation — + /// ready to be re-indented. + /// + /// A token that carries a string literal across a line break is emitted + /// completely untouched instead: the leading whitespace of such a + /// continuation line is part of the string's *value*, and re-indenting it + /// would rewrite the string. Emitting the text as a single `Doc::Text` + /// means the printer copies the newlines through without adding indent, + /// so nothing changes and the result is a fixed point by construction. fn raw_text(&self, raw: &RawText) -> Doc { + if crosses_line_inside_string(&raw.text) { + return text(raw.text.clone()); + } self.raw_lines(&raw.text, raw.col) } + /// A macro invocation standing as an item or a statement. The invocation + /// itself is verbatim source — we do not expand macros, so re-spacing the + /// argument list would be guesswork — and the trailing `;` is reproduced + /// only if the source wrote one. + fn macro_call(&self, call: &MacroCall) -> Doc { + let body = self.raw_text(&call.raw); + if call.semi { + concat(vec![body, text(";")]) + } else { + body + } + } + /// A comment, ready to be re-indented at the printer's current level. fn comment(&self, c: &Comment) -> Doc { self.raw_lines(&c.text, c.col) @@ -322,6 +348,7 @@ impl<'a> Fmt<'a> { concat(docs) } ItemKind::Directive(d) => self.raw_text(d), + ItemKind::MacroItem(m) => self.macro_call(m), ItemKind::Import(paths) => text(format!("import {};", paths.join(", "))), ItemKind::Timeunit(t) => text(format!("{t};")), ItemKind::Typedef(t) => self.typedef(t), @@ -1363,6 +1390,7 @@ impl<'a> Fmt<'a> { StmtKind::Continue => text("continue;"), StmtKind::Disable(name) => text(format!("disable {name};")), StmtKind::Directive(d) => self.raw_text(d), + StmtKind::MacroStmt(m) => self.macro_call(m), StmtKind::Assert { kw, cond, then, els } => { let mut docs = vec![text(format!("{kw} ")), self.parens(cond)]; match (then, els) { @@ -1604,6 +1632,13 @@ impl<'a> Fmt<'a> { } /// Drop up to `n` leading spaces or tabs. +/// True if any line break in `text` falls inside a string literal, making +/// every byte of the following line part of that string's value rather than +/// layout. See [`crate::verify::line_starts_inside_string`]. +fn crosses_line_inside_string(text: &str) -> bool { + text.contains('\n') && line_starts_inside_string(text).iter().skip(1).any(|&inside| inside) +} + fn strip_blanks(line: &str, n: usize) -> &str { let mut rest = line; for _ in 0..n { diff --git a/crates/vlog_formatter/src/verify.rs b/crates/vlog_formatter/src/verify.rs index dbedda3..01c1bc9 100644 --- a/crates/vlog_formatter/src/verify.rs +++ b/crates/vlog_formatter/src/verify.rs @@ -223,16 +223,29 @@ fn comment_item(text: &str, line: u32, col: u32) -> Item { /// Token text as compared. Only the kinds the formatter re-indents are /// normalized; everything else must survive byte-for-byte. +/// +/// A macro usage lexes as an identifier whose text is the whole invocation, +/// argument list included, so a call spread over several lines is one token +/// with newlines in it — and the formatter re-indents its continuation lines +/// exactly like a continued `` `define ``. All three kinds can also carry a +/// *string literal* that spans a line break, whose leading whitespace is part +/// of its value, so they use the string-aware trim. Single-line tokens are +/// unaffected either way. fn normalize(kind: TokenKind, text: &str) -> String { match kind { - TokenKind::Directive | TokenKind::Attribute => trim_lines(text), + TokenKind::Directive | TokenKind::Attribute => trim_lines_outside_strings(text), + TokenKind::Ident if text.starts_with('`') => trim_lines_outside_strings(text), _ => text.to_string(), } } -/// Trim every line of a multi-line item. Re-indenting a block comment or a -/// continued `` `define`` changes the whitespace around its continuation -/// lines and nothing else, so that difference must not count as corruption. +/// Trim every line of a multi-line item. Re-indenting a block comment changes +/// the whitespace around its continuation lines and nothing else, so that +/// difference must not count as corruption. +/// +/// Used for comments only. A comment has no lexical structure inside it, so +/// every line boundary in one is pure layout — unlike the token kinds handled +/// by [`trim_lines_outside_strings`]. fn trim_lines(text: &str) -> String { if !text.contains('\n') { return text.to_string(); @@ -240,6 +253,102 @@ fn trim_lines(text: &str) -> String { text.lines().map(str::trim).collect::>().join("\n") } +/// Trim every line of a multi-line token, *except* at line boundaries that +/// fall inside a string literal. +/// +/// Whitespace next to a line break is normally pure layout, which is why +/// [`trim_lines`] can drop it. Inside a string literal it is not: it is part +/// of the value. A blind per-line trim there would let the formatter silently +/// re-indent the *contents of a string* and still pass this check — masked +/// corruption, and the reason this function exists (QA finding, 2026-08-19: +/// `` `uvm_info("id", "line one\n line two", UVM_LOW) `` had its string +/// rewritten with vfmt exiting 0). Leaving those lines untrimmed makes the +/// comparison byte-exact exactly where bytes are meaningful. +fn trim_lines_outside_strings(text: &str) -> String { + if !text.contains('\n') { + return text.to_string(); + } + let inside = line_starts_inside_string(text); + let lines: Vec<&str> = text.split('\n').collect(); + let mut out = Vec::with_capacity(lines.len()); + for (i, line) in lines.iter().enumerate() { + // `inside[i]` is the state entering this line, `inside[i + 1]` the + // state entering the next one — i.e. whether the newline that ends + // this line sits inside a string. + let start_trimmed = if inside[i] { line } else { line.trim_start() }; + out.push(if inside[i + 1] { start_trimmed } else { start_trimmed.trim_end() }); + } + out.join("\n") +} + +/// For each line of `text` split on `\n`, whether that line *begins* inside a +/// string literal. The returned vector has one more entry than there are +/// lines: the last is the state at the end of the text. +/// +/// Mirrors the lexer's own reading of a macro argument list +/// (`vlog_parser::lexer::scan_macro_args`): a `"` opens a string unless it is +/// inside a comment, `\` escapes the next character, and `//` / `/* */` +/// comments are skipped so a quote written inside one cannot open a string. +/// Shared with the formatter so both sides agree on which line breaks are +/// layout and which are data. +pub(crate) fn line_starts_inside_string(text: &str) -> Vec { + #[derive(PartialEq, Eq, Clone, Copy)] + enum State { + Code, + Str, + LineComment, + BlockComment, + } + + let bytes = text.as_bytes(); + let mut state = State::Code; + let mut out = vec![false]; + let mut i = 0usize; + while i < bytes.len() { + let c = bytes[i]; + match state { + State::Code => match c { + b'"' => state = State::Str, + b'/' if bytes.get(i + 1) == Some(&b'/') => { + state = State::LineComment; + i += 1; + } + b'/' if bytes.get(i + 1) == Some(&b'*') => { + state = State::BlockComment; + i += 1; + } + _ => {} + }, + State::Str => match c { + // An escape consumes the next byte, a line continuation + // inside a string included. + b'\\' => i += 1, + b'"' => state = State::Code, + _ => {} + }, + State::LineComment => { + if c == b'\n' { + state = State::Code; + } + } + State::BlockComment => { + if c == b'*' && bytes.get(i + 1) == Some(&b'/') { + state = State::Code; + i += 1; + } + } + } + // Record the state entering the next line. The newline itself never + // changes it (the line-comment case above already closed). + if bytes.get(i) == Some(&b'\n') { + out.push(state == State::Str); + } + i += 1; + } + out.push(state == State::Str); + out +} + /// 1-based number of the first differing line, with both versions of it. fn first_line_difference(a: &str, b: &str) -> (usize, String, String) { let mut a_lines = a.lines(); diff --git a/crates/vlog_formatter/tests/cases/macros.cases b/crates/vlog_formatter/tests/cases/macros.cases new file mode 100644 index 0000000..0962959 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/macros.cases @@ -0,0 +1,265 @@ +# bare macro invocation as a module item, no semicolon +module m; +`ASSERT_INIT +wire w; +endmodule +---- +module m; + `ASSERT_INIT + wire w; +endmodule +==== +# macro item with arguments and no trailing semicolon +module m; +`ASSERT_INIT(CheckNGreaterZero_A, N > 0) +endmodule +---- +module m; + `ASSERT_INIT(CheckNGreaterZero_A, N > 0) +endmodule +==== +# macro item with arguments keeps a trailing semicolon +module m; +`FFARNC(q, d, en, '0, clk_i, rst_ni); +endmodule +---- +module m; + `FFARNC(q, d, en, '0, clk_i, rst_ni); +endmodule +==== +# bare macro item keeps its semicolon +module m; +`MY_MACRO; +endmodule +---- +module m; + `MY_MACRO; +endmodule +==== +# macro item argument list spanning several lines is re-indented, not reflowed +module m; +`ASSERT(LongNameCheck_A, + a_i == b_i, + clk_i, !rst_ni) +endmodule +---- +module m; + `ASSERT(LongNameCheck_A, + a_i == b_i, + clk_i, !rst_ni) +endmodule +==== +# nested parens, brackets and braces inside macro arguments +module m; +`ASSERT_INIT(Nested_A, f(g(h(1))) == {a, b[3:0], '{c: 1}}) +endmodule +---- +module m; + `ASSERT_INIT(Nested_A, f(g(h(1))) == {a, b[3:0], '{c: 1}}) +endmodule +==== +# a string argument may contain an unbalanced parenthesis +module m; +`ASSERT_INIT(Msg_A, W > 0, "width must be > 0 (really)") +endmodule +---- +module m; + `ASSERT_INIT(Msg_A, W > 0, "width must be > 0 (really)") +endmodule +==== +# macro items between ordinary items, comments and blank lines preserved +module m; +// leading comment +`ASSERT_KNOWN(AKnown_A, a_i) // trailing comment + +wire w; +// before the second macro +`ASSERT_KNOWN(BKnown_A, b_i) +assign w = a_i; +endmodule +---- +module m; + // leading comment + `ASSERT_KNOWN(AKnown_A, a_i) // trailing comment + + wire w; + // before the second macro + `ASSERT_KNOWN(BKnown_A, b_i) + assign w = a_i; +endmodule +==== +# macro item inside a generate for block +module m; +generate +for (genvar i = 0; i < N; i++) begin : g_bit +`FF(q[i], d[i], '0, clk_i, rst_ni) +end +endgenerate +endmodule +---- +module m; + generate + for (genvar i = 0; i < N; i++) begin : g_bit + `FF(q[i], d[i], '0, clk_i, rst_ni) + end + endgenerate +endmodule +==== +# macro item inside a generate if / else block +module m; +if (Secure) begin : g_secure +`ASSERT_INIT(SecureWidth_A, W > 1) +end else begin : g_plain +`ASSERT_INIT(PlainWidth_A, W > 0) +end +endmodule +---- +module m; + if (Secure) begin : g_secure + `ASSERT_INIT(SecureWidth_A, W > 1) + end else begin : g_plain + `ASSERT_INIT(PlainWidth_A, W > 0) + end +endmodule +==== +# macro at statement position inside an always block +module m; +always_ff @(posedge clk_i) begin +`DV_CHECK(a_i) +q <= d; +end +endmodule +---- +module m; + always_ff @(posedge clk_i) begin + `DV_CHECK(a_i) + q <= d; + end +endmodule +==== +# macro statement with a trailing semicolon inside a begin/end block +module m; +initial begin +`uvm_info("id", "hello", UVM_LOW); +x = 1; +end +endmodule +---- +module m; + initial begin + `uvm_info("id", "hello", UVM_LOW); + x = 1; + end +endmodule +==== +# macro statement in a function body and in a task body +module m; +function automatic int f(input int a); +`TRACE_ENTER(f) +return a; +endfunction +task automatic t(); +`TRACE_ENTER(t) +endtask +endmodule +---- +module m; + function automatic int f(input int a); + `TRACE_ENTER(f) + return a; + endfunction + task automatic t(); + `TRACE_ENTER(t) + endtask +endmodule +==== +# macro item in a package body +package p; +`DEFINE_REGS(foo) +localparam int W = 8; +endpackage +---- +package p; + `DEFINE_REGS(foo) + localparam int W = 8; +endpackage +==== +# macro-defined type name still starts a declaration, not a macro item +module m; +`MY_TYPE_T sig; +`MY_TYPE_T [3:0] vec; +endmodule +---- +module m; + `MY_TYPE_T sig; + `MY_TYPE_T [3:0] vec; +endmodule +==== +# macro usage in expression position is unchanged +module m; +localparam int W = `WIDTH; +wire [`WIDTH-1:0] bus; +assign bus = `PACK(a_i, b_i); +endmodule +---- +module m; + localparam int W = `WIDTH; + wire [`WIDTH-1:0] bus; + assign bus = `PACK(a_i, b_i); +endmodule +==== +# a macro item may sit between two instantiations +module m; +`ASSERT_INIT(One_A, N > 0) +prim_flop u_a (.d(d_i), .q(q_o)); +`ASSERT_KNOWN(Known_A, q_o) +prim_flop u_b (.d(q_o), .q(r_o)); +endmodule +---- +module m; + `ASSERT_INIT(One_A, N > 0) + prim_flop u_a (.d(d_i), .q(q_o)); + `ASSERT_KNOWN(Known_A, q_o) + prim_flop u_b (.d(q_o), .q(r_o)); +endmodule +==== +# macro item at file scope, outside any module +`SOME_GLOBAL_MACRO(a, b) +module m; +wire w; +endmodule +---- +`SOME_GLOBAL_MACRO(a, b) +module m; + wire w; +endmodule +==== +# a string argument spanning lines keeps its own bytes: no line inside it is re-indented +module m; +if (X) begin : g +`uvm_info("id", "line one + line two", UVM_LOW); +end +endmodule +---- +module m; + if (X) begin : g + `uvm_info("id", "line one + line two", UVM_LOW); + end +endmodule +==== +# a `define whose body continues a string is passed through untouched +module m; +if (X) begin : g +`define MSG "line one \ + line two" +end +endmodule +---- +module m; + if (X) begin : g + `define MSG "line one \ + line two" + end +endmodule diff --git a/crates/vlog_formatter/tests/verification.rs b/crates/vlog_formatter/tests/verification.rs index b3981fc..a779ab6 100644 --- a/crates/vlog_formatter/tests/verification.rs +++ b/crates/vlog_formatter/tests/verification.rs @@ -39,6 +39,69 @@ fn multiline_block_comment_may_be_reindented() { verify_equivalence(input, output).expect("only per-line indentation changed"); } +#[test] +fn multiline_macro_invocation_may_be_reindented() { + // A macro usage lexes as one identifier token holding the whole + // invocation, so re-indenting its continuation lines changes that token's + // text — exactly like a continued `define, and normalized the same way. + let input = "module m;\n`A(x,\n y)\nendmodule\n"; + let output = "module m;\n `A(x,\n y)\nendmodule\n"; + verify_equivalence(input, output).expect("only per-line indentation changed"); +} + +/// QA repro (2026-08-19): a string literal inside a macro argument that spans +/// physical lines. Its continuation line's leading whitespace is part of the +/// string's *value*, so re-indenting it corrupts the string — and a blind +/// per-line trim in `normalize` used to report the pair as equivalent, so +/// `vfmt` exited 0 and wrote the corrupted file. The net must reject this. +#[test] +fn reindented_string_inside_a_macro_argument_is_rejected() { + let input = "module m;\nif (X) begin : g\n`uvm_info(\"id\", \"line one\n line two\", UVM_LOW);\nend\nendmodule\n"; + let output = "module m;\n if (X) begin : g\n `uvm_info(\"id\", \"line one\n line two\", UVM_LOW);\n end\nendmodule\n"; + expect_divergence(input, output); +} + +/// The same hole for a `` `define `` whose body carries a continued string, +/// and for an attribute — both are re-indented through the same path. +#[test] +fn reindented_string_inside_a_directive_or_attribute_is_rejected() { + let input = + "module m;\nif (X) begin : g\n`define MSG \"line one \\\n line two\"\nend\nendmodule\n"; + let output = "module m;\n if (X) begin : g\n `define MSG \"line one \\\n line two\"\n end\nendmodule\n"; + expect_divergence(input, output); + + let input = "module m;\n(* note = \"line one\n line two\" *)\nwire w;\nendmodule\n"; + let output = "module m;\n (* note = \"line one\n line two\" *)\n wire w;\nendmodule\n"; + expect_divergence(input, output); +} + +/// The whole point of the normalization survives the fix: a line break that is +/// *not* inside a string is still free to be re-indented. +#[test] +fn reindenting_outside_a_string_is_still_allowed() { + // The string ends on its own line, so the following break is layout. + let input = "module m;\n`A(\"msg\",\n x)\nendmodule\n"; + let output = "module m;\n `A(\"msg\",\n x)\nendmodule\n"; + verify_equivalence(input, output).expect("only per-line indentation changed"); + // A quote written inside a comment must not be read as opening a string. + let input = "module m;\n`A(x, // it's a \"quote\n y)\nendmodule\n"; + let output = "module m;\n `A(x, // it's a \"quote\n y)\nendmodule\n"; + verify_equivalence(input, output).expect("a quote inside a comment opens nothing"); +} + +#[test] +fn a_changed_macro_argument_is_still_rejected() { + let input = "module m;\n `A(x,\n y)\nendmodule\n"; + let output = "module m;\n `A(x,\n z)\nendmodule\n"; + match expect_divergence(input, output) { + VerificationError::Divergence { expected, got, .. } => { + assert!(expected.expect("expected item").text.contains('y')); + assert!(got.expect("got item").text.contains('z')); + } + other => panic!("wrong error: {other}"), + } +} + #[test] fn differing_token_is_rejected() { let err = expect_divergence("assign x = a;\n", "assign x = b;\n"); diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index 187c558..7c58303 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -25,6 +25,19 @@ pub struct RawText { pub col: u32, } +/// A macro invocation standing where a module item or a statement belongs +/// (`` `ASSERT_INIT(...) ``, `` `FFARNC(...) ``). Its arguments are token soup +/// handed to a preprocessor we do not run, so the whole invocation is kept as +/// verbatim source text — same treatment as a compiler directive. +#[derive(Debug)] +pub struct MacroCall { + /// The invocation from the backtick through the closing `)`, verbatim. + pub raw: RawText, + /// True if a `;` followed it in the source. Both spellings occur in real + /// RTL, so the formatter reproduces whichever one was written. + pub semi: bool, +} + #[derive(Debug)] pub struct SourceFile { pub items: Vec, @@ -50,6 +63,8 @@ pub enum ItemKind { end_label: Option, }, Directive(RawText), + /// Macro invocation used as a module item. + MacroItem(MacroCall), Import(Vec), Timeunit(String), Typedef(Typedef), @@ -507,6 +522,8 @@ pub enum StmtKind { Continue, Disable(String), Directive(RawText), + /// Macro invocation used as a statement. + MacroStmt(MacroCall), /// Immediate assertion: kept simple — `assert (expr) stmt else stmt;` Assert { kw: String, diff --git a/crates/vlog_parser/src/lexer.rs b/crates/vlog_parser/src/lexer.rs index 7f74d20..ab26f3b 100644 --- a/crates/vlog_parser/src/lexer.rs +++ b/crates/vlog_parser/src/lexer.rs @@ -56,6 +56,13 @@ const OPERATORS: &[&str] = &[ const SINGLE_OPS: &[u8] = b"+-*/%&|^~!<>=?:;,.#@()[]{}'$"; +/// How deeply brackets may nest inside a macro invocation's argument list. +/// +/// The scan is iterative, so this is not a stack bound — it is a guard that +/// turns pathologically unbalanced input into a lex error at the offending +/// position instead of a token that swallows the rest of the file. +const MAX_MACRO_ARG_NESTING: usize = 256; + impl<'a> RawLexer<'a> { fn new(src: &'a [u8]) -> Self { RawLexer { src, pos: 0, line: 1, col: 1 } @@ -130,19 +137,7 @@ impl<'a> RawLexer<'a> { return Ok(RawTok { kind: RawKind::LineComment, text, line, col, newlines_before }); } if c == b'/' && self.peek_at(1) == b'*' { - self.bump(); - self.bump(); - loop { - if self.pos >= self.src.len() { - return Err(self.error("unterminated block comment".to_string())); - } - if self.peek() == b'*' && self.peek_at(1) == b'/' { - self.bump(); - self.bump(); - break; - } - self.bump(); - } + self.skip_block_comment()?; let text = self.text_from(start); return Ok(RawTok { kind: RawKind::BlockComment, text, line, col, newlines_before }); } @@ -191,23 +186,9 @@ impl<'a> RawLexer<'a> { while is_ident_char(self.peek()) { self.bump(); } - // Macro call with arguments: `NAME(...) — capture balanced parens. + // Macro call with arguments: `NAME(...) — capture balanced text. if self.peek() == b'(' { - let mut depth = 0usize; - loop { - if self.pos >= self.src.len() { - return Err(self.error("unterminated macro call".to_string())); - } - let ch = self.bump(); - if ch == b'(' { - depth += 1; - } else if ch == b')' { - depth -= 1; - if depth == 0 { - break; - } - } - } + self.scan_macro_args()?; } let text = self.text_from(start); return Ok(RawTok { @@ -246,19 +227,7 @@ impl<'a> RawLexer<'a> { // String literal. if c == b'"' { - self.bump(); - loop { - if self.pos >= self.src.len() { - return Err(self.error("unterminated string literal".to_string())); - } - match self.bump() { - b'\\' => { - self.bump(); - } - b'"' => break, - _ => {} - } - } + self.skip_string()?; let text = self.text_from(start); return Ok(RawTok { kind: RawKind::Real(TokenKind::String), @@ -365,6 +334,90 @@ impl<'a> RawLexer<'a> { Err(self.error(format!("unexpected character {:?}", c as char))) } + /// Scan a macro invocation's argument list, from the `(` the caller is + /// sitting on through its matching `)`. + /// + /// Macro arguments are token soup, not an expression: they are handed to + /// the preprocessor, not to the grammar. So this only tracks bracket + /// nesting, and skips over strings and comments because either can hold + /// an unmatched bracket (`` `uvm_info("(", ...) ``). The scan is a flat + /// loop with an explicit counter — it never recurses, so the only reason + /// for [`MAX_MACRO_ARG_NESTING`] is to fail loudly on pathological input + /// instead of scanning to end of file. + fn scan_macro_args(&mut self) -> Result<(), LexError> { + let mut depth = 0usize; + loop { + if self.pos >= self.src.len() { + return Err(self.error("unterminated macro call".to_string())); + } + if self.peek() == b'"' { + self.skip_string()?; + continue; + } + if self.peek() == b'/' && self.peek_at(1) == b'/' { + while self.pos < self.src.len() && self.peek() != b'\n' { + self.bump(); + } + continue; + } + if self.peek() == b'/' && self.peek_at(1) == b'*' { + self.skip_block_comment()?; + continue; + } + match self.bump() { + b'(' | b'[' | b'{' => { + depth += 1; + if depth > MAX_MACRO_ARG_NESTING { + return Err(self.error(format!( + "macro argument nesting too deep (limit {MAX_MACRO_ARG_NESTING})" + ))); + } + } + b')' | b']' | b'}' => { + depth = depth.saturating_sub(1); + if depth == 0 { + return Ok(()); + } + } + _ => {} + } + } + } + + /// Consume a string literal starting at the opening quote. + fn skip_string(&mut self) -> Result<(), LexError> { + self.bump(); // opening quote + loop { + if self.pos >= self.src.len() { + return Err(self.error("unterminated string literal".to_string())); + } + match self.bump() { + b'\\' => { + self.bump(); + } + b'"' => return Ok(()), + _ => {} + } + } + } + + /// Consume a `/* ... */` comment starting at the opening `/`. + fn skip_block_comment(&mut self) -> Result<(), LexError> { + self.bump(); + self.bump(); + loop { + if self.pos >= self.src.len() { + return Err(self.error("unterminated block comment".to_string())); + } + if self.peek() == b'*' && self.peek_at(1) == b'/' { + self.bump(); + self.bump(); + return Ok(()); + } + self.bump(); + } + } + fn text_ends_with_continuation(&self, start: usize) -> bool { let text = &self.src[start..self.pos]; let trimmed: &[u8] = { @@ -664,6 +717,37 @@ mod tests { assert!(toks.iter().any(|(k, t)| *k == TokenKind::Ident && t == "`WIDTH")); } + #[test] + fn macro_call_captures_balanced_arguments() { + // Nested brackets of every flavour, a string and a comment holding + // unmatched brackets, and a call spread over two lines. + let src = "`A(f(g(1)), {b[3:0], '{c: 1}}, \"a )\", /* ) */ x, // )\n y) wire w;"; + let toks = kinds(src); + assert_eq!(toks[0].0, TokenKind::Ident); + assert_eq!(toks[0].1, "`A(f(g(1)), {b[3:0], '{c: 1}}, \"a )\", /* ) */ x, // )\n y)"); + assert_eq!(toks[1], (TokenKind::Keyword, "wire".to_string())); + } + + #[test] + fn unterminated_macro_call_is_a_lex_error() { + let err = tokenize("`A(a, b").expect_err("expected a lex error"); + assert!(err.message.contains("unterminated macro call"), "unexpected: {err}"); + } + + #[test] + fn deeply_nested_macro_arguments_are_a_lex_error() { + let src = format!("`A({}x{})", "(".repeat(400), ")".repeat(400)); + let err = tokenize(&src).expect_err("expected a lex error"); + assert!(err.message.contains("macro argument nesting too deep"), "unexpected: {err}"); + } + + #[test] + fn bare_macro_does_not_swallow_the_next_line() { + let toks = kinds("`BARE\n(a);"); + assert_eq!(toks[0], (TokenKind::Ident, "`BARE".to_string())); + assert_eq!(toks[1], (TokenKind::Symbol, "(".to_string())); + } + #[test] fn attributes() { let toks = kinds("(* keep = \"true\" *) wire w;"); diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index 9b8d6f5..2bc20c0 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -292,6 +292,48 @@ impl Parser { RawText { text: self.bump().text, col } } + /// True when the macro usage at the cursor stands on its own as an item or + /// a statement rather than opening a declaration, an instantiation or an + /// expression. + /// + /// The lexer hands us the whole invocation as one token, so this is a + /// one-token lookahead: + /// + /// * next token is `;` — always a standalone invocation; + /// * next token is any other symbol — an expression or declaration + /// continues (`` `MACRO(x) = y; ``, `` `MOD #(...) u(); ``, + /// `` `TYPE [3:0] x; ``); + /// * next token is a plain identifier — `` `TYPE x; `` / + /// `` `MOD u (...); ``, *unless* this invocation has an argument list, + /// which no type or module name in real RTL does; + /// * anything else (a keyword, another macro, a directive, end of file) — + /// the invocation stands alone. + /// + /// Guessing wrong cannot corrupt code: either reading emits the same + /// tokens in the same order, so the equivalence check still passes and + /// only the line breaks differ. + fn at_macro_item(&self) -> bool { + if !self.cur().is_macro() { + return false; + } + let next = self.nth(1); + if next.is_sym(";") { + return true; + } + match next.kind { + TokenKind::Symbol => false, + TokenKind::Ident if !next.is_macro() => self.cur().has_macro_args(), + _ => true, + } + } + + /// Consume a standalone macro invocation and its optional trailing `;`. + fn parse_macro_call(&mut self) -> MacroCall { + let raw = self.take_raw_text(); + let semi = self.eat_sym(";"); + MacroCall { raw, semi } + } + /// Take the comments the lexer attached *before* the current token, /// bypassing the usual pending-comment plumbing so a construct can keep /// them itself. Must be called before the token is consumed. @@ -375,6 +417,9 @@ impl Parser { } fn parse_item_kind(&mut self) -> PResult { + if self.at_macro_item() { + return Ok(ItemKind::MacroItem(self.parse_macro_call())); + } let t = self.cur(); match t.kind { TokenKind::Directive => Ok(ItemKind::Directive(self.take_raw_text())), @@ -1354,6 +1399,9 @@ impl Parser { } fn parse_stmt_kind(&mut self) -> PResult { + if self.at_macro_item() { + return Ok(StmtKind::MacroStmt(self.parse_macro_call())); + } let t = self.cur(); if t.kind == TokenKind::Directive { return Ok(StmtKind::Directive(self.take_raw_text())); @@ -2390,4 +2438,71 @@ mod tests { endmodule", ); } + + #[test] + fn macro_items_and_statements() { + let file = parse_ok( + "`GLOBAL_MACRO(a, b) + package p; + `DEFINE_REGS(foo) + endpackage + module m; + `ASSERT_INIT(Check_A, N > 0) + `FFARNC(q, d, en, '0, clk_i, rst_ni); + `BARE + `BARE_SEMI; + generate + for (genvar i = 0; i < N; i++) begin : g + `FF(q[i], d[i], '0, clk_i, rst_ni) + end + endgenerate + always_ff @(posedge clk_i) begin + `DV_CHECK(a_i) + `uvm_info(\"id\", \"m\", UVM_LOW); + q <= d; + end + function automatic int f(); + `TRACE_ENTER(f) + return 0; + endfunction + endmodule", + ); + assert!(matches!(file.items[0].kind, ItemKind::MacroItem(_))); + } + + /// The one-token lookahead in `at_macro_item` must not steal a macro that + /// names a type, a module or the target of an assignment. + #[test] + fn macro_lookahead_leaves_declarations_alone() { + let file = parse_ok( + "module m; + `MY_TYPE_T sig; + `MY_TYPE_T [3:0] vec; + `MY_MODULE u_inst (.a(sig)); + `MY_MODULE #(.W(8)) u_param (.a(sig)); + initial `LVALUE(x) = 1; + assign y = `PACK(a, b); + endmodule", + ); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + assert!( + !m.items.iter().any(|i| matches!(i.kind, ItemKind::MacroItem(_))), + "no item should have been read as a standalone macro invocation" + ); + } + + #[test] + fn macro_semicolon_is_reproduced_not_invented() { + let file = parse_ok("module m;\n`A(x)\n`B(y);\nendmodule"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let semis: Vec = m + .items + .iter() + .map(|i| match &i.kind { + ItemKind::MacroItem(call) => call.semi, + other => panic!("expected a macro item, got {other:?}"), + }) + .collect(); + assert_eq!(semis, [false, true]); + } } diff --git a/crates/vlog_parser/src/token.rs b/crates/vlog_parser/src/token.rs index 9f2304f..75e444f 100644 --- a/crates/vlog_parser/src/token.rs +++ b/crates/vlog_parser/src/token.rs @@ -69,6 +69,18 @@ impl Token { pub fn is_sym(&self, sym: &str) -> bool { self.kind == TokenKind::Symbol && self.text == sym } + + /// True for a macro usage token: a backtick name that is not one of the + /// line-oriented compiler directives (those lex as [`TokenKind::Directive`]). + /// The text is the whole invocation, argument list included. + pub fn is_macro(&self) -> bool { + self.kind == TokenKind::Ident && self.text.starts_with('`') + } + + /// True if this macro usage carries an argument list: `` `NAME(...) ``. + pub fn has_macro_args(&self) -> bool { + self.is_macro() && self.text.contains('(') + } } /// Reserved words we treat as keywords. This covers Verilog-2001 plus the diff --git a/docs/features/macro-items/README.md b/docs/features/macro-items/README.md new file mode 100644 index 0000000..1a66dd5 --- /dev/null +++ b/docs/features/macro-items/README.md @@ -0,0 +1,868 @@ +# macro-items + +## Goal + +Support macro invocations where a **module item** or a **statement** belongs — +`` `ASSERT_INIT(CheckN_A, N > 0) ``, `` `FFARNC(q, d, en, '0, clk_i, rst_ni) ``, +`` `uvm_info("id", "m", UVM_LOW); ``. `docs/features/corpus-check/README.md` +measured this as the single largest blocker in the 820-file corpus: ≥200 files, +38% of all parse errors and **60% of parse errors in synthesizable RTL**, +because both lowRISC and PULP build their register and assertion layers out of +these. The README claimed macro usage was supported "in expression position", +which is the half real RTL needs least. The macro body is a preprocessor +concern we deliberately do not model: the invocation is carried through the +formatter as verbatim source text, exactly like `` `define `` and `(* attr *)`` +already are, so support costs one AST leaf rather than a grammar. + +## Assumptions + +- **A macro invocation is opaque text, not a parse tree.** Its arguments are + handed to a preprocessor we do not run, so re-spacing them would be guesswork + (`` `FF(q, d) `` and `` `FF(q,d) `` can expand into different token streams + when the macro pastes with `` ## ``). The invocation is therefore reproduced + byte-for-byte apart from the indentation of continuation lines. +- **The lexer already delivers the whole invocation as one token.** A backtick + name that is not one of the line-oriented directives lexes as + `TokenKind::Ident` whose text runs from the backtick through the matching + `)`. This feature did not change that shape — it made the scan correct + (strings/comments) and taught the *parser* to accept the token at item and + statement position. +- **One-token lookahead is enough to tell a standalone invocation from a + macro-named type or module.** See `Parser::at_macro_item`. Two shapes are + deliberately resolved *against* being a macro item, because real RTL uses + them: `` `MY_TYPE_T sig; `` (bare macro + identifier) and + `` `MY_MODULE #(.W(8)) u (...); `` (bare macro + symbol). The one shape this + gets wrong is a *parameterized* macro type — `` `SOME_TYPE(8) sig; `` — which + would be read as a standalone invocation followed by a broken declaration. No + file in the corpus does this. +- **Guessing wrong cannot corrupt code.** Both readings emit the same tokens in + the same order; only line breaks differ. So a misclassification shows up as + odd layout, never as a failed equivalence check or a rewritten file. This is + what makes the heuristic acceptable at all. +- **Both semicolon spellings exist and neither is canonical.** `` `ASSERT* `` + macros are written without a trailing `;` (the macro body supplies it), + `` `uvm_* `` macros with one. Adding or removing one would change the token + stream, so the formatter reproduces whatever was written. +- **A macro invocation is never re-wrapped to fit the line limit.** A 140-column + `` `ASSERT(...) `` stays 140 columns. Breaking it would mean choosing split + points inside token soup. +- **A space before the argument list is not an invocation-with-args.** The + lexer only attaches a `(` that immediately follows the macro name + (`lexer.rs`, `self.peek() == b'('`, no whitespace skip), so + `` `M (a, b); `` lexes as a bare `` `M `` followed by the symbol `(`. + `at_macro_item` then sees a symbol and declines, and the file gets a clean + parse error rather than any output. Known usability gap, not corruption; + the workaround is to write the call tight, `` `M(a, b); ``, which is how + every call site in the corpus is written. Left unfixed this round (QA + finding, 2026-08-19) — the fix is a whitespace skip in the lexer, but it + would also make `` `WIDTH (a + b) `` in expression position swallow a + following parenthesized expression, which needs its own thought. +- **Whitespace next to a line break inside a *string literal* is data, not + layout.** This is the premise the first round of this feature got wrong; see + the QA finding and the fix under Handshakes and Design. Everywhere else in a + raw token, whitespace around a line break is layout and may be rewritten. +- **Comments inside an argument list ride along inside the token.** They are + never dropped (invariant #3 holds) but they are also not re-indented + individually and do not force anything to break — they are part of the raw + text on both sides of the comparison. + +## Handshakes + +**Consumed from `vlog_parser::lexer`:** a macro usage arrives as one +`TokenKind::Ident` token whose `text` starts with `` ` `` and, when the macro +has arguments, contains the whole balanced argument list including any +newlines. `Token::is_macro()` / `Token::has_macro_args()` are the predicates; +use those rather than open-coding a `starts_with('`')`. + +**Promised to `vlog_formatter`:** + +- `ItemKind::MacroItem(MacroCall)` and `StmtKind::MacroStmt(MacroCall)`, where + `MacroCall { raw: RawText, semi: bool }`. `raw.col` is the 1-based column the + backtick stood in, and it is load-bearing: it is what + `Fmt::raw_lines` dedents continuation lines by before the printer re-indents + them. Formatting a multi-line invocation without honoring `col` does not + converge — this is the same contract `ItemKind::Directive` and `Meta::attrs` + already have. +- The trailing `;` is *not* part of `raw.text`; `semi` records whether one was + written. + +**Consumed from / requested of `verify.rs` (extended by this feature):** +`normalize()` now routes a `TokenKind::Ident` whose text starts with a +backtick through the per-line trim, alongside `Directive` and `Attribute` — +and that trim is now **string-aware** (`trim_lines_outside_strings`). +Reasoning, since this widens what the safety net tolerates: + +- A multi-line invocation is *one token* containing newlines. The formatter + re-indents its continuation lines (it must, or output at a new indent level + would never reach a fixed point), which changes that token's text. +- Without the extension, every multi-line macro item in the corpus would fail + equivalence and be refused — the check would be rejecting the formatter's own + correct behavior, the same situation `Directive` was already in. +- **A blind per-line trim is not safe here**, which is what round 1 shipped and + QA caught. Whitespace next to a line break is only layout when that break is + *outside* a string literal; inside one it is part of the value. See the + string-literal section under Design. +- It stays narrow: it only affects tokens containing a newline (early return + otherwise), only the three raw-text kinds, and only whitespace at line edges + outside strings. Any change to an argument, an added or removed token, a + dropped comment, or a rewritten string is still caught — see + `a_changed_macro_argument_is_still_rejected` and + `reindented_string_inside_a_macro_argument_is_rejected` in + `tests/verification.rs`. +- Comments keep the plain `trim_lines`. A comment has no lexical structure + inside it, so a quote written in one opens nothing and every line break in + one is pure layout; applying string-awareness there would make an unbalanced + quote inside a block comment freeze its indentation for no reason. + +**Promised to `vlog_formatter::format`:** `verify::line_starts_inside_string` +is `pub(crate)` and is the single shared definition of "which line breaks are +inside a string". Both sides must use it, or the formatter can rewrite bytes +the net believes are layout — that gap is exactly the bug below. + +**Recursion/chain budgets (`docs/features/recursion-limit/README.md`):** no new +budget is charged and none is needed. A macro item/statement is an AST **leaf** +— it holds a `String`, not a `Box` — so it adds no root-to-leaf depth and +the formatter's walk terminates at it. Nesting *through* generate blocks and +`begin`/`end` still goes through the already-gated `parse_item`/`parse_stmt`. +No loop in this feature boxes a base expression per iteration, so the +`link()` requirement in that feature's Handshakes does not apply. The lexer's +argument scan is a flat `loop` with an explicit `usize` counter (never +recursion) and is capped at `MAX_MACRO_ARG_NESTING = 256` so pathological input +becomes a lex error at the offending position instead of a token that swallows +the file. + +## Design + +### Lexer — `scan_macro_args` (`crates/vlog_parser/src/lexer.rs`) + +The previous scan counted `(` and `)` only, so `` `uvm_info("a )", ...) `` or a +`//` comment holding a bracket would end the token in the wrong place. The scan +now: + +- tracks `(`/`[`/`{` against `)`/`]`/`}` with one `usize` counter; +- skips string literals and both comment forms wholesale, because either can + hold an unmatched bracket; +- errors with `unterminated macro call` at end of input, and with + `macro argument nesting too deep (limit 256)` past the cap. + +The string- and block-comment skips were factored out of the existing token +paths (`skip_string`, `skip_block_comment`) rather than duplicated. + +### Parser — `at_macro_item` (`crates/vlog_parser/src/parser.rs`) + +One predicate, called from the top of both `parse_item_kind` and +`parse_stmt_kind`, so every position that reaches those — module body, package +body, `generate` region, generate `if`/`for`/`case` blocks, `begin`/`end`, +`fork`/`join`, case-item bodies, `if`/`else` branches, function and task bodies +— accepts a macro invocation without any per-site code. + +| next token | verdict | why | +|---|---|---| +| `;` | macro item | always standalone | +| any other symbol | not a macro item | `` `M(x) = y; ``, `` `MOD #(...) u(); ``, `` `T [3:0] x; ``, `` `M(x).f `` | +| plain identifier | macro item **iff** this invocation has an argument list | `` `T x; `` is a declaration; `` `ASSERT(A, 1) prim_flop u(...) `` is not | +| another macro / keyword / directive / EOF / anything else | macro item | nothing can continue the previous construct | + +The "has an argument list" clause is what makes a macro item that is directly +followed by an instantiation work, which is a common shape in the corpus. + +### Formatter — `Fmt::macro_call` (`crates/vlog_formatter/src/format.rs`) + +`raw_text(&call.raw)` plus `";"` when `call.semi`. `raw_text` is the existing +`RawText.col` path: single-line text passes through as one `Doc::Text`; +multi-line text is split, each continuation line dedented by `col - 1`, and the +printer prepends the current indent after each `HardLine`. That is what makes +re-indenting converge in one pass instead of drifting right forever. + +### String literals that span a line break (QA round 1 fix) + +A raw token can carry a string literal across a physical line — the lexer +accepts a bare newline inside a string, and `` `uvm_info``-family macros exist +precisely to carry free text: + +```systemverilog +`uvm_info("id", "line one + line two", UVM_LOW); +``` + +The leading whitespace of `line two` is part of the string's **value**. +Round 1 re-indented it like any other continuation line (QA measured 3 spaces +becoming 7) *and* masked the change in `verify.rs`, so `vfmt` exited 0 and +wrote corrupted code — a real violation of hard invariant #1. The same hole +existed for `` `define `` bodies with a `\`-continued string and for +`(* attr = "..." *)`; both pre-date this feature and are fixed here too, since +all three share `raw_lines`/`trim_lines`. + +Fixed on both sides, deliberately, so neither alone is load-bearing: + +1. **The net** (`verify.rs`): `trim_lines_outside_strings` trims a line's start + only when that line does not *begin* inside a string, and its end only when + the newline ending it is not inside a string. `line_starts_inside_string` + computes those states with a small state machine that mirrors the lexer — + `\` escapes, and `//` / `/* */` comments are skipped so a quote written + inside a comment cannot open a string. +2. **The formatter** (`format.rs`): `raw_text` checks + `crosses_line_inside_string` first and, if any break falls inside a string, + emits the token as one `Doc::Text` with **no re-indent of any line**. The + printer copies embedded newlines through without adding indent, so nothing + about the token changes and the result is a fixed point by construction. + +The all-or-nothing formatter rule was chosen over a per-line "re-indent only +the lines outside strings" scheme: the latter has to reason about convergence +for a token whose lines move independently, and buys nothing — a macro +carrying a multi-line string is already unformattable text. Because the +formatter now changes such a token not at all, the two sides cannot disagree: +tokens with a string-crossing break compare byte-for-byte, and tokens without +one behave exactly as before. + +## Status / TODO + +- [x] Lexer: balanced argument scan skips strings and comments; nesting cap + with a clean lex error; string/block-comment skips deduplicated. +- [x] `Token::is_macro()` / `Token::has_macro_args()`. +- [x] AST: `MacroCall`, `ItemKind::MacroItem`, `StmtKind::MacroStmt`. +- [x] Parser: `at_macro_item` lookahead + `parse_macro_call`, wired into + `parse_item_kind` and `parse_stmt_kind`. +- [x] Formatter: `Fmt::macro_call`, verbatim via the `RawText.col` path. +- [x] `verify.rs`: `normalize` trims lines of backtick identifiers; reasoning + recorded under Handshakes. +- [x] 20 cases in `crates/vlog_formatter/tests/cases/macros.cases`. +- [x] 3 parser unit tests + 4 lexer unit tests + 5 verification tests. + +From QA round 1 (2026-08-19): + +- [x] **Blocking:** masked corruption of a string literal spanning a line + break inside a macro argument. Fixed on both sides — string-aware trim + in `verify.rs`, verbatim pass-through in `format.rs`. QA's repro is now + a test asserting `verify_equivalence` **rejects** the pair. +- [x] Checked and covered the same hole for `Directive` (`` `define `` with a + `\`-continued string) and `Attribute` — both reproduce identically + before the fix and are fixed by the same change. +- [x] Non-blocking note recorded in Assumptions: `` `M (a, b); `` with a space + before the paren is not treated as an invocation-with-args and + parse-errors; workaround documented, fix deferred with a reason. +- [x] Corpus acceptance: 3 named files, before/after recorded below. +- [x] Full corpus re-run; new parse rate recorded below. +- [x] `README.md` supported-syntax updated, roadmap item 1 struck. +- [x] `cargo test --workspace` green, `cargo clippy --all-targets` silent, + `cargo fmt --check` clean. +- [ ] **Not done, deliberately:** breaking an over-long invocation across + lines. Would require choosing split points inside token soup; the only + defensible rule (split at top-level commas) still guesses at whether the + macro pastes its arguments. Revisit only if someone asks. +- [ ] **Not done:** `` `ifdef ``/`` `define ``/`` `include `` in *nested* + positions (inside a port list, an enum body, a parameter list). This is + the remaining backtick-shaped blocker in the corpus — 12 files, see the + corpus section below. Different feature: those are `Directive` tokens, + not macro usages. + +## Corpus results + +Re-ran `./tools/corpus_check.sh corpus` against the same pinned 820-file corpus +as the baseline in `docs/features/corpus-check/README.md`. The corpus was +verified unmodified afterwards (`git status --porcelain` clean in all four +repos; only the untracked `.vfmt-corpus-rev` stamps show). + +| metric | baseline (35.2% era) | after macro-items | +|---|---|---| +| **parsed** (reached the formatter) | 289/820 (**35.2%**) | 468/820 (**57.1%**) | +| formattable (parsed *and* passed the safety net) | 265/820 (32.3%) | 422/820 (51.5%) | +| parse-error | 531 (64.8%) | 352 (42.9%) | +| verification-error | 24 (2.9%) | 46 (5.6%) | +| crash | 0 | 0 | +| already format-clean | 1 | 2 | + +``` +outcome files share +-------------------- ----- ------- +ok-unchanged 2 0.2% +would-reformat 420 51.2% +parse-error 352 42.9% +verification-error 46 5.6% +other-error 0 0.0% +crash 0 0.0% +-------------------- ----- ------- +total 820 100.0% +``` + +Per repo (files / clean / would-reformat / parse-error / verification-error): +common_cells 131 / 0 / 75 / 41 / 15; ibex 613 / 2 / 309 / 273 / 29; +opentitan 35 / 0 / 5 / 29 / 1; picorv32 41 / 0 / 31 / 9 / 1. + +**Honest reading of the numbers.** + +- **179 files** moved from `parse-error` to parsed. **Zero** files regressed the + other way (checked by diffing the two TSVs by path, not just by count). +- 159 of those 179 had a first error whose "found" token was literally a macro + invocation; the other 20 were blocked *behind* one (the parser reported the + next token — `end`, `endmodule`, `logic`, `assign` — after failing to consume + a macro call, which is exactly the under-counting the corpus README warned + about when it called ≥200 a floor). +- The corpus README predicted ≥200 files unblocked. **179 is the honest + figure**, and the gap is what that README also predicted: many macro-blocked + files contain a *second* blocker (classes/UVM, `bind`, `interface`, dynamic + arrays) and so still land in `parse-error`, just with a different first error. + The top remaining blocking token is now `extends` (142 files, UVM classes), + which was previously invisible behind macros. +- **Verification errors rose 24 → 46 (+22).** None of them involve a macro + token. All 22 are the pre-existing root causes A–C catalogued in the + corpus-check README — event-list `,` rewritten as `or`, comments dropped from + port/parameter lists and `always` blocks, consecutive header `import`s merged + — in files that previously died at the parser and now reach the safety net. + That is the expected consequence of parsing more code, and it belongs to the + formatter-bug-fixes round, not here. The safety net refused output for every + one of them, so no file was corrupted. +- Only 12 parse errors still name a backtick token, and all 12 are + `` `ifdef ``/`` `define ``/`` `include `` *directives* in nested positions + (inside a port list, an enum body, a parameter list) — a separate gap, listed + under Status/TODO. + +### Corpus acceptance files + +Three real corpus files that were blocked *only* on this construct. All three +now parse, format, and are a fixed point on a second pass (formatted a copy in +a scratchpad, then `--check` on the result → exit 0). The corpus itself was +never written to. + +| file | before | after | +|---|---|---| +| `corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_arbiter_fixed.sv` | `parse-error` at 41:3, "expected declaration or instantiation", found `` `ASSERT_INIT(CheckNGreaterZero_A, N > 0) `` | `would-reformat`, round-trip idempotent | +| `corpus/common_cells/src/credit_counter.sv` | `parse-error` at 45:3, "expected declaration or instantiation", found `` `FFARNC(credit_q, credit_d, credit_init_i, InitNumCredits, clk_i, rst_ni) `` | `would-reformat`, round-trip idempotent | +| `corpus/common_cells/src/lfsr_8bit.sv` | `parse-error` at 58:3, "expected declaration or instantiation", found `` `ASSERT_INIT(width_gt_8, WIDTH <= 8, "…") `` | `would-reformat`, round-trip idempotent | + +The first is a lowRISC prim with the `` `ASSERT_* `` family, the second a PULP +`` `FF* `` register macro, the third a `` `ASSERT_INIT `` with a string +argument — one file per dialect the corpus README named. + +## Work log + +### 2026-08-19 — dev agent + +- Read `CLAUDE.md`, `README.md`, `docs/features/corpus-check/README.md` and + `docs/features/recursion-limit/README.md` (Handshakes) before touching code. + Baseline: `cargo test --workspace` 86 passed, clippy silent, fmt clean. +- **First surprise: the lexer already produced the right token.** A backtick + name that is not a line directive was already lexed as one `Ident` carrying + the balanced argument list — the expression-position support depends on it. + So this was never a lexing feature; the gap was entirely in the parser, which + is why it is as cheap as the corpus README predicted. +- **Second surprise: the old behavior was worse than "parse error".** On + `` `A(x)\n`B(y)\nwire w; `` the parser did not reject the macro — it read + `` `A(x) `` as a *type* and `` `B(y) `` as a declarator name and only failed + at the `wire` three tokens later. The diagnostic pointed at the wrong line, + and it is only luck (nothing downstream parsed) that this never produced + output. That is what made `at_macro_item` a *predicate consulted first* + rather than a fallback in the error path. +- **Chose one-token lookahead over a two-token or content-based rule.** The + alternatives considered: (a) always treat a backtick token at item position + as a macro item — breaks `` `MY_TYPE_T sig; ``, which the corpus does + contain; (b) look at whether the *next* token could start a new item — needs + a keyword whitelist that has to be kept in sync with `parse_keyword_item`; + (c) the shipped rule, which asks only "does something continue this + construct" and uses "has an argument list" to break the one genuinely + ambiguous tie. (c) is the only one that also handles a macro item directly + followed by an instantiation, which is common in lowRISC prims. +- **Verified the failure mode of a wrong guess before relying on it.** Both + readings of an ambiguous macro emit the same tokens in the same order, so the + equivalence check cannot fire and a file can never be corrupted by a + misclassification — only laid out oddly. Recorded under Assumptions because + it is the property that makes a heuristic acceptable in a formatter with + CLAUDE.md's invariant #1. +- **Hardened the lexer scan while I was in there**, because macro-item support + makes it reachable on far more code: the old scan counted only parentheses, + so `` `uvm_info("a )", ...) `` (string) and a `//` comment holding a bracket + ended the token early. Added `[`/`{` tracking plus string/comment skipping, + and factored `skip_string`/`skip_block_comment` out of the two existing + token paths rather than writing a third copy of each. +- **Capped argument nesting at 256** per the recursion-limit Handshakes. Noted + explicitly in the code comment that this is *not* a stack bound — the scan is + a flat loop — but a guard against a token that swallows the rest of the file. + The macro node itself is an AST leaf, so no `enter()`/`link()` charge is + correct here; recorded the reasoning under Handshakes so the next reader does + not have to re-derive it. +- **`verify.rs` extension was necessary, and was confirmed necessary by + experiment first.** Formatting a multi-line invocation from column 1 to + column 3 changes the token's own text, which failed equivalence before the + change. Kept the extension to one arm (`Ident` starting with a backtick) and + added a test proving a genuinely changed argument is still caught, so the + widened tolerance is pinned by a test rather than by prose. +- Idempotency of the multi-line case was checked the hard way (format, then + `--check` the result) on hand-written inputs at three different starting + columns *and* on all three corpus acceptance files, not just via the case + table. +- Corpus re-run diffed by path against the committed baseline TSV: 179 files + gained, **0 lost**, and all 22 new verification errors traced back to the + four root causes already catalogued in the corpus-check README (none touches + a macro token). Confirmed all four corpus repos unmodified afterwards. +- Did not touch `tools/`, `corpus/`, `crates/vfmt/` or `TODO.md` (no matching + checkbox exists). Did not run `git commit`/`git push`. + +**Results:** `cargo test --workspace` **95 passed, 0 failed** (up from 86: +4 +`vlog_parser` lexer unit, +3 `vlog_parser` parser unit, +2 `vlog_formatter` +verification; the case table grew from 200 to 218 cases inside its single +test). `cargo clippy --all-targets` silent. `cargo fmt --check` clean. +Files touched: `crates/vlog_parser/src/{lexer,token,ast,parser}.rs`, +`crates/vlog_formatter/src/{format,verify}.rs`, +`crates/vlog_formatter/tests/cases/macros.cases` (new), +`crates/vlog_formatter/tests/verification.rs`, `README.md`, this README. + +### 2026-08-19 (later) — dev agent, answering QA round 1 + +- **Reproduced the blocking finding before touching anything**, end-to-end + through the real debug binary rather than from the QA write-up: the string's + second line went from 3 leading spaces to 7, `vfmt` exited 0, and the file + was written. Confirmed QA's point that convergence does not help — the + corrupted output is a stable fixed point, so re-formatting reproduces it. +- **Widened the finding before fixing it.** QA reported it against macro + arguments; the defect is in `raw_lines` + `trim_lines`, which `Directive` + and `Attribute` share. Built repros for both and confirmed the same + corruption pre-dates this feature: `` `define MSG "line one \ `` plus a + continuation line went 3 → 7 leading spaces, and `(* note = "..." *)` went + 3 → 4. Fixing only the macro path would have left two live instances of the + same bug in the tree. +- **Fixed the net first, as instructed**, then the formatter, so neither is + solely load-bearing. The shared piece is + `verify::line_starts_inside_string`, `pub(crate)` and used by both — one + definition of which line breaks are data, because two definitions drifting + apart is precisely how this bug happened. +- **Chose the all-or-nothing formatter rule** (a token with a string-crossing + break is emitted verbatim, no line re-indented) over per-line + re-indent-outside-strings. Rationale in Design: it is idempotent by + construction rather than by argument, and it guarantees the two sides agree + — for such a token the formatter changes nothing, so the comparison is + byte-exact regardless of what the trim would have allowed. +- **Kept string-awareness off comments.** `comment_item` still uses the plain + `trim_lines`: a comment has no lexical structure inside it, so a lone quote + in a block comment must not freeze that comment's indentation. Getting this + wrong would have been a regression in the opposite direction — legitimate + comment re-indents starting to fail verification. +- **Made the state machine mirror the lexer**, not just track quotes: `\` + escapes, and `//` / `/* */` comments are skipped, so a quote inside a + comment cannot open a string and a `//` inside a string cannot open a + comment. Verified all four combinations on the real binary + (`` `A(/* " */ "real⏎ string") ``, `` `A("has \" escaped⏎ more") ``, + `` `A("http://x.com",⏎ y) ``, `` `A("msg",⏎ y) ``): the first two are + passed through verbatim, the last two are re-indented normally, all four + idempotent. +- Added QA's repro as `reindented_string_inside_a_macro_argument_is_rejected` + (asserts the net **rejects** the pair), plus directive/attribute variants, a + test that re-indenting *outside* a string is still allowed, and two + case-table entries asserting the string's bytes survive a real format. +- **Corpus re-run after the fix: byte-identical TSV to the pre-fix run** — + 468/820 parsed (57.1%), 422 formattable, 352 parse-error, 46 + verification-error, 0 crash; 179 gained, **0 lost** against the committed + baseline. Honest delta from this fix: **zero**, because no corpus file + carries a string across a line break inside a macro, directive or attribute. + The fix is about what vfmt would do to code it has not met yet, which is the + whole point of the net. All four corpus repos confirmed unmodified. + +**Results:** `cargo test --workspace` **98 passed, 0 failed** (up from 95: +3 +verification tests; the macro case table grew 18 → 20 inside its single test). +`cargo clippy --all-targets` silent. `cargo fmt --check` clean. Files touched +this round: `crates/vlog_formatter/src/{verify,format}.rs`, +`crates/vlog_formatter/tests/verification.rs`, +`crates/vlog_formatter/tests/cases/macros.cases`, this README. + +## QA log + +### 2026-08-19 — QA agent + +**Scope.** Verified the six claims in the dev's work log against the working +tree as found (`README.md`, `crates/vlog_parser/src/{lexer,parser,ast,token}.rs`, +`crates/vlog_formatter/src/{format,verify}.rs`, +`crates/vlog_formatter/tests/{cases/macros.cases,verification.rs}`). Did not +touch `tools/` or `corpus/` contents; ran `tools/corpus_check.sh` read-only. +Made no permanent changes — `git status --porcelain` before and after this +pass is identical (8 modified + 2 untracked, all the dev's). All adversarial +inputs and scratch tests referenced below live in the QA scratchpad, not the +repo; two were dropped into the tree temporarily to run under `cargo test` +and removed immediately after (`git status --porcelain` confirmed clean each +time before moving on). + +**Tools — exact results.** +- `cargo test --workspace`: **95 passed, 0 failed**, 0 ignored, across + vfmt (18 unit + 13 cli), vlog_formatter (3 unit + 1 cases + 4 deep_nesting + + 2 fixtures + 22 verification), vlog_parser (32 unit). Matches the claimed + 86→95 (+4 lexer, +3 parser, +2 verification). +- `cargo clippy --all-targets`: silent, 0 warnings (`grep -c warning:` → 0). +- `cargo fmt --check`: clean, exit 0. + +**Claim 1 (AST leaf, verbatim, semicolon fidelity, item/stmt coverage) — +PASS.** Confirmed `ItemKind::MacroItem`/`StmtKind::MacroStmt` wrap +`MacroCall { raw: RawText, semi: bool }` (`crates/vlog_parser/src/ast.rs`), +formatted via `Fmt::macro_call` → `raw_text` → `raw_lines` +(`crates/vlog_formatter/src/format.rs:113-128`), which is the same +`RawText.col`-dedent path `Directive`/`Meta::attrs` already use. Exercised +macro items/statements in every position the design table names — module +body, package body, generate region, generate `if`/`for`/`case`, `begin`/ +`end`, `fork`/`join`, function/task bodies, `if`-without-`begin`, `while`- +without-`begin`, `for`-without-`begin`, `foreach`-without-`begin`, +case-item body, `else` branch, sole content of a generate `if`/`else` block +— all parse, format, and round-trip idempotent (formatted, then `--check`d +the result → exit 0) via `target/debug/vfmt -`. Did **not** find a statement +position where a macro fails to parse; this claim holds without +qualification for everywhere tested. + +**Claim 2 (disambiguation) — PASS, with one documented edge case.** +Adversarial cases through `target/release/vfmt -` (or debug, same logic): + +| input | result | +|---|---| +| `` `M[3:0] x; `` | declaration, type=`` `M ``, packed dim `[3:0]` — parses, formats to `` `M [3:0] x; ``, idempotent | +| `` `M `N; `` | two adjacent macro items, `` `M `` bare then `` `N; `` — idempotent | +| `` `M(a)(b); `` | **clean parse error** (2:1 "expected declaration or instantiation") — not corrupted, just refused | +| `` `M `` immediately before `endmodule` | parses as a bare macro item | +| `` `M `` immediately before a directive (`` `ifdef ``) | parses as a bare macro item | +| `` `M(a) `` as sole content of a `case` item, an `else` branch, a generate block | all parse and round-trip | +| `` `uvm_info("a )( b", "msg", UVM_LOW); `` (unbalanced paren inside string) | parses correctly, string content untouched | +| `` `OUTER(`INNER(a, b), c) `` (nested macro in args) | parses as one opaque token, untouched | +| `` `M() `` (empty args) | parses, round-trips | +| **`` `M (a, b); `` — space before the paren** | the lexer does *not* attach a space-separated `(...)` to the macro token (`lexer.rs:186`, `self.peek() == b'('` has no whitespace skip), so the token is bare `` `M `` and the next real token is the symbol `` ( ``. `at_macro_item` reads `next.kind == Symbol` → **not** a macro item, so it falls into ordinary item parsing and hits a clean parse error ("expected declaration or instantiation, found `` `M ``"). This is not corruption (nothing is emitted) and is consistent with the "wrong guesses cannot corrupt" assumption, but it is a real usability gap worth a one-line mention in Assumptions: a macro invocation with space before `(` is rejected outright rather than treated as an invocation. Not blocking — no corpus file does this (macro-call sites are always written tight) — but worth a note since it's easy to hit by hand. | + +**Claim 3 (lexer hardening, nesting cap, no budget charge) — PASS.** +- Nesting cap verified at the exact boundary: `` `M( `` counts as the first + open, so **256 total nested opens parses cleanly**, **257 is a clean lex + error** ("macro argument nesting too deep (limit 256)") — no off-by-one. +- Confirmed the scan is genuinely iterative and unrelated to the *parser's* + recursion budgets: a macro argument containing a 1000-term `a + a + ... ` + chain (`` `ASSERT_INIT(Big_A, a + a + ... `` × 1000) parses fine — it is + never handed to the expression grammar, so `MAX_CHAIN_LENGTH` (256) does + not apply, confirming it truly costs nothing. +- Confirmed the converse: a macro used in **expression** position still + charges the ordinary paren-nesting budget normally. `wire w = + ((((...`M(x)...))));` with 300 real parens around the macro hits + `nesting too deep (limit 64)` exactly like any other 300-deep expression + — the macro leaf itself doesn't bypass budgets it isn't inside of. +- String/comment skipping inside macro args re-verified with the unbalanced- + paren-in-string and nested-bracket-and-comment cases above. + +**Claim 4 (verify.rs normalization) — BLOCKING FINDING.** This is the one +the task flagged as highest-risk, and attacking it directly found a real +masked-corruption hole. + +`normalize()` (`crates/vlog_formatter/src/verify.rs:230-236`) routes any +multi-line backtick-`Ident` token through `trim_lines`, which does +`text.lines().map(str::trim).collect().join("\n")` — it trims every +physical line of the token's text unconditionally, with **no awareness of +whether that line is inside a string literal**. But the *lexer's* +`skip_string` (used both for ordinary strings and inside +`scan_macro_args`) does not reject a literal newline inside a string +either — it only breaks out on an unescaped `"`. So a macro argument can +legally contain a string literal that itself spans physical lines, and the +formatter's `raw_lines` (`format.rs:139-155`) — which dedents/reindents +*every* continuation line of the macro token by column, again with no +string-boundary awareness — will rewrite the leading whitespace inside that +string when the surrounding indent level changes. That is a genuine change +to the string's *value*, not layout. `normalize()`'s blind per-line trim +then treats the before/after difference as "just reindentation" and the +equivalence check passes. + +Reproduced two ways: + +1. **End-to-end through the real binary** (`target/debug/vfmt -`), no + handcrafted internals: + ``` + module m; + if (X) begin : g + `uvm_info("id", "line one + line two with leading spaces", UVM_LOW); + end + endmodule + ``` + formats (exit 0, no error) to: + ``` + module m; + if (X) begin : g + `uvm_info("id", "line one + line two with leading spaces", UVM_LOW); + end + endmodule + ``` + The string's second line had **3** leading spaces in the input and + **7** in the output — the string literal's value changed. This is + stable/idempotent (formatting the corrupted output again reproduces it + exactly), so it isn't caught by convergence either — convergence only + checks the formatter reaches a fixed point, not that the fixed point is + correct. +2. **Isolated unit test against `verify_equivalence` directly**, proving + it's specifically the safety net that's blind here (not some other + stage): + ```rust + let input = "module m;\nif (X) begin : g\n`uvm_info(\"id\", \"line one\n line two\", UVM_LOW);\nend\nendmodule\n"; + let output = "module m;\n if (X) begin : g\n `uvm_info(\"id\", \"line one\n line two\", UVM_LOW);\n end\nendmodule\n"; + assert!(verify_equivalence(input, output).is_err()); // FAILS: returns Ok(()) + ``` + `verify_equivalence(input, output)` returns `Ok(())`. Full repro saved at + `qa_masked_corruption_repro.rs` in the QA scratchpad (not committed to + the repo) — drop it into `crates/vlog_formatter/tests/` and + `cargo test -p vlog_formatter` to reproduce. + +This violates CLAUDE.md invariant #1 ("never corrupt code") for input the +lexer already accepts without error. It is **not** hypothetical or +contrived past the point of realism: nothing about a macro argument +containing a multi-line string is unusual for `` `uvm_info``/`` `uvm_error``- +style macros, whose whole purpose is carrying free-text messages. I did not +attempt a fix — this is a safety-net design question (the options are +non-trivial: track string/comment spans while trimming, forbid raw +newlines inside strings at the lexer level and require `\`-continuation +instead, or stop trimming and require the *formatter* to prove it only +touched whitespace by some other means) and is squarely a dev-agent +decision, not a QA one-liner. + +I also attacked the narrower reindent-forgiveness logic itself and found no +other hole — these are all correctly **rejected** (not masked), verified +against `verify_equivalence` directly: +- an argument's entire line deleted (line count changes); +- two argument lines merged onto one (line count changes); +- internal spacing changed *inside* one line of a multi-line argument + (`str::trim` only strips line edges, never interior whitespace — a + single-line token doesn't even reach `trim_lines`, since it early-returns + on "no `\n`", so single-line internal-spacing changes were already caught + before this feature and remain so); +- an argument line reduced to empty; +- content changes survive under CRLF input (the lexer strips `\r` + entirely before a token's text is ever recorded, so `\r\n` files behave + identically to `\n` files here — not a separate risk). +The structural reason the rest is safe: `trim_lines` joins per-line trimmed +text with `\n`, so two texts can only normalize equal if they have the same +number of lines *and* every line's trimmed core is byte-identical — content +cannot move between lines undetected, only each line's own leading/trailing +whitespace can differ. The string-literal case above is the sole exception +because it breaks the premise that "the trimmed core of a line is the part +that matters" — inside a string, the leading whitespace of a continuation +line **is** the trimmed-away part. + +**Claim 5 (test/lint counts) — PASS.** See Tools above; exact match. + +**Claim 6 (corpus) — PASS, independently re-verified against a real +pre-feature baseline, not just re-run.** The repo has no committed baseline +TSV (`corpus-check-results.tsv` is gitignored and only the post-feature copy +was on disk), so per the task instructions I rebuilt one: `git worktree add` +a detached checkout at `HEAD` (no stash, no modification to the working +tree — verified `git status --porcelain` identical before/after), built +`target/release/vfmt` there, and ran `tools/corpus_check.sh` against the +*same* corpus with `-b` pointed at that baseline binary vs. the feature +binary. Worktree removed after. + +| metric | baseline (rebuilt from HEAD) | feature (working tree) | claimed | +|---|---|---|---| +| parse-error | 531 | 352 | 531 → 352 ✓ | +| verification-error | 24 | 46 | 24 → 46 ✓ | +| would-reformat | 264 | 420 | — | +| ok-unchanged | 1 | 2 | — | +| parsed (820 − parse-error) | 289 (35.2%) | 468 (57.1%) | 289 → 468, 35.2% → 57.1% ✓ | + +Diffed the two 820-row TSVs by file path (not just by count): **179 files +moved parse-error → parsed, 0 files moved the other way, 0 files changed +status among files that were already parsing before** (i.e. no +would-reformat file silently became verification-error, etc.) — the +22 +verification-errors are entirely accounted for by files that were +parse-error at baseline and land in verification-error now, matching the +dev's claim precisely. All four corpus repos confirmed `git status +--porcelain` clean except the untracked `.vfmt-corpus-rev` stamp, both +before and after. Ran the feature corpus check twice — byte-identical TSVs +both times (deterministic). + +Spot-checked all 3 named acceptance files +(`prim_arbiter_fixed.sv`, `credit_counter.sv`, `lfsr_8bit.sv`): each +formats without error, the macro lines are byte-identical to source, and +`--check` on the formatted output exits 0 (fixed point) — confirmed +directly, not just by exit code, by grepping the `` `ASSERT``/`` `FFARNC`` +lines before and after. + +Sampled 3 of the 22 new verification-error files and confirmed the +diagnostic matches a pre-existing, non-macro root cause from +`docs/features/corpus-check/README.md`: +- `common_cells/src/cdc_fifo_2phase.sv` — comma→`or` in an `always_ff` + event list (root cause A); the flagged lines (88/91) are a sensitivity + list, no macro nearby. +- `common_cells/src/rr_arb_tree.sv` — `/* verilator split_var */` trailing + comment on a packed declaration (root cause B); no macro nearby. +- `ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_sha2.sv` — `// latch in + configured mode` trailing comment on a ternary-assignment line (root + cause B); no macro nearby. + +**CLAUDE.md compliance — PASS.** Grepped +`lexer.rs`/`parser.rs`/`ast.rs`/`token.rs`/`format.rs`/`verify.rs` for +`.unwrap()`/`.expect(`/`panic!` outside `#[cfg(test)]` modules; the three +hits that exist (`lexer.rs:625`, `format.rs:582,762`) all pre-date this +diff (`git blame` → commits `d3d9786`/`9f1a6cf`, both before this feature's +work), so this feature introduces none. All new public items have doc +comments (`MacroCall` + both fields, `ItemKind::MacroItem`, +`StmtKind::MacroStmt`, `Token::is_macro`, `Token::has_macro_args`). +`docs/features/macro-items/README.md` has all six required sections. Work +log reads as honest (states the 179-vs-≥200 gap plainly, doesn't round the +corpus numbers favorably, documents the one deliberately-unhandled shape). + +**Summary.** + +| claim | verdict | +|---|---| +| 1 — AST leaf / verbatim / semicolon fidelity / coverage | PASS | +| 2 — disambiguation | PASS (one documented non-blocking edge case: space before `(`) | +| 3 — lexer hardening / nesting cap / no budget charge | PASS | +| 4 — verify.rs normalization | **BLOCKING** — masked string-literal corruption, see above | +| 5 — test/lint counts | PASS | +| 6 — corpus results | PASS (independently re-verified against a rebuilt baseline) | + +Recommend **not** shipping this feature as-is until claim 4 is resolved: +the specific failure is narrow (a string literal inside a macro argument +that itself spans physical lines) but it is a real, reproducible violation +of the project's #1 hard invariant, achievable with ordinary +`` `uvm_info``-style macro text, and currently invisible to every check the +formatter runs on itself. + +### 2026-08-19 (re-QA) — QA agent, verifying the fix for the round-1 blocking finding + +**Scope.** Re-read the updated work log (dev's "answering QA round 1" entry) +and diffed `crates/vlog_formatter/src/{verify,format}.rs` and +`tests/verification.rs` line by line before running anything. No permanent +changes made — `git status --porcelain` before and after this pass is +identical to the dev's stated diff (8 modified + 2 untracked); two scratch +test files were dropped into `crates/vlog_formatter/tests/`, run, and +removed, verified clean each time. + +**1. Original repro re-run — FIXED, confirmed both ways.** +- End-to-end through `target/debug/vfmt -` on the exact round-1 input: exit + 0, and the string's second line is now byte-identical between input and + output (`"line one\n line two with leading spaces"` — 3 leading spaces + in, 3 leading spaces out; previously became 7). Idempotent (formatted the + output again, `diff` clean). +- Isolated `verify_equivalence(input, output)` on the round-1 (input, + *corrupted*-output) pair now returns `Err(Divergence { .. })` pointing at + the token whose text differs — the net itself, not just the formatter's + new behavior, rejects the pair. Repro saved to the QA scratchpad as + `qa_round2_repro1.rs` (not committed). + +**2. Attacking `line_starts_inside_string` — no hole found.** Built 10 +targeted (input, output) pairs against `verify_equivalence` directly, +covering every case in the brief, and separately ran the *input* half of +each through the real binary for idempotency: + +| attack | verify_equivalence verdict | real-binary round-trip | +|---|---|---| +| escaped backslash before quote (`` "x\\" ``, string ends, following break is code) | reindent **accepted**; content change after the closing quote still **rejected** | reindented normally, idempotent — confirms the fix does not over-trigger on this shape | +| quote immediately at line start | corruption inside the string **rejected** | verbatim, idempotent | +| string opened line 1, closed line 3 (middle line fully inside) | corruption on the untouched middle line **rejected** | verbatim, idempotent | +| `//` comment with an odd number of quotes, followed by a real multi-line string | corruption of the real string **rejected**; the odd quote in the comment does not desync tracking | verbatim, idempotent | +| `/* ... */` comment spanning lines with quotes inside, followed by a real string | corruption of the real string **rejected**; reindenting *inside* the block comment itself (no real string reachable from it) is still **accepted** | verbatim for the string; comment-only case reindents normally, idempotent | +| a string containing `/*` (must not be read as opening a comment) | corruption inside that string **rejected** | verbatim, idempotent | +| backtick-nested macro, inner string spans a line inside the outer token's raw text (`` `A("x", `B("y\nz")) ``) | corruption inside the inner string **rejected** | verbatim, idempotent | +| CRLF: `\r` immediately before an in-string `\n` | corruption (reindent) of the string **rejected**; the `\r` is not silently trimmed as ordinary whitespace | in practice the lexer strips `\r` from every token before it's ever recorded, so real `vfmt` input never carries `\r` this deep — confirmed by feeding it a raw `\r\n` file end-to-end: output is pure `\n`, idempotent. The `verify_equivalence`-level test still matters because that function accepts raw strings from any caller, not just the file-reading pipeline. | +| CRLF, reindent outside any string | **accepted** | reindented normally, idempotent | + +Repro saved to the QA scratchpad as `qa_round2_state_machine_attack.rs` +(10/10 passed, not committed). No masked-corruption pair survived. + +**3. Directive/Attribute fix — confirmed end-to-end.** Ran the dev's two +named repro shapes through `target/debug/vfmt -`: +- `` `define MSG "line one \ line two" `` inside an indented + block: output's continuation line is byte-identical to input + (` line two"`, 3 leading spaces, untouched) — previously this pre-existing + (not introduced by this feature) defect would have widened it. Idempotent. +- `(* note = "line one line two" *)`: same — continuation line + byte-identical, idempotent. + +Both match the case-table entries the dev added (`macros.cases` grew 18→20 +entries, confirmed by counting `====` separators: 19 separators = 20 +entries). + +**4. Verbatim fallback does not over-trigger — confirmed.** The dev's +`reindenting_outside_a_string_is_still_allowed` test exercises exactly what +it should: a multi-line macro token (`` `A("msg",\n x) ``) whose only +string is entirely on the first line — the line break falls in code, not +in the string, so normal per-line reindenting still applies (verified this +is genuinely exercised, not vacuous, by running it through the real binary: +output is `` `A("msg",\n x) `` with the continuation line's indent +changed from 2 to 4 spaces, not left alone). Also independently confirmed +with the escaped-backslash-string case above (case 1 in the table): a +string that *looks* risky (contains a backslash right before what could be +misread as an unescaped quote) but actually closes correctly still gets +ordinary reindenting, not the verbatim fallback. Comments were separately +confirmed to still use the string-unaware `trim_lines` (a block comment +containing a bare `"` still reindents normally end-to-end). + +**5. Tools and corpus — exact numbers.** +- `cargo test --workspace`: **98 passed, 0 failed** (18+13+3+1+4+2+25+32 — + verification.rs grew 22→25, exactly the claimed +3). Matches claim. +- `cargo clippy --all-targets`: silent, 0 warnings. +- `cargo fmt --check`: clean, exit 0. +- Corpus: fresh `cargo build --release` (touched `lexer.rs` first to force a + real rebuild, confirmed by compile output), then + `tools/corpus_check.sh corpus`: **468/820 parsed (57.1%)**, 352 + parse-error, 46 verification-error, 420 would-reformat, 2 ok-unchanged — + **byte-identical** to my round-1 post-macro-items TSV (`diff` clean). Since + round 1 already diffed that TSV against a rebuilt true pre-feature baseline + (179 gained, 0 lost, 0 status changes among already-parsing files), that + regression analysis carries over unchanged: this fix touched 0 corpus + files, exactly as the dev predicted (no corpus file carries a string + across a line break inside a macro/directive/attribute). All four corpus + repos confirmed `git status --porcelain` clean (only the untracked + `.vfmt-corpus-rev` stamp) before and after. +- `git status --porcelain`: identical to the dev's stated diff throughout — + no stray files left behind. + +**Verdict.** The round-1 blocking finding is **resolved**. No new hole +found despite a targeted, adversarial pass at the exact mechanism +(`line_starts_inside_string`) the lead asked to be attacked hardest — its +lexer-mirroring state machine (backslash escapes, `//`/`/* */` comment +skipping, one-state-at-a-time so a quote inside a comment can't open a +string and vice versa) held up against every shape tried, including the +one that most resembles a classic off-by-one trap (a string that closes on +the same line it looked risky on) and the one most likely to have been +missed (a nested macro's string spanning a line *inside* the outer token). +The all-or-nothing verbatim choice in `format.rs` (rather than a partial +per-line reindent) is why the two sides can't drift apart: for any token +where this matters, the formatter now provably changes nothing, so the +comparison is moot rather than merely correct. Recommend this feature is +clear to ship on the strength of this fix; I found nothing else blocking +across either QA pass. + +## Review + +**2026-08-19 — lead. Verdict: accepted and committed after one rejection +and a verified rework. Largest single improvement in the project so far +(corpus parse rate 35.2% → 57.1%), and the most important lesson.** + +The feature work itself was excellent from round 1: riding the existing +lexer representation instead of inventing one, the `at_macro_item` +disambiguation being safe-by-construction (both readings emit identical +tokens), semicolon fidelity, the iterative arg scanner with its own +capped counter, and honest corpus reporting that didn't let the headline +number hide the 179-vs-200 gap or the expected rise in verification +errors. + +The rejection was for the one thing that matters more than any feature: +the verify.rs normalization added for multi-line macro tokens could mask +real corruption — a string literal spanning lines inside a macro arg had +its bytes changed by re-indent, and vfmt exited 0. First genuine +invariant-#1 violation in the project. Credit where due on the rework: + +1. **The dev widened the finding before fixing it** — the same defect + pre-existed in `` `define`` bodies and attributes via the shared + `raw_lines`/`trim_lines` path, live since the RawText round and + masked by the same trim. I ruled the pre-existing halves ride along + in this commit: same three lines of shared root cause; splitting + would leave known corruption in the tree during the gap. +2. **One scanner, two consumers**: `line_starts_inside_string` is the + single definition of "which line breaks are data", shared by the + formatter (verbatim fallback — idempotent by construction) and the + verifier (string-aware trim). Two definitions drifting apart is how + this bug happened; one definition is how it stays fixed. +3. **Comments deliberately keep plain trimming** — a lone quote in a + block comment must not freeze re-indentation. Correctly reasoned, + correctly bounded. +4. Re-QA attacked the scanner on ten edge shapes (escapes, quotes in + comments, comment-openers in strings, nested macros, CRLF) and found + no hole; the over-trigger check confirmed the verbatim fallback fires + only when a break truly lands inside a string. + +Process consequence, now codified as CLAUDE.md hard-invariant #4: any +widening of the safety net's forgiveness ships with masked-corruption +attack tests, dev-written and QA-re-attacked. The net exists to catch +the formatter; nothing gets to quietly widen what the net forgives. + +Also accepted: the `` `M (a, b); `` space-before-paren gap stays a +documented Assumption (the expression-position ambiguity the dev +identified is real; it needs its own round if it ever matters — no +corpus call site writes it spaced).