Files

559 lines
33 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# corpus-bugs
## Goal
Fix the four formatter bugs the 820-file corpus check exposed, catalogued as
root causes A–D in `docs/features/corpus-check/README.md` and re-measured at 46
affected files after `macro-items` raised the parse rate to 468/820. Every one
of them made the runtime safety net refuse output (exit 2), so each was a file
`lucisv` could not format at all: an event list's `,` rewritten as `or`, comments
moved out of port/parameter lists and out of expressions, two module-header
`import` statements folded into one, and a hand-written empty `#()` dropped.
Three of the four are token rewrites the net is right to reject; the fourth is
comment motion. None of them is fixed by widening the net — this feature does
not touch `verify.rs`'s normalizations at all. **Result: 46 verification
errors → 0, with the parse rate unchanged at 468/820.**
## Assumptions
- **The safety net is the spec, not the obstacle.** Every fix here makes the
formatter emit what the input actually said; not one relaxes a check.
`verify.rs` is byte-identical to `HEAD` (`git diff --quiet` confirmed); the
only addition is seven new **rejection** tests in `tests/verification.rs`.
- **A separator that is legal in two spellings is not the formatter's to
choose.** `@(a, b)` and `@(a or b)` mean the same thing to a simulator and
different things to a token stream. The same reasoning already governs the
trailing `;` of a macro invocation (`macro-items`): reproduce what was
written.
- **An empty `#()` is meaningful text, not noise.** Verilog allows both
`sub u (...)` and `sub #() u (...)`; the second is what picorv32's testbench
writes, and rewriting it to the first loses two tokens. The formatter neither
adds nor removes one.
- **Comments before a list's closing `)` belong inside the list.** A comment
written on its own line after the last parameter, or a
`/* verilator lint_on */` pragma closing a bracketed region, is about the
list. Letting it fall through to the *next* construct's leading comments
moves it across the `)` in the token stream — which the net rejects, and
rightly, because the pragma would then cover the wrong region. This is the
same rule `take_dangling` already applies before `end`/`endmodule`.
- **A comment between a construct's last token and its `;` belongs before the
`;`.** `logic x /* verilator split_var */;` is a verilator pragma whose
position is load-bearing.
- **Comments inside an expression stay on the side of the operator they were
written on.** `a && // why` and `a // why` + `&& b` are different streams.
The parser therefore records "before the operator" and "after the operator"
separately, and the same for the four gaps inside a `? :`. Guessing a single
side would be a coin flip that the net catches half the time.
- **Two line comments never share a printed line.** `// a // b` re-lexes as one
comment, which is comment loss disguised as comment motion. Every place this
feature prints a run of comments goes through `Fmt::inline_comments`, which
puts a hard line after any line comment. Pinned by
`two_line_comments_merged_onto_one_line_are_still_rejected`.
- **Blank lines inside a bracketed or label list are dropped**, as
`Fmt::delimited` already documents. `ibex_alu.sv`'s blank line between
`ALU_SUB,` and `// Comparator OPs` does not survive; the comment and the
order do.
- **Comments inside a replication, inside a compactly-printed bracket
expression, and between a *continuous assignment's* value and its `;` remain
refusals** — see Corpus results. They are refusals, not corruption, and each
needs its own design decision.
## Handshakes
**Changed in `vlog_parser::ast` (consumed by `vlog_formatter::format`):**
| item | before | after |
|---|---|---|
| `SensItem` | `{ edge, expr }` | `{ sep: Option<SensSep>, edge, expr }`; new `enum SensSep { Comma, Or }`. `sep` is the separator written *before* this item, `None` on the first. Any consumer printing an event list must interleave these instead of picking one spelling per list. |
| `Module::imports` | `Vec<String>` | `Vec<Vec<String>>` — one entry per `import` statement. Print one `import ...;` line per entry. |
| `Module::param_ports` | `Vec<ParamPort>` | `Option<Vec<ParamPort>>`. `None` = no `#(...)` written; `Some(vec![])` = a written `#()`. `is_empty()` no longer distinguishes them. |
| `Module` | — | new `param_dangling` / `port_dangling: Vec<Comment>`: comments before the closing `)` of each header list. |
| `PortList::Empty` | — | may now come with a non-empty `Module::port_dangling` (`module m (/* c */);`). |
| `Parser::parse_port_list` | `-> PResult<PortList>` | `-> PResult<(PortList, Vec<Comment>)>` |
| `Instantiation::params` | `Vec<Connection>` | `Option<Vec<Connection>>`, same meaning as `Module::param_ports`. |
| `Expr::Binary` | `{ .., comments: Vec<Comment> }` | `{ .., comments: Box<BinaryComments> }` with `before` / `after` fields. Boxed to keep `Expr` small — otherwise `clippy::large_enum_variant` fires on `ItemKind`/`GenElse`. |
| `Expr::Ternary` | `{ cond, then, els }` | `+ comments: Box<TernaryComments>` with the four positions `before_question` / `after_question` / `before_colon` / `after_colon`. Boxed for the same reason. |
| `Expr::Empty` | unit variant | `Empty(Vec<Comment>)` — the comments written inside `.name(/* unused */)`. |
| `CaseItem::labels`, `GenCaseItem::labels` | `Vec<Expr>` | `Vec<ExprItem>`, so each label carries its own leading/trailing comments. |
| `AssignPair` | `{ meta, lhs, rhs }` | `+ rhs_comments: Vec<Comment>` — comments between the `=` and the value. |
New parser helper `Parser::take_around(mark)` collects "every comment written
in the gap ending at the cursor". It **clamps `mark`**, which also removes a
latent panic: the two pre-existing raw `pending_trailing.split_off(mark)` call
sites (`parse_binary_inner`, the `Expr::Paren` arm) could underflow when a
nested construct drained the pending list, and both now go through the helper.
New formatter helpers: `Fmt::delimited_dangling` (`delimited` delegates to it
with an empty slice, so its eight other call sites are untouched),
`Fmt::inline_comments`, `Fmt::case_labels`, `Fmt::ternary_with_comments`,
`Fmt::assign_pair`, and the `BinaryOp` struct that carries an operator plus the
comments on each side through `binary_chain`'s flattening walk.
**Consumed from `verify.rs`:** nothing new. **No normalization was added or
broadened**, per CLAUDE.md hard invariant #4. The three token-rewrite bugs are
fixed by emitting the right token; the comment bug by printing the comment
where the input had it. The seven new tests assert the net still *rejects*
every shape these fixes could plausibly have been "fixed" by forgiving instead
— including both directions of the `,`↔`or` rewrite.
**Recursion/chain budgets (`docs/features/recursion-limit/README.md`):** no new
budget is charged and none is needed. Nothing added here recurses or builds a
left-nested chain. `SensSep` is a `Copy` enum on an existing leaf; the import
change adds one `Vec` level inside a loop that was already flat; `params`
becomes an `Option` around an existing `Vec`; the comment work moves
already-allocated `Comment` values between existing nodes. The two new boxes
(`BinaryComments`, `TernaryComments`) sit *beside* the existing `Box<Expr>`
children, so root-to-leaf depth is unchanged — and both make `Expr` **smaller**
than it was before this feature (48 and 32 bytes for those variants, against 64
and 24+96 if left inline), which is why `clippy::large_enum_variant` is silent
again.
## Status / TODO
- [x] **A** — event-list `,` vs `or` preserved per separator (13 corpus files).
- [x] **B** — comments in port/parameter lists, declarations, case labels and
expressions (26 corpus files, six distinct shapes — see Work log).
- [x] **C** — consecutive module-header `import`s stay separate statements
(5 corpus files).
- [x] **D** — a written empty `#()` is printed back (1 corpus file), plus the
same bug found in the *module header* `#()` while fixing it.
- [x] 28 new case-table entries (19 comments, 4 statements, 3 module_headers,
2 instantiation) + 6 parser unit tests + 7 verification rejection tests.
- [x] `cargo test --workspace` 111 passed (was 98), clippy silent, fmt clean.
- [x] Corpus acceptance: 46 verification errors → **0**, parse rate held at
468/820, corpus verified unmodified.
- [x] 10 named corpus files (2–4 per bug) format and are a fixed point on the
second pass.
- [x] `TODO.md`: nothing to check off — none of these bugs has a backlog item.
- [ ] **Not done, deliberately:** three of the four comment-placement refusals
documented in `docs/features/formatter-bug-fixes/README.md` still refuse
(replication, compact bracket expression, value-before-`;` in a
*continuous assignment*). The fourth — a comment in a ternary branch —
is fixed here as a side effect of `TernaryComments`. See Corpus results.
- [ ] **Not done:** comments between `=` and the value are handled for
continuous assignments only, not for procedural assignments or
declarator initializers. No corpus file needs them; the shape is
`x <= // c` ⏎ `y;`. Same fix, one field each, when someone asks.
## Corpus results
`./tools/corpus_check.sh corpus` against the same pinned 820-file corpus,
release build, corpus verified unmodified afterwards (`git status --porcelain`
clean in all four repos apart from the untracked `.lucisv-corpus-rev` stamps).
| metric | after macro-items | after corpus-bugs |
|---|---|---|
| **verification-error** | 46 (5.6%) | **0 (0.0%)** |
| parsed (reached the formatter) | 468/820 (57.1%) | 468/820 (57.1%) |
| formattable (parsed *and* passed the net) | 422/820 (51.5%) | **468/820 (57.1%)** |
| would-reformat | 420 | 466 |
| parse-error | 352 (42.9%) | 352 (42.9%) |
| ok-unchanged | 2 | 2 |
| crash | 0 | 0 |
```
outcome files share
-------------------- ----- -------
ok-unchanged 2 0.2%
would-reformat 466 56.8%
parse-error 352 42.9%
verification-error 0 0.0%
other-error 0 0.0%
crash 0 0.0%
-------------------- ----- -------
total 820 100.0%
```
**Diffed the two TSVs by path, not just by count**: exactly 46 files moved
`verification-error → would-reformat` and **nothing else changed status** — no
parse regression, no file that was formatting before stopped. The script's own
exit status is now 0 (it was 1).
### The 46, by root cause
Classified from the diagnostics before any code was written, since the
corpus-check README's original 10/9/4/1 split predates `macro-items`:
| cause | files | shape |
|---|---|---|
| A | 13 | `@(posedge clk_i, negedge rst_ni)` → `or` |
| B | 26 | six shapes, below |
| C | 5 | two header `import`s merged, `;` → `,` |
| D | 1 | `picorv32 #(\n) uut (` loses `#()` |
Bug B's 26 split six ways, which is why it was the bulk of the work:
| B shape | files | example |
|---|---|---|
| B1a comment before a list's closing `)` | 6 | `prim_clock_buf.sv`, `prim_fifo_async_simple.sv`, `ibex_controller.sv` |
| B1b comment inside an empty connection | 2 | `edge_propagator.sv` `.ack_tx_o (/* unused */)` |
| B2 comment between a declarator and its `;` | 3 | `prim_subst_perm.sv` `/* verilator split_var */` |
| B3a comment after a binary operator | 7 | `ibex_prefetch_buffer.sv`, `ibex_trvk.sv` |
| B3b comment between case labels | 2 | `ibex_alu.sv` `// Comparator OPs` |
| B3c comment inside a ternary | 6 | `prim_sha2.sv`, `uart_core.sv`, `ibex_pmp.sv` |
Two files (`ibex_icache.sv`, `uart_core.sv`) needed a seventh shape that only
surfaced once the first six were fixed: a comment written between `assign x =`
and the value.
### Named-file acceptance
Each formatted into a scratch copy, then `--check`ed on the result. The corpus
itself was never written to (`md5` before/after identical for every file).
| bug | file | before | after |
|---|---|---|---|
| A | `common_cells/src/cdc_4phase.sv` | `,` at 172:28 → `or` | fixed point |
| A | `common_cells/src/sync.sv` | `,` at 27:30 → `or` | fixed point |
| A | `ibex/shared/rtl/ram_1p.sv` | `,` at 46:28 → `or` | fixed point |
| B | `…/prim_generic/rtl/prim_clock_buf.sv` | `/* verilator lint_on UNUSED */` at 13:3 moved | fixed point |
| B | `…/prim/rtl/prim_subst_perm.sv` | `/* verilator split_var */` at 32:49 moved | fixed point |
| B | `ibex/rtl/ibex_alu.sv` | `// Comparator OPs` at 64:7 moved | fixed point |
| B | `ibex/rtl/ibex_prefetch_buffer.sv` | `// Current address + 4` at 171:25 moved | fixed point |
| C | `…/fpv/tb/prim_alert_rxtx_tb.sv` | `;` at 9:27 → `,` | fixed point |
| C | `…/fpv/tb/prim_alert_rxtx_async_tb.sv` | `;` at 9:27 → `,` | fixed point |
| D | `picorv32/testbench_ez.v` | `#` at 47:11 dropped | fixed point |
Spot-checked the output text, not just the exit code: `prim_clock_buf.sv` keeps
both `lint_off`/`lint_on` pragmas inside the `#( ... )`, `sync.sv` keeps
`@(posedge clk_i, negedge rst_ni)`, `prim_alert_rxtx_tb.sv` keeps two `import`
lines, `testbench_ez.v` keeps `picorv32 #() uut (`.
### Remaining refusals: none in this corpus
Zero files in the 820 refuse. The known comment-placement refusals from
`docs/features/formatter-bug-fixes/README.md` were re-probed by hand, since the
corpus no longer exercises them:
| refusal | still refuses? |
|---|---|
| comment inside a replication — `{2{a, // c` | yes |
| comment inside a compact bracket expression — `x[a /* c */ + b]` | yes |
| comment between a continuous assignment's value and its `;` — `assign y = a /* c */ ;` | yes |
| comment in a ternary branch — `assign w = c ? a : // c` ⏎ `b;` | **no — fixed here** |
The fourth was listed as a nit in that feature's QA log and is fixed as a side
effect of `TernaryComments`: `after_colon` is exactly the position it names.
The other three are untouched and remain refusals, not corruption.
## Work log
### 2026-08-19 — dev agent
Read `CLAUDE.md`, `README.md`, and the corpus-check, macro-items,
formatter-bug-fixes and recursion-limit feature READMEs before touching code.
Baseline: `cargo test --workspace` 98 passed, clippy silent, fmt clean;
`tools/corpus_check.sh corpus` reproduces 46 verification errors exactly.
**Classified the 46 before writing anything.** The corpus-check README's
10/9/4/1 split is pre-`macro-items`; the live numbers are 13/26/5/1, and bug B
turned out to be six different shapes rather than one. Doing this first is what
kept the work ordered — B3c (ternaries) would otherwise have looked like a
surprise at the end.
**Bug A (event-list separator) — fixed.** `Fmt::sens_list` chose one separator
for the whole list (`if any item has an edge { " or " } else { ", " }`), so a
comma list with edges came out as `or`. The information simply was not in the
AST. Added `SensSep` and `SensItem::sep`, set from whichever of `,`/`or` the
parse loop ate, and replaced `join(parts, sep)` with an interleave. Mixed lists
(`@(posedge clk, negedge rst_n or a, b)`) now round-trip each separator
independently, which the old shape could not express at all.
**Bug C (merged header imports) — fixed.** `parse_module` did
`imports.extend(parse_import_list())`, flattening every header `import` into one
`Vec<String>` the formatter printed as a single `import a::*, b::t;`. A
one-word parser fix (`extend` → `push`) once the type became `Vec<Vec<String>>`.
Added a case asserting that a *single* import with several paths still stays one
statement, since that is the behavior the naive fix would break.
**Bug D (dropped empty `#()`) — fixed.** `Instantiation::params` was a
`Vec<Connection>` and the formatter tested `is_empty()`, so "no override list"
and "an empty override list" were the same value. Made it `Option<Vec<_>>` —
the `Option` carries "was it written", exactly like `MacroCall::semi`. **While
there, found the same bug in the module header**: `module m #() (...);` also
dropped its `#()`. No corpus file writes it, but it is the identical root cause
in code I was already changing, so it rides along (`Module::param_ports` is now
an `Option` too).
**Bug B — six shapes, fixed in increasing order of AST churn.**
- *B3a, comment after a binary operator.* `parse_binary_inner` already captured
comments written *before* the operator; the corpus writes them *after*
(`!is_sealing_cap && // Not sealing cap`). Added the mirror capture and
taught `binary_chain` to print each side. Extracted `BinaryOp` so the
flattening walk carries an operator plus both comment runs instead of a
widening tuple.
- *B3c, comments inside a ternary.* Four gaps, four vectors
(`TernaryComments`), because a comment after `?` and one before `:` are not
interchangeable. **Chose four explicit positions over one "somewhere inside"
vector**: the latter cannot be printed back without guessing, and a wrong
guess is a stream divergence, i.e. a refusal — the bug I was fixing.
- *B3b, comments between case labels.* `labels: Vec<Expr>` had nowhere to hang
a comment. Switched both `CaseItem` and `GenCaseItem` to `Vec<ExprItem>` and
reused the existing `parse_expr_item`/`parse_expr_list` pair, which already
harvests exactly the right comments. `Fmt::case_labels` keeps the current
one-line rendering when no label carries a comment and goes one-per-line
otherwise, so no existing case moved.
- *B1b, comments in an empty connection.* `.ack_tx_o (/* unused */)` parsed to
`Expr::Empty` and the comment drifted past the `)`. Made it
`Expr::Empty(Vec<Comment>)` — the comments live on the node they describe
rather than in a field on `Connection` that would be meaningless for every
other variant.
- *B2, comment before a declaration's `;`.* `parse_declarators` harvested a
trailing comment only when a comma followed, so the last declarator's
`/* verilator split_var */` fell through to the *item's* trailing and printed
after the `;`. Now always harvested — safe because the `;` has not been
consumed at that point, so nothing written after it can be picked up.
`Fmt::declarators` puts a hard line after a *line* comment there, since the
caller appends the `;` on the same line; that makes the pathological
`logic x // note` ⏎ `;` idempotent instead of a refusal.
- *B1a, comments before a list's closing `)`.* The largest change.
`Fmt::delimited` grew a sibling `delimited_dangling` rather than a fifth
parameter, so its eight unrelated call sites are untouched. `take_dangling`
— which already existed for `end`/`endmodule` — is now also called before the
`)` of the parameter-port list and both port-list flavors, and the comments
land in two new `Module` fields. Also covered the empty-list case
(`module m (/* c */);`), which needed `delimited_dangling` to stop
short-circuiting on `items.is_empty()`.
**A seventh shape only appeared after the first six.** With B1a–B3c done the
corpus was at 2 errors, both `assign x =` ⏎ `// comment` ⏎ `value`. Added
`AssignPair::rhs_comments`. Worth recording: fixing comment motion is
layered — each fix stops a comment drifting one step further, and the next
resting place is only visible once the earlier one is gone.
**Two cross-cutting decisions.**
1. **One helper for printing a run of comments** (`Fmt::inline_comments`),
used by the binary, ternary and assign paths. The reason is not tidiness: a
naive `for c in comments { push(" "); push(comment) }` prints
`// a // b` for two line comments, which re-lexes as *one* comment — comment
loss the net would catch, but only as a refusal. The helper puts a hard line
after any line comment. It is pinned by its own rejection test.
2. **`take_around(mark)` clamps `mark`.** Writing it exposed that the two
pre-existing raw `split_off(mark)` call sites can underflow — a nested
construct's `take_trailing()` drains the pending list with `drain(..)`, so
`len` can drop below `mark` and `split_off` would panic. Both call sites now
go through the clamped helper. No `unwrap`/`expect`/`panic!` was added
anywhere in library code.
**`verify.rs` was not touched, and did not need to be.** Confirmed with
`git diff --quiet HEAD -- crates/vlog_formatter/src/verify.rs`. Every one of
these bugs was the formatter emitting something the input did not say, so the
net was right every time; there was never a case where the correct output
failed a check. Added seven rejection tests anyway — one per root cause plus
the comment-motion and merged-line-comment shapes — so that if someone later
"fixes" a regression here by widening a normalization instead, those tests fail
first. The `,`↔`or` test asserts *both* directions.
**Clippy fallout, and why the boxes are there.** Adding `after_op` to
`Expr::Binary` and `TernaryComments` to `Expr::Ternary` grew `Expr` enough to
trip `clippy::large_enum_variant` on `ItemKind` and `GenElse` (clean at `HEAD`,
verified in a throwaway worktree). Boxing both comment groups fixes it and
leaves those variants *smaller* than before this feature. Also dropped an
unused `BinaryComments::is_empty` rather than keep a method with no caller.
Did not touch `tools/`, `corpus/` contents, `crates/lucisv/`, `CLAUDE.md`,
`README.md` or `TODO.md` (no matching checkbox exists — these bugs were never
backlog items). Did not run `git commit`/`git push`.
**Results:** `cargo test --workspace` **111 passed, 0 failed** (up from 98: +6
`vlog_parser` parser unit, +7 `vlog_formatter` verification; the case table grew
from 209 to 237 entries inside its single test). `cargo clippy --all-targets`
silent. `cargo fmt --check` clean. Files touched:
`crates/vlog_parser/src/{ast,parser}.rs`,
`crates/vlog_formatter/src/format.rs`,
`crates/vlog_formatter/tests/cases/{comments,statements,module_headers,instantiation}.cases`,
`crates/vlog_formatter/tests/verification.rs`, this README.
## QA log
### 2026-08-19 — QA agent
Verified every claim in the dev's Work log and Status/TODO against the code,
a fresh release build, and independent corpus runs. **All claims pass.**
Zero blocking findings — no masked corruption, no regression in the 237-case
table, no panic reachable through the shipped binary.
**Tooling (exact numbers).**
- `cargo test --workspace`: 111 passed, 0 failed (18+13+3+1+4+2+32+38 across
the ten test binaries). `cargo clippy --all-targets`: silent. `cargo fmt
--check`: clean.
- `git diff --quiet HEAD -- crates/vlog_formatter/src/verify.rs`: exits 0 —
byte-identical to `HEAD`, confirmed independently.
- Case table: 209 → 237 entries, delta +28 split exactly
comments+19/statements+4/module_headers+3/instantiation+2 per-file, matching
the Work log's claim byte for byte.
- `Box<BinaryComments>`/`Box<TernaryComments>` size claim reproduced exactly:
built a throwaway crate against `vlog_parser` and measured
`size_of::<BinaryComments>() == 48`, `size_of::<TernaryComments>() == 96`
(raw structs); the *variant* sizes the Work log quotes (48 for
`Expr::Binary`, 32 for `Expr::Ternary`) are the boxed-field arithmetic
(8+24+8+8=48, 8+8+8+8=32) and check out.
**Corpus (independent re-run, fresh release builds).** Built the working
tree's release binary and, in a separate `git worktree add --detach HEAD`
(no `git stash` used — sandbox denied it), built `HEAD`'s release binary too,
so both TSVs came from real independent runs rather than trusting the
committed numbers:
- `HEAD` binary: 46 verification-error, exit 1 — reproduces the pre-fix
baseline exactly, including all 46 file paths and diagnostics quoted in the
README's "The 46" table.
- Working-tree binary: 0 verification-error, 468/820 parsed, 466
would-reformat, exit 0.
- Diffed both TSVs by path (`sort -k2,2 | cut -f1,2`, then `diff`): exactly 46
`verification-error` lines removed and 46 `would-reformat` lines added, and
the sorted path lists of the removed and added rows are byte-identical —
confirmed with `diff removed_paths.txt added_paths.txt` (empty). No other
row changed outcome.
- Re-ran the working-tree binary a second time: output TSV byte-identical to
the first (deterministic).
- All four corpus repos `git status --porcelain` clean after both runs
(only the untracked `.lucisv-corpus-rev` stamps, as documented).
- Cleaned up the worktree (`git worktree remove --force`) after use; the main
working tree's `git status` is unchanged from before this session.
**Adversarial round-trips (debug binary, scratchpad).** Built battery of
hand-written inputs beyond the dev's own cases, each formatted twice and
checked for idempotency:
- Mixed 3-separator sens list `@(posedge a, negedge b or posedge c)`: each
separator preserved, idempotent.
- `#()` / `#(.W(8))` / absent, on both instantiations and module headers
(including `module m #() (input a);`): all correct. (My first attempt used
`#(.P(1))` on a module header, which is instantiation-override syntax, not
legal in a header — parser correctly rejected it; not a bug, my test error.)
- Two comments in one empty connection `.x(/* a */ /* b */)`: idempotent,
both comments kept inside the parens.
- Comment before the colon of a case label (`A // before colon\n:`) and after
it (`A: // after colon`): both idempotent, sane placement.
- Comments on *both* sides of a binary operator simultaneously
(`a /* before */ && /* after */ b` and the line-comment variant): both
idempotent — this exact combination isn't in the case table but the shared
`inline_comments`/`BinaryComments{before,after}` machinery handles it
correctly.
- Block comment in an empty port list `module m (/* none */);`: idempotent.
- Comment before the closing `}` of a concat/replication
(`{a, b\n// c\n}`): **refuses cleanly** (exit 2, verification failure) —
not one of the documented seven shapes (those cover `)`-closed lists, not
`}`-closed ones), consistent with "refusal, not corruption."
- Comments written between or after header `import` statements (a shape
adjacent to bug C but not one of the documented seven — e.g. a comment on
its own line between `import a::*;` and `import b::t;`, or a trailing
comment on a non-final import): **refuses cleanly** (exit 2) rather than
silently dropping or misplacing the comment. Non-blocking; flagging as a
known gap in case a future corpus file exercises it — the README's
Handshakes/Status section doesn't claim these are handled, and they aren't,
correctly refusing instead of corrupting.
**Sabotage checks (2 of the 7 new rejection tests).** The 7 tests in
`verification.rs` call `verify_equivalence` directly on hand-written
`(input, output)` string pairs, so they exercise `verify.rs` alone — hacking
`Fmt::inline_comments` (as suggested) would not touch them, since none of
these seven go through the actual formatter. Adjusted the attack accordingly
and sabotaged `verify.rs` itself twice, confirming each test is a real pin,
not a vacuous pass:
1. Widened `Item::matches` to treat the `,` symbol and `or` keyword as
equivalent (a plausible future "forgive the spelling" mistake) →
`an_event_list_comma_rewritten_as_or_is_still_rejected` failed with the
expected panic message ("expected a divergence between..."). Reverted;
`git diff --quiet HEAD -- crates/vlog_formatter/src/verify.rs` confirmed
clean afterward.
2. Added a `merge_adjacent_comments` pass in `lex_stream` that concatenates
consecutive comment items (a plausible future "stop caring about comment
splitting" mistake) → `two_line_comments_merged_onto_one_line_are_still_rejected`
failed the same way. Reverted; `verify.rs` confirmed byte-identical to
`HEAD` again.
Both sabotages used only `verify.rs`; no other file was touched. Ran the full
workspace suite after the final revert: 111 passed, 0 failed.
**`take_around` panic claim — reproduced the old panic directly**, not just
read the code. Built `HEAD`'s parser in a separate worktree (pre-fix, with the
two raw `pending_trailing.split_off(mark)` call sites) and constructed inputs
that make a nested comment-harvest (`take_meta`/`take_trailing`, which
unconditionally drain *all* of `pending_trailing`, not just what's past an
outer `mark`) drain below an outer, already-captured `mark`:
- `parse_binary_inner` site: `assign y = a + // note\n b(x) * c;` — the
operator's own trailing comment (`// note`) gets pushed onto
`pending_trailing`, inherited as a nonzero starting `mark` by the recursive
`parse_binary(prec+1)` call for the right operand, then wiped out by the
nested call argument's `take_meta()` before the next operator's harvest —
`HEAD`'s binary panics: `` panicked while formatting: `at` split index
(is 1) should be <= len (is 0) `` (exit 2, caught by `catch_unwind`, not a
hard crash, but still a panic in library code). The working-tree binary
formats it cleanly (exit 0) and idempotently.
- `Expr::Paren` site: same idea one level deeper —
`assign y = a + // note\n (b(x)) * c;` — reproduces the identical panic
message on `HEAD`; the working-tree binary again formats cleanly and
idempotently.
Both call sites in the diff were read and confirmed to go through the new
`take_around` helper, and both are now demonstrably panic-free on inputs that
provably panicked before the fix. Cleaned up both worktrees afterward.
**Named-file acceptance and refusals — all confirmed.** Formatted all 10
named corpus files into scratch copies (corpus files' md5 unchanged
before/after every run); all 10 format, `--check` clean on the formatted
result (fixed point). Spot-checked content, not just exit codes:
`testbench_ez.v` line 44 keeps `picorv32 #() uut (`; `prim_clock_buf.sv` keeps
both `lint_off`/`lint_on` pragmas inside `#( ... )`; `sync.sv` keeps
`@(posedge clk_i, negedge rst_ni)`; `prim_alert_rxtx_tb.sv` keeps two separate
`import` lines. The three documented remaining refusals (replication, compact
bracket expression, comment between a continuous assignment's value and its
`;`) all still refuse cleanly (exit 2, verification failure, no corruption).
The ternary-branch case is confirmed fixed: `assign w = c ? a : // c\nb;`
formats to a clean, idempotent `exit 0`.
**CLAUDE.md compliance.** Every `panic!`/`unwrap`/`expect` added in this diff
is inside `#[cfg(test)] mod tests` in `parser.rs` (grepped the full diff for
these patterns outside `+++`/test blocks — none found in library code paths).
No `#[allow]` added anywhere. README has all seven required sections,
Handshakes accurately describes every signature change I checked against the
actual diff, and the Work log's specific factual claims (numbers, file
paths, byte sizes) all independently verified as stated above.
**Overall disposition: PASS on every claim, no blocking findings.** The two
non-blocking observations (concat/replication `}`-comment and header-import
inter-statement comments both refuse rather than corrupt) are pre-existing
gaps outside this feature's documented scope, not regressions — recorded here
for visibility, not as required fixes.
## Review
**2026-08-19 — lead. Verdict: accepted and committed as-is; no lead fixes
needed. This round takes the 820-file corpus to zero verification errors
and zero crashes — hard invariant #1 demonstrated at ecosystem scale.**
What distinguishes this round:
1. **The fixes are all "say what the input said."** Every one of the
four root causes was the formatter inventing or discarding
information (a separator, a `;`, an empty `#()`, a comment's
position). The fixes make the AST carry the missing fact
(`SensSep`, `Vec<Vec<String>>` imports, `Option<Vec>` params,
comment fields) rather than special-casing the printer — the right
layer every time.
2. **verify.rs byte-identical to HEAD**, confirmed twice (dev and QA).
The net was right on all 46 files; the 7 new rejection tests turn
that judgment into pinned regression protection, and QA's sabotage
checks prove they bite. This is hard-invariant #4 practiced, not
just written down.
3. **Discipline on discovery**: the same-root-cause module-header `#()`
fix and the `take_around` panic clamp both rode along because the
dev was already in that code — correctly judged; the panic claim was
verified by QA the strong way (reproduce on pre-fix binary).
4. Bug B's "one bug" turning into seven shapes (and the seventh only
visible after six were fixed) is a good record of why comment
attachment is the hardest part of this codebase — and why
`Fmt::inline_comments` as the single printing path matters.
Dispositions on QA's non-blocking observations: both (concat
`}`-comment, header-import inter-statement comments) join the
documented-refusals list — refusals, not corruption; candidates for a
future comments round alongside the two survivors from
formatter-bug-fixes (replication, compact bracket, assign-value; the
ternary one is fixed by this round's `TernaryComments`).
Corpus state after this round: 468/820 parse (57.1%), 466 would-reformat,
2 ok-unchanged, 352 parse-error, **0 verification-error, 0 crash** —
`corpus_check.sh` exits 0 for the first time. The remaining work is
parse coverage (roadmap in README.md) and the LSP track (TODO §6).