Files
lucisv/docs/features/macro-items

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. (2026-08-19: assessed by lexer-cleanup and parked — the expression-position risk is real and the glue cannot be proven meaning-preserving; full analysis in docs/features/lexer-cleanup/README.md.) (2026-08-20: closed by item-misc, in the parser rather than the lexer. Parser::at_spaced_macro_call offers the invocation reading only where an item or a statement belongs — the position where neither reading is a legal parse, so the ambiguity the lexer park is about does not arise. Expression position is unchanged and still parses `A (b) as a call. The space is reproduced as written, not tightened. See docs/features/item-misc/README.md.)
  • 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<Expr> — 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:

`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 lucisv 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

  • Lexer: balanced argument scan skips strings and comments; nesting cap with a clean lex error; string/block-comment skips deduplicated.
  • Token::is_macro() / Token::has_macro_args().
  • AST: MacroCall, ItemKind::MacroItem, StmtKind::MacroStmt.
  • Parser: at_macro_item lookahead + parse_macro_call, wired into parse_item_kind and parse_stmt_kind.
  • Formatter: Fmt::macro_call, verbatim via the RawText.col path.
  • verify.rs: normalize trims lines of backtick identifiers; reasoning recorded under Handshakes.
  • 20 cases in crates/vlog_formatter/tests/cases/macros.cases.
  • 3 parser unit tests + 4 lexer unit tests + 5 verification tests.

From QA round 1 (2026-08-19):

  • 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.
  • 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.
  • 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.
  • Corpus acceptance: 3 named files, before/after recorded below.
  • Full corpus re-run; new parse rate recorded below.
  • README.md supported-syntax updated, roadmap item 1 struck.
  • 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 .lucisv-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 imports 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/lucisv/ 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, lucisv 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 lucisv 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 lucisv (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 --checkd the result → exit 0) via target/debug/lucisv -. 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/lucisv - (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 hitsnesting 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/lucisv -), 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):
    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/lucisv 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 .lucisv-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/lucisv - 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 lucisv 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/lucisv -:

  • `define MSG "line one \<newline> 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<newline> 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 .lucisv-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 lucisv 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).