Files
lucisv/docs/features/comments-round-2

comments-round-2

Goal

Close the last two comment-attachment gaps that ordinary RTL still trips over. comments-round fixed comments inside lists and parked "a comment before a construct's opening bracket" as a shape nobody writes; the corpus disagreed. A sweep that inserts one // marker line at lines len/3 and len/2 of every formattable corpus file refused 14 files, in exactly two shapes: a comment between a module/instantiation head and the #( or ( that follows it (10 files), and a comment written next to an (* attribute *), which came out on the wrong side of it (4 files). Both are refusals, not corruption — the safety net was right both times — but a file lucisv cannot format is a file lucisv cannot format. Measuring the fix turned up a third, quieter bug in the same family: instantiation's single-instance branch never read the instance's Meta, so a comment before a lone instance's name was parsed and then dropped (hard invariant #3, visible only because the net refused the file). Result: 14 refusals → 0 on the acceptance sweep, 335 → 240 on an exhaustive one with 0 new refusals, verify.rs byte-identical to HEAD and the corpus TSV md5 unchanged.

Assumptions

  • A comment stays lexically between the two tokens it was written between. That is the whole spec, and it is what verify_equivalence checks. Every fix here gives the comment a place to live in the AST at the position the source put it; not one of them relaxes a check.
  • An opening bracket is a token like any other. module m ⏎ // why ⏎ #(...) and module m #( ⏎ // why ⏎ ...) are different streams. The first is what prim_mubi*_dec.sv writes once a marker lands there, and the parser now records which one it saw instead of letting the comment fall through to the first element of the list.
  • Attributes and leading comments interleave, so their relative order is data, not a formatting choice. Meta keeps them in two lists (attrs and leading) because they are different kinds of thing, but both carry byte spans, and the source order is recoverable from those spans. Printing all comments and then all attributes silently reorders a (* DONT_TOUCH *) against the comment explaining it.
  • "Harvest only when the bracket is actually there." take_before_open is a no-op unless the cursor is on the bracket named, exactly as take_before_sep is a no-op unless the cursor is on the separator. A module that writes no #( must leave the comment for whoever comes next — which is why the whole 512-test suite stayed byte-for-byte green.
  • A line comment runs to end of line, so the bracket that follows one goes on the next line. sub u // why ⏎ (.a(b)); is ugly and faithful; sub u // why (.a(b)); would delete the connection list into the comment.
  • A header that has broken to column 0 keeps the bracket at column 0. The module printer already does this after an import block ("the usual single space before #(/( is dropped"); a line comment in the same position takes the same path, so module m // why ⏎ #(...) is the existing spelling, not a new one.

Handshakes

Changed in vlog_parser::ast (consumed by vlog_formatter::format):

item before after
Module — new param_comments: Vec<Comment> — comments between the header's name (or its last import) and the # of the parameter port list. Empty when the header wrote no #(.
Module — new port_comments: Vec<Comment> — comments between whatever precedes the port list and its (. Empty when the header wrote no parenthesized port list.
Instantiation — new param_comments: Vec<Comment> — comments between the module name and the # of the override list.
Instance — new conn_comments: Vec<Comment> — comments between the instance name (or its dimensions) and the ( of its connection list.

All four are plain Vec<Comment> beside existing Vecs; no variant grew, so clippy::large_enum_variant stayed silent.

New parser helper: Parser::take_before_open(open) -> Vec<Comment> — the opening-bracket twin of take_before_sep, a no-op unless the cursor is on that bracket.

New formatter helpers: Fmt::bracket_comments (prints one of the four buckets — or a lone instance's leading comments, which sit in the same head position — and reports whether the caller must start the next token on a fresh line), Fmt::push_leading (one leading entry plus the break before it) and Fmt::push_comment (the fence-aware half of the old leading_comments loop). Fmt::leading now merges meta.leading and meta.attrs by span instead of concatenating them.

Fmt::instantiation's single-instance branch now reads Instance.meta. It printed self.instance(only) bare, so the instance's leading comments were parsed and never emitted; the multi-instance branch beside it has always called self.leading. Only the leading comments are printed here — before_sep and trailing stay empty for a lone instance, since nothing separates it — so the two branches cannot double-print.

Fmt::item_docs restructured, not re-specified. It used to emit leading comments, check the fence, then emit attributes; it now checks the fence first and takes the merged leading() on the normal path. The fenced path is unchanged (an item's attributes are inside its span, so a fence emits them as source bytes and the formatter must not print them again).

Consumed from verify.rs: nothing new. No normalization was added, broadened or weakened — git diff --quiet -- crates/vlog_formatter/src/verify.rs exits 0, so CLAUDE.md hard invariant #4 does not bind this round. Seven new rejection tests were added to tests/verification.rs anyway, one per shape fixed, each asserting that the "corrupted" output a widened normalization would have forgiven is still refused. The attribute swap asserts both directions, and one test pins the dropped-comment failure mode the four new Vec<Comment> fields could regress into (hard invariant #3).

Format fences (docs/features/format-fences/README.md): unchanged, and verified so. fence::scan_scope walks item-level leading comments only, so a // lucisv: off written in one of the four new bracket positions opens no region — exactly as it opened none when the same comment used to land in the first parameter port's meta.leading. The difference is that such a file is now formatted (fence inert, output verified) instead of refused. fence.rs, tests/fences.rs and fences.cases are untouched and green.

Recursion/chain budgets (docs/features/recursion-limit/README.md): unaffected. Four Vec<Comment> fields on existing nodes; nothing recurses, nothing nests, root-to-leaf depth is unchanged.

line_starts_inside_string is still the one in-string-break definition — untouched; nothing here parses comment or string text.

Not touched, by scope: crates/lucisv, crates/lucisv_core, crates/lucisv_server, crates/vlog_linter, crates/vlog_semantic, editors/, tools/, corpus/, verify.rs. lucisv_server's tests consume format_source and stayed green. cargo fmt --all rewrote exactly one file, this round's own tests/verification.rs (confirmed against cargo fmt --all --check beforehand, which listed only that file).

Status / TODO

  • Bucket 1 — comment before an opening bracket. Four positions, four fields: a module header's #( and its port-list (, an instantiation's #( and an instance's connection (. 10 of the 14 corpus refusals.
  • Bucket 2 — comment adjacent to an (* attribute *). Fmt::leading merges comments and attributes by span. Covers items and statements (both go through Meta.attrs), so the generate-block and procedural-block twins came free. 4 of the 14.
  • Found while measuring — a comment before a lone instance's name was parsed and never printed. instantiation's single-instance branch called self.instance(only) without ever reading only.meta; the multi-instance branch beside it does. sub #(.W(1)) ⏎ // the instance ⏎ u (...) therefore lost the comment — hard invariant #3, refused by the net every time, and 6 more corpus positions. Fixed by routing that Meta's leading comments through the same bracket_comments helper.
  • 16 new .cases entries in comments.cases (77 → 93; 299 → 315 overall).
  • 8 new rejection tests in tests/verification.rs (39 → 47).
  • 4 new parser unit tests, including the "no bracket, no harvest" one that pins why the existing suite did not churn.
  • Sweep acceptance: 14 → 0 on the lead's protocol, reproduced against a HEAD worktree binary first.
  • cargo test --workspace 524 passed (512 baseline + 12), clippy silent, fmt clean, verify.rs byte-identical to HEAD.
  • Corpus TSV md5 unchanged: aa982463f68c1a3568c02a0fc5e0c455, 0 verification errors, 0 crashes, script exit 0.
  • TODO.md §2: the comment item's note updated with what this round closed and what is still parked.
  • Still parked, inherited from comments-round — bracket interiors (x[a /* c */ : b], logic [7 /* c */ : 0]), a comment before a procedural statement's ;, a comment before else, and the bare name lists (genvar i /* c */, j;). All refusals, never corruption. The exhaustive sweep shows the else one is by far the biggest of them.
  • Not done — the remaining head positions, the rest of bucket 1's family: a comment before an opening { / '{ (a concatenation, an assignment pattern, a struct body), before an if's (, and between a function's return type and its name. Same shape as bucket 1 and each is its own slot, but none is reachable by the lead's sweep and the exhaustive one says they are rare; this round stopped at the positions the corpus actually refuses on. Counts in Measurements.

Measurements

The lead's sweep, reproduced and re-run. One // marker line inserted so that it becomes line len/3 (and, separately, line len/2) of every corpus file that formats cleanly unmodified; formatted through lucisv --stdin-filename <path> -. A trial is discarded when the insertion breaks the parse — a comment dropped into a backslash-continued macro body genuinely changes what the file says, and that is the harness's doing, not the formatter's. Script in the session scratchpad (sweep.py); not checked in, as none of the earlier rounds' harnesses were.

before (HEAD worktree, c8b936a) after
formattable files 501 501
usable trials 989 989
discarded (insertion broke the parse) 11 11
verification refusals 14 0

The 14 are the lead's 14, file for file and line for line — 10 prim_*_dec.sv / prim_lc_dec.sv (bucket 1) and 4 prim_xilinx / read.sv (bucket 2). The trial count differs from the brief's 934 because the file set and the parse-error accounting are this harness's own; the failure list is identical, which is the part that matters.

Exhaustive line sweep. The same insertion before every line of every formattable corpus file, run on both binaries — because "0 refusals at two sample points per file" is a weaker claim than it sounds, and because it is the only way to say honestly whether anything got worse. Script dense.py, same scratchpad.

before (HEAD) after
usable trials 62 407 62 407
discarded (insertion broke the parse) 967 967
verification refusals 335 (0.54%) 240 (0.38%)

Diffed by file:line, not by count: 95 positions fixed, 0 positions newly refusing. The 95 are exactly the three shapes this round names — 46 before a #(, 22 an attribute/comment swap, 21 before an instantiation's or header's (, 6 before a lone instance's name.

The 240 survivors, bucketed by the token the output has where the input has the comment. None is a new bucket; every one is a head or interior position of the already-parked families:

survivors shape disposition
89 before an else keyword parked by comments-round: the else-branch Meta is read as _meta and never printed. A layout decision, not plumbing.
74 before an opening { (58) or '{ (16) bucket 1's family, other members: a concatenation, an assignment pattern, a struct body.
49 before an identifier 36 of them one generated package (prim_secded_pkg.sv) splitting a function's return type from its name; the rest are expression positions.
20 before a ) (13) or a ( (7) remaining head positions (if (, a call's () and list-closing brackets in expressions.
8 before =, begin, a number, $signed, ! expression and statement interiors — the comments-round parked list.

Every survivor refuses on HEAD too, at the same position. Refusals, never corruption: the net caught all 240.

Corpus results

./tools/corpus_check.sh corpus, release build:

ok-unchanged             8    1.0%      (unchanged)
would-reformat         460   56.1%      (unchanged)
parse-error            352   42.9%      (unchanged)
verification-error       0    0.0%
other-error              0    0.0%
crash                    0    0.0%
total                  820  100.0%

Script exit status 0. TSV md5 aa982463f68c1a3568c02a0fc5e0c455 — byte-identical to the comments-round baseline, so no corpus file moved category and no by-path delta exists to report. That is the expected result and it was checked, not assumed: no corpus file writes any of these three shapes uninserted, which is exactly why they needed an insertion sweep to find at all.

Work log

2026-08-19 — dev agent

  • Read CLAUDE.md, the comments-round and corpus-bugs READMEs, and TODO.md §2 before touching code. Baseline: cargo test --workspace 512 passed, clippy silent, fmt clean, corpus TSV md5 aa982463f68c1a3568c02a0fc5e0c455.
  • Reproduced the harness before reproducing the bugs. The brief's failure list gave file and line, so the first job was finding the insertion index that reproduces it: inserting so the marker becomes line len/3 (0-based index len/3 − 1), not at index len/3. With that, a HEAD worktree binary reproduces all 14 failures exactly. Every later number has a real control.
  • Reduced both buckets to five-line cases before writing any code, and found in the process that the brief's bucket 1 is only half about instantiations: 10 of the 10 corpus files are module headers (module prim_mubi4_dec ⏎ import prim_mubi_pkg::*; ⏎ // marker ⏎ #(), not instantiations. The instantiation twin exists and refuses identically, so both are fixed; the module header is the one the corpus actually writes.
  • Root cause, bucket 1. bump() moves a consumed token's leading comments into pending_leading, so nothing is dropped — the comment simply reappears at the next take_meta, which is the first element of the list. The comment therefore printed inside the #(...) the author wrote it before. The information was in the token stream and nowhere in the AST, the same diagnosis the previous two rounds reached for separators.
  • Chose four narrow fields over one general one. A single Meta::before_open beside before_sep was tempting, but the four positions belong to three different nodes (Module, Instantiation, Instance) and two of them are not Meta-carrying at all. Four Vec<Comment> fields with four one-line doc comments read better than one field whose doc has to explain four meanings.
  • take_before_open is a no-op unless the bracket is there, copied deliberately from take_before_sep. That single decision is why a change reaching four parse sites left all 299 pre-existing .cases, all snapshots and all 512 tests byte-for-byte green: a module with no #( never enters the new path. Pinned by a_header_without_brackets_keeps_its_comment_for_the_next_construct.
  • Root cause, bucket 2, was a printing bug, not a parsing one. The parser already stores attributes and the comments after them in source order within each list; Fmt::leading just concatenated the two lists. Merging by span.start is a five-line change, and it happens to be a no-op for the common // comment ⏎ (* attr *) spelling, which is why only four corpus files ever hit it.
  • Restructuring item_docs was the risky half of bucket 2. It emitted leading comments, then checked the fence, then emitted attributes — so the merged leading() could not simply be dropped in without emitting a fenced item's attributes twice. Hoisted the fence check to the top and left the fenced path on the comments-only helper. Probed it four ways (fence covering an attributed item, fence opening between an attribute and its comment, a comment before the fence, a region spanning several items): every fenced region still byte-exact, tests/fences.rs 6/6, fences.cases untouched.
  • Checked the fence question the new bucket-1 fields raise, since they hold comments the fence scanner never sees. It never saw them before either — scan_scope walks item-level meta.leading only, and the comment used to live in a parameter port's meta. So a // lucisv: off in bracket position is inert now and was inert before; the change is that the file formats instead of refusing. Written up in Handshakes rather than left as a surprise.
  • Every fixed shape is 3-pass stable, checked outside cargo test on all 23 reduced cases plus the four fence probes: format(format(x)) == format(x) with no refusals.
  • Ran the exhaustive line sweep as well as the lead's two sample points, on both binaries, because "0 at two positions per file" is a weaker claim than it sounds and because only a full run can say whether something got worse. 62 407 trials each: 335 → 240, 95 positions fixed, 0 newly refusing.
  • The exhaustive sweep is what found the third bug. Reading its survivors rather than counting them turned up rrarbiter.sv and friends refusing at a comment between an instantiation's #(...) and its instance name — and the cause was that instantiation's single-instance branch never reads only.meta at all, while the multi-instance branch three lines below it does. A comment parsed and never printed is hard invariant #3; it only ever showed up as a refusal. Fixed through the same bracket_comments helper, and pinned by its own rejection test. Six more corpus positions, zero test churn.
  • Did not touch verify.rs (git diff --quiet exits 0), crates/lucisv*, crates/vlog_linter, crates/vlog_semantic, editors/, tools/ or corpus/. Did not run git commit/git push.

Results: cargo test --workspace 524 passed, 0 failed (512 baseline + 8 rejection tests + 4 parser unit tests; the 16 new .cases entries run inside the existing case_tables test, which now covers 315 cases). cargo clippy --workspace --all-targets silent. cargo fmt --all --check clean. Corpus TSV md5 unchanged, tools/corpus_check.sh exit 0.

Files touched: crates/vlog_parser/src/{ast,parser}.rs, crates/vlog_formatter/src/format.rs, crates/vlog_formatter/tests/cases/comments.cases, crates/vlog_formatter/tests/verification.rs, TODO.md (§2, one note), this README.

QA log

2026-08-19 — QA agent

Verdict: pass on all five claims. No blocking findings.

Gates. cargo fmt --all -- --check clean. cargo clippy --workspace --all-targets silent. cargo test --workspace: 524 passed, 0 failed (counted by hand: 27+48+31+82+3+8+1+4+6+2+47+71+30+57+24+19+17+6+1+19+20+1 doc-test = 524). git diff --quiet -- crates/vlog_formatter/src/verify.rs exits 0; same for fence.rs/tests/fences.rs/fences.cases; fences.rs 6/6. comments.cases 77 → 93 (grep -c '^# '), workspace .cases total 315. Corpus: ./tools/corpus_check.sh corpus release build, exit 0, TSV md5 aa982463f68c1a3568c02a0fc5e0c455 — byte-identical to the claimed baseline.

Claim 1 (bucket 1 / take_before_open). Read parser.rs: take_before_open is exactly if !self.cur().is_sym(open) { return Vec::new(); } self.take_dangling() — a true no-op unless the cursor sits on the named bracket, the same shape as take_before_sep. Confirmed by the untouched pre-existing suite staying green (524 total, no regressions) and by the new parser unit test a_header_without_brackets_keeps_its_comment_for_the_next_construct. Pass.

Claim 2 (bucket 2 / span-merge, fence hoist). Read format.rs::leading: merges meta.leading and meta.attrs with a peekable iterator comparing span.start, in source order. item_docs checks self.is_fenced(item.span) first and only then branches to leading_comments (comments only, fenced path) vs leading (merged, normal path) — matches the claim exactly. Probed directly (attack_g_fence_attrs.sv, attack_e_attr_comment_interleave.sv below): fenced region byte-exact, no double emission; 4-way comment/attribute interleave preserved in source order. Pass.

Claim 3 (single-instance Instance.meta). Read the diff: the single-instance branch now calls self.bracket_comments(&only.meta.leading, ...) before self.instance(only); the multi-instance branch calls the full self.leading(&instance.meta). Checked whether this asymmetry (leading only, not attrs) could drop an attribute on a lone instance: Instance.meta is built by plain take_meta(), which never populates .attrs (only parse_item_inner/parse_stmt_inner run the attribute-harvest loop) — so Instance.meta.attrs is structurally always empty, confirmed by trying to write one ((* keep_hierarchy *) before an instance name is a parse error, pre-existing, not a regression). The asymmetry is therefore not a gap. Pass.

Claim 4 (sweep numbers). Reproduced independently, not just re-read.

  • Lead's 14-item list: reconstructed each file:line insertion from comment_fails.txt, ran on the current release binary — 14/14 format cleanly, are 3-pass idempotent (checked pass1==pass2==pass3 by re-feeding output), and keep // marker at a sane position (eyeballed prim_mubi4_dec.sv and prim_and2.sv: marker lands between the import and #(, and between the attribute and module, exactly source order).
  • Exhaustive spot-check: built a HEAD (832bf4a) worktree binary, picked 30 corpus files (8 import-header family, 6 prim_xilinx attribute family, 16 random 20–200-line would-reformat files), inserted // marker before every line of every file on both binaries (7273 usable trials, 2 discarded for breaking parse). Result: HEAD refusals 19, current refusals 9, 10 fixed, 0 newly refusing. Spot-checked 3 of the still-parked survivors: ibex_alu.sv:655 etc. are '{...} assignment-pattern lines and ibex_controller.sv/pulp_sync.sv are else/= lines — exactly the parked families the README names, refusing on both binaries. Pass (numbers are of a different sample than the lead's full run, as instructed, but the direction and zero-regression property both hold).

Claim 5 (verify.rs / corpus untouched). Covered under Gates above; also re-verified after both sabotage rounds (see below) that verify.rs returned byte-identical (md5 of the file matched pre-sabotage) and the full verification suite went back to 47/47.

Attack pass on the new comment slots (8 probe files, crates/.../attack_ {a..h}_*.sv pattern, saved in scratch; each run 3 passes through the current binary): comment before both #( and ( in one header; three stacked comments in one bracket position; comment before #( on an instantiation (not just a header); comment between #(...) and an instance name for a single instance, an array instance [3:0], and a multi-instance list; 4-way attribute/comment interleave; attribute+comment on a statement inside always; a fence carrying an oddly-spaced attribute and a comment (verified byte-exact region reproduction, no double emission); comment before #( on an instantiation inside a generate block. All 8 passed: no crashes, all 3-pass stable, every comment landed in the same source order at a sane position, no drops.

Sabotage (hard invariant #4 check). verify.rs carries no new normalization this round, so there's nothing "widened" to attack directly; instead confirmed the 8 new rejection tests have real teeth by weakening the guard itself two different ways, one at a time, each reverted before the next:

  1. Added a normalization sorting adjacent Comment/Attribute runs by text (simulating "attribute/comment order stops mattering"). Result: exactly the two attribute-order tests (a_comment_swapped_with_an_attribute_is_still_rejected, an_attribute_hoisted_past_a_comment_that_preceded_it_is_still_rejected) went red; 45/47 others stayed green — narrowly scoped, as expected.
  2. Commented out the leading/trailing comment-harvest lines in lex_stream (simulating "comments stop being compared at all"). Result: a_dropped_bracket_comment_is_still_rejected and a_dropped_instance_name_comment_is_still_rejected both went red (plus a pre-existing round-1 test, a_dropped_enum_dangling_comment_is_still_ rejected, consistently — not an anomaly). Both times: reverted via git checkout -- crates/vlog_formatter/src/ verify.rs, confirmed git diff --quiet exits 0 and the file's md5 matches the pre-sabotage value, then reran the full verification suite (47/47) and cargo test --workspace (524/524) clean.

Regression breadth. Full .cases + fixtures suite green (in the 524). 10 random previously-passing would-reformat corpus files (fresh random sample, different from the QA's dense-sweep sample), run through --stdin on both the current and HEAD binaries: 0/10 differ — byte-identical output and exit code on every one.

CLAUDE.md compliance. Files touched match the stated scope exactly (git diff --stat: TODO.md, crates/vlog_formatter/src/format.rs, crates/vlog_formatter/tests/cases/comments.cases, crates/vlog_formatter/tests/verification.rs, crates/vlog_parser/src/{ast,parser}.rs, plus this README). crates/ lucisv_server/ and crates/vlog_linter/ show as untracked in git status but predate this feature (present in the session's initial git-status snapshot) — not touched by this diff. README has all seven required sections; Review is empty, left alone. TODO.md §2 note read honest: it states the sweep numbers, names the two shapes closed, and points at this README rather than re-explaining bucket 1's remaining head positions inline — acceptable, since the README itself lists them under "Not done."

No blocking findings. No dropped or reordered comment that verify_equivalence missed, no newly-refusing position, in any of the above. One non-blocking observation for the record, not a defect: the 8 rejection tests in verification.rs call expect_divergence(input, output) directly on hand-written literal pairs — they exercise verify.rs's strictness on these corruption shapes, not the parser.rs/format.rs fix itself (which has no failure path to hit from a test that never runs it). That's consistent with how the pre-existing rejection tests in this file are already written, so it isn't a regression, just worth naming: the fix's own regression coverage lives in the parser unit tests and the .cases entries, not in verification.rs.

Review

2026-08-19 — lead. Verdict: accepted and committed. The owner's comment-drop report is fully resolved: 14/14 reported positions fixed, zero regressions across 62k exhaustive trials, and a third latent invariant-#3 bug found and fixed along the way.

Points reviewed and accepted:

  1. Root-causing bucket 1 to module headers, not instantiations (the brief's guess) is why the fix is right rather than lucky: bump() pushing consumed tokens' leading comments into pending_leading meant the comment teleported into the bracket it preceded. take_before_open as the opening-bracket twin of take_before_sep — no-op unless the cursor is on the bracket — inherits the proven byte-identity argument, and QA read it to confirm the shape.
  2. Bucket 2's span-merge (attrs and comments emitted in source order, not list order) covers items and statements in one change, and the fence-check hoist keeps fenced items emitting attrs only as source bytes — the interaction QA attacked directly.
  3. The third bug — a lone instance's meta parsed and never printed — was found by reading sweep survivors rather than stopping at the brief's two buckets. QA's follow-up (Instance.meta.attrs is structurally always empty, so no attr twin of the bug exists) closes the question properly.
  4. The survivor accounting (240 positions, all in families comments-round already parked, all refusing on HEAD too) keeps the honest ledger: nothing new refuses, and what still refuses is documented, not hidden.

QA's non-blocking note — the rejection tests pin verify.rs strictness on literal pairs rather than exercising the fix path — is accurate and matches the file's pre-existing style; the fix path itself is pinned by the 16 new .cases entries, so the two layers together cover both directions. Worth keeping in mind if verification.rs ever grows a format-then-verify harness.

Comment-insertion refusal history, for the record: ~6% (fences QA, pre-comments-round) → 0.4% (comments-round) → 0 on the acceptance protocol (this round), with survivors only at exhaustive per-line granularity in parked families.