Merge testbench-syntax Lane B (formatter round-trip bugs)
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 21s

Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	TODO.md
This commit is contained in:
lucio committed 2026-08-29 12:56:47 -07:00
commit 27a652ee3d
6 files changed
+987 -46

No files matched your search

+404
View File
@@ -24,6 +24,21 @@ The five:
5. `always @( /* c */ * )` loses the comment: `parse_sens_list` discarded
comments written inside the parens of an implicit sensitivity list.
**Round 2 (2026-08-29, Lane B of the testbench-syntax wave).** The same
feature, extended to `syntax_coverage.md`'s bucket 2: the 12 real OpenTitan
files that parse with zero errors but whose *formatted output* the safety net
refused. Three more bugs, all in `format.rs`'s layout, none needing a
`verify.rs` change:
6. A line comment trailing the then-branch's `end` swallowed the `else` that
followed it (`end // addr_phase_write` + `else if (...) begin` came back as
one comment). 4 of the 12 files.
7. A comment written inside a statement header's parentheses (`if (// why` ⏎
`cond)`, `while (`, `repeat (`, `wait (`, `case (`) printed *after* the
`)`, moving it across a token. 7 of the 12 files.
8. `default;` — the case-item colon IEEE 1800 §12.5 makes optional — came
back as `default:`, inventing a token the source never wrote. 1 file.
## Assumptions
- The four `#SKIP` expected outputs are the spec. None of them was changed.
@@ -66,6 +81,46 @@ The five:
enclosing group in this printer. The hug only applies when the value already
contains a forced break, so no case without comments changed.
### Round 2 (2026-08-29)
- **`verify.rs` was not touched at all this round** (`git diff` on it is
empty), and no normalization was added or broadened. Every fix is a layout
change in `format.rs`; the safety net's judgement of all three shapes is
unchanged, and four crafted (input, corrupted output) pairs assert it still
rejects exactly the corruptions these bugs used to produce.
- **The parser's trivia attachment is taken as given.** Nothing between a
statement header's `(` and `)` owns trivia, so a comment written there is
queued and lands on the next node that takes meta — the body statement, or
a `case`'s first item. The formatter takes it back by *span* rather than
asking the parser to change: a leading comment of the body that starts
before the header's `)` was written inside the parentheses. This is Lane B's
file-set constraint made into a design point, and it is exact, because a
comment's byte span says unambiguously which side of the `)` it was on.
- **The `)` is found in the source, not in the AST**, by skipping whitespace
and comments forward from the end of the condition expression
(`skip_trivia`). Only trivia can stand there for `if`/`while`/`repeat`/
`wait`/`case`. If anything else turns up, the header prints its plain
parentheses and takes nothing, so an unrecognized shape behaves exactly as
it did before.
- **A cuddled `else` is a layout decision, not a token.** `end` keeps `else`
on its line unless the then-branch's own trailing comments end in a line
comment, which would swallow it. A block comment still cuddles
(`end /* why */ else`).
- `for`, `foreach` and `do ... while` are **not** covered: the first two do
not end their header in a single condition expression, and a `do`-`while`
has no body after its parentheses to take the comment back from. All three
still refuse cleanly and are pinned as refusals by a test.
- A comment written *before* a header's `(` (`if /* c */ (a)`) is also not
covered — the formatter has no offset for the `(`, so such a comment is
treated as if it were inside and the file is still refused, exactly as it
was before. No corpus use.
- **`default;` is read from the source too.** `CaseItem` records no `colon`
flag (the parser does `let _ = self.eat_sym(":")`), so `default_has_colon`
looks at the byte after the keyword. With a null body the `;` hugs the
keyword — `default;`, not `default ;` — while `default: ;` keeps both the
colon and the space it already had. Generate-case `default` reads the same
way.
## Handshakes
- **`vlog_parser::token::Comment` gained a position** (the handshake request
@@ -102,6 +157,45 @@ The five:
and the top-level `README.md` (another agent's scope) are untouched;
`cargo fmt` was run and left those files byte-identical.
### Round 2 (2026-08-29)
- **Nothing was changed outside `crates/vlog_formatter`.** Round 2 consumes
the AST exactly as it stands: `Comment.span`, `Expr.span`, `CaseItem.span`
and `Meta.leading`'s source order are the only new load-bearing surfaces,
and all four already existed. `git diff` on `crates/vlog_parser` and
`crates/vlog_semantic` is empty.
- **Open handshake request to whoever owns `vlog_parser/src/parser.rs`
(Lane A's file this wave).** `Parser::take_before_open` (`parser.rs:757`)
calls `take_dangling()`, which drains the *whole* pending-comment queue —
`pending_trailing`, `pending_leading` and the bracket token's own leading
comments — rather than only the comments actually written in front of the
bracket. So a comment written just after a statement header's `(` is
swallowed by the first call inside the condition and printed between that
call's callee and its own `(`:
```systemverilog
if (// If keymgr is not enabled in the current LC
!cfg.keymgr_vif.get_keymgr_en() || ...
```
comes back as `!cfg.keymgr_vif.get_keymgr_en // If keymgr ...` ⏎ `() ||`.
`header_parens` cannot take it back — it never reaches the body's leading
comments — and the formatter cannot hoist it out past the `!` without a
cutoff threaded through every `expr` call, which is far more machinery than
the parser fix. **Requested fix**: in `take_before_open`, keep only the
comments whose `span.start >= self.last_end()`, i.e. those written in the
gap that ends at the bracket, and leave the rest queued. `last_end()`
already exists (`parser.rs:611`). This is the last of the 12 bucket-2 files
(`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv`); the shape is pinned as a
clean refusal by
`verification.rs::a_comment_before_a_call_in_a_condition_is_still_refused`,
which is the test that should flip to a `.cases` entry when the parser fix
lands.
- **Format-cache discipline** (`topo.md` §2.3): this round changes formatter
*output* for the shapes above, so the workspace version must be bumped at
release or a stale `.lucisv_cache` will skip files that would now format
differently. Flagged for the lead; no version was bumped here.
## Status / TODO
- [x] Bug 3 — closing block labels preserved (`end`, all `join` kinds,
@@ -131,6 +225,34 @@ The five:
The "re-enable the four `#SKIP` cases" item lives in the case-tables
README's TODO and is now satisfied.
### Round 2 (2026-08-29)
- [x] Bug 6 — a line comment trailing `end` no longer swallows the `else`
that follows it; a block comment still cuddles.
- [x] Bug 7 — a comment written inside an `if`/`while`/`repeat`/`wait`/`case`
header's parentheses is printed inside them, on the correct side of the
condition.
- [x] Bug 8 — `default;` keeps IEEE 1800 §12.5's optional colon off, and
`default: ;` keeps it on.
- [x] 11 of the 12 bucket-2 OpenTitan files format cleanly and are
idempotent; the whole checkout is unchanged on disk. Before/after in
the work log.
- [x] 11 new `.cases` entries (10 in `comments.cases`, 1 in
`statements.cases`) — each one asserts the output *and* that
re-formatting it is a fixed point, which is what the harness does.
- [x] 4 masked-corruption rejection pairs + an explicit
comments-never-dropped assertion in `verification.rs`, plus 4 pinned
refusals for the shapes deliberately left uncovered.
- [x] `cargo fmt --check` clean, `cargo clippy --all-targets` silent,
`cargo test --workspace` green, pinned corpus 813/820 (baseline 813,
zero verification errors).
- [ ] Not fixed, needs a change in `vlog_parser` (see Handshakes): a comment
after `if (` when the condition starts with a call —
`keymgr_scoreboard.sv`, the 12th file.
- [ ] Not fixed, no corpus evidence, pinned as refusals: a comment inside a
`for`/`foreach` header or a `do ... while (...)`; a comment written
between a header keyword and its `(`.
## Work log
### 2026-08-18 — dev agent
@@ -239,6 +361,109 @@ an indented banner comment) formats cleanly, and `lucisv` on its own output is
byte-identical. Every bug's original repro from the two feature READMEs was
re-run through the built CLI and now exits 0.
### 2026-08-29 — dev agent (Lane B, testbench-syntax wave)
**Scope.** `syntax_coverage.md`'s bucket 2: the 12 OpenTitan files that parse
with zero errors but whose formatted output the safety net refused. Measured
first, against the real checkout at `/Users/guoliangchen/repo/opentitan`
(`--no-cache --check` over all 3,943 `.sv`/`.svh`): **151 failures, 12 of them
`verification failed:`** — reproducing the sweep exactly. The 12 are three
shapes, not one:
| # | shape | files |
|---|---|---|
| 6 | `end // c` ⏎ `else …` — the trailing line comment swallows the `else` | 4 |
| 7 | a comment inside a statement header's `(...)` prints after the `)` | 7 |
| 8 | `default;` comes back as `default:` | 1 |
**Bug 6 — `end // c` then `else`.** `if_stmt` cuddled `else` onto the `end`
line whenever the then-branch was a block. `stmt_as_body` has already printed
the block's trailing comments by then, so ` else if (b) begin` landed *inside*
a line comment's text and `verify.rs` saw one comment reading
`// addr_phase_write else if (addr_phase_read) begin`. The whole fix is one
extra condition on `then_is_block`: a free `trailing_ends_line(&then.meta)`
that asks whether the last thing `trailing` prints is a `//` comment. A block
comment still cuddles, which is what the source wanted anyway.
**Bug 7 — comments inside a header's parentheses.** The header's `(` and `)`
are printed by `parens()` and belong to no node, so the parser has nowhere to
put a comment written between them: it stays in the pending queue and lands on
the next node that calls `take_meta` — the body statement (`if`, `while`,
`repeat`, `wait`) or the first case item (`case`). Printed there, the comment
sits after a `)` it was written before.
Fixed entirely on the formatter side, by span. `header_parens(cond, body_meta)`
finds the closing `)` with `skip_trivia` (forward from `cond.span.end`; only
whitespace and comments can stand there), takes every leading comment of the
body that starts before it, splits them at `cond.span.start` into before/after
buckets, and hands them to `paren_comments` — which is the existing
`ExprKind::Paren { before, after }` layout, factored out and now shared by both
callers rather than duplicated. It returns how many comments it consumed;
`stmt_as_body_from` / `leading_from` / `case_body` skip exactly that many.
`leading`, `stmt_as_body` and `case_body`'s old signature are all preserved as
`skip = 0` wrappers, so the twelve other `stmt_as_body` call sites are
untouched. When the source is not the expected shape (no `)` where one was
expected, or nothing to take) the function returns the plain `parens(cond)` and
takes nothing, so every input that formatted before formats identically.
`for`, `foreach` and `do ... while` were deliberately left out: the first two
do not end their header in one condition expression and the third has no body
after its parens. Confirmed they still refuse cleanly and pinned that with a
test, so a later round sees them change rather than appear.
**Bug 8 — `default;`.** `parse_case_body` does `let _ = self.eat_sym(":")`, so
the AST does not record whether the source wrote the colon, and `case_labels`
printed `default:` unconditionally — inventing a token. Since `CaseItem.span`
starts at the `default` keyword, `default_has_colon` reads the byte after it
(through the same `skip_trivia`) and prints what was written. With a null body
the `;` hugs the keyword, because `stmt_as_body` would otherwise lay the `;`
out as a body and produce `default ;`. `default: ;` is unchanged.
**`verify.rs` is untouched** — `git diff` on it is empty. Per `topo.md` §2.1's
standing template I added the rejection tests anyway: four crafted (input,
corrupted output) pairs asserting the net still refuses the comment merged into
`else if`, the comment moved across the `)`, `default;` → `default: ;` and its
mirror `default: ;` → `default;`.
**Before / after on the real OpenTitan checkout** (3,943 files, `--no-cache
--check`, nothing ever written — `git status` in the corpus shows only the
pre-existing `hw/ip/aes/dv/tb/tb.sv` modification `syntax_coverage.md` already
records):
| | before | after |
|---|---|---|
| total failures (exit 2) | 151 | 140 |
| `verification failed:` | 12 | **1** |
| `parse error:` / `lex error:` | 139 | 139 |
| crashes | 0 | 0 |
All 11 fixed files were additionally formatted twice through `--stdout` and the
two passes compared byte-for-byte: **idempotent**, and every checkout file's
`md5` is unchanged. Pinned 820-file corpus: **813 passing** (baseline 813),
zero verification errors, zero crashes — no regression.
**The 12th file, and why it is not mine to fix.**
`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` had *two* bucket-2 bugs; fixing the
first (the `end // addr_phase_write` / `else if` merge at line 643) uncovered a
second at line 1254 that is not a formatter layout bug at all. The comment
there is written after `if (` and the condition starts with a call, so
`Parser::take_before_open` — which drains the whole pending queue — hands it to
`CallComments::before_open`, and the formatter faithfully prints it between the
callee and its `(`. `header_parens` never sees it. Hoisting it back out of the
expression past the `!` would need a suppression cutoff threaded through every
`expr` call; the parser fix is one span check. Filed as an open handshake
(above) with the exact patch, out of Lane B's file set, and pinned as a clean
refusal by a test. Also confirmed the same parser bug bites
`return // c` ⏎ `g();`, which is a second, independent symptom.
**Deviation from the brief**: 11 of 12 files, not 12, for the reason above.
Nothing was worked around and no corruption ships — the 12th file is still
refused and left byte-identical, which is the correct behavior until the parser
lands its fix.
**Format-cache note for the lead**: formatter output changed, so the workspace
version must be bumped at release (`topo.md` §2.3). Not bumped here.
## QA log
### 2026-08-19 — QA agent
@@ -485,8 +710,187 @@ compliance (no unwrap/expect/panic in library paths, no new deps, no
un-explained `#[allow]`, TODO.md/README.md/`lucisv` untouched) all confirmed
by direct inspection, not just by trusting the work log's claims.
### 2026-08-29 — QA agent (Lane B, testbench-syntax wave)
**Scope**: round 2 only — the three bucket-2 fixes (bug 6 `end // c` + `else`,
bug 7 `header_parens`, bug 8 `default;`) — with the adversarial charter aimed
squarely at a dropped/merged comment, an invented/moved token, or a fix that
only works on the corpus shapes. Built a `--no-cache --stdout`/`--check`
attack harness (pass1 → pass2 byte comparison for idempotency) and ran ~30
hand-crafted `.sv` files beyond the committed cases, then reproduced every
number in the work log independently against the real checkouts.
**Tool chain** (workspace root, after adding the two regression tests below):
`cargo fmt --check` clean; `cargo clippy --all-targets` silent, no new
`#[allow]`; `cargo test --workspace` green — `vlog_formatter`'s
`verification.rs` at 119/119 (118 + 1 new), `cases.rs` 1/1 (672 total cases
across all `.cases` files, `grep -c '#SKIP'` zero everywhere). Confirmed
`git diff --stat` on `crates/vlog_parser`, `crates/vlog_semantic`,
`crates/vlog_formatter/src/verify.rs` is empty — the "verify.rs untouched"
claim holds.
**Shape-A attacks (`end // c` / `else`)** — 5 crafted files: nested three-deep
if-else-if chain with every `end` individually commented (correct, stable);
the comment text containing the literal word "else" (correct, not
mistaken for structure); a CRLF-terminated file with the same shape
(correct); a pure block comment before `else` (still cuddles, as designed).
**One real gap found** (below) with a mixed block+line trailing comment.
**Shape-B attacks (`header_parens`)** — 9 crafted files hitting the source
scan directly: a `)` inside a string literal in the condition
(`s == ")"`), a `)` inside a nested paren sub-expression, a `)` spelled
inside a block comment (`/* looks like ) but is not */`), comments on both
sides of the `cond.span.start` split simultaneously, a condition that is
itself a `Paren` (double parens), `case`/`while`/`repeat`/`wait` each with
both-sided comments, and a case with two commented items after the header to
attack the skip-count plumbing. **All format correctly, keep every comment
in its original stream position, and are idempotent — no corruption, no
double-print, no drop.** Also re-confirmed the two documented refusal
boundaries directly (not just via `cargo test`): a comment before the
statement keyword's `(` (`if /* c */ (a)`) refuses cleanly (`token stream
diverges ... input has comment ... output has symbol "("`), and a comment
before a call in the condition refuses cleanly, matching the Handshakes
description exactly.
**Shape-C attacks (`default`)** — 9 crafted files: `default ;` (extra space)
normalizes to `default;`; `default: ;` unchanged; `default begin end` /
`default: begin end` both correct with the colon exactly as written;
`default y = 9;` (no colon, non-null body — a shape not explicitly named in
the work log but legal per the same IEEE grammar) correctly keeps the colon
off; two `default`s in one `case` (illegal but tolerated) round-trips both
correctly; `default /* c */: y = 9;` (comment between keyword and colon)
refuses cleanly rather than dropping or moving the comment. **One
non-blocking style nit found** (below): a trailing comment on `default;`
breaks the hug. `default;` inside a `generate case` without `begin`/`end`
hits a **pre-existing parser error** ("expected item"), confirmed unrelated
— `default begin : gd end` in the same position parses and formats fine, so
this is generate-case's existing null-body restriction, not a regression
from this round.
**Refusal-pin sabotage check**: confirmed by inspection that `StmtKind::For`
and `StmtKind::DoWhile` were not touched by the diff at all (no
`header_parens` call added), so their pinned refusal test is exercising the
same pre-existing, unmodified comment-position divergence check from round
1 — not a vacuous pass against dead code.
**Masked-corruption template**: all four crafted pairs genuinely attack the
paths this round changed (else-swallow, comment-across-`)`, colon invented,
colon dropped) rather than generic corruptions; re-ran them independently
via `cargo test -p vlog_formatter the_bucket_two_corruptions_are_still_rejected`.
**Numbers reproduced independently**, all against the live checkouts, all
read-only (`--check`/`--stdout` only):
- OpenTitan (`/Users/guoliangchen/repo/opentitan` @ `0098135264`, the same
pre-existing `hw/ip/aes/dv/tb/tb.sv` local edit `syntax_coverage.md`
records, nothing else dirty): `lucisv --no-cache --check .` →
**exactly 1** `verification failed:` (`hw/ip/keymgr/dv/env/
keymgr_scoreboard.sv:1254`, byte-identical message to the Handshakes
quote). Total failure count differs slightly from the work log's 140
(146 here) — attributable to `.gitignore`/vendor-tree walk differences
between sweeps, not to this round; the load-bearing number (verification
failures) matches exactly.
- Grepped the whole checkout for the three trigger shapes independently of
the work log's file list (`end\s*//.*\n\s*else`, `(if|while|repeat|wait|
case)\s*\(\s*//`, `^\s*default\s*;`) and got **exactly 12** candidate
files. Ran each through format+idempotency: **10 format cleanly and are
pass1==pass2 idempotent**, `keymgr_scoreboard.sv` is the documented
refusal, and one grep hit (`spi_device_scoreboard.sv`) fails on an
unrelated pre-existing macro-expansion parse error
(`` `CREATE_TPM_CASE_STMT ``) before the formatter ever reaches the
bucket-2 shape — confirms "11 of 12" exactly, with the 12th grep hit
being a false positive from the search pattern, not a second bug.
- Corpus gate: fetched `tools/corpus_fetch.sh`'s four pinned repos (820
files: 131 + 613 + 35 + 41, matches exactly) and ran `scripts/score.sh`:
`{"passing":813,"total":820,...}` — the exact baseline, zero
`verification failed:` entries in `.score-results.tsv` (the 7 failures
are all pre-existing parse/lex errors, none in the `other` bucket is a
verification error).
**Findings**
*Should-fix*: none. No hard-invariant violation found in either crafted
attacks or the real checkouts.
*Nit / informational* (both non-blocking — the safety net holds in both
cases; regression tests added for both):
1. **`trailing_ends_line` (`format.rs`, the `Some(tr)` arm) checks whether
the *merged* trailing text starts with `//`, not whether it ends in a
line comment.** `Meta.trailing` merges several trailing comments into one
string (see `ast.rs:92-96`); a line comment must physically be last in
any such merge (nothing can follow `//` on the same source line), so the
correct test is "does the merge end in one", not "does it start with
one". For `end /* a */ // b` the merged text is `"/* a */ // b"`, which
does not start with `//`, so `trailing_ends_line` returns `false` and
`then_is_block` stays `true` — the `else` still tries to cuddle, exactly
reproducing the bug this round fixes, on the one merge shape the fix's
condition doesn't cover. **Not a corruption**: `verify.rs` catches it on
reparse (the output's one merged comment doesn't match the input's two)
and the file is refused, byte-identical, same as it was before this
round (this exact shape always cuddled unconditionally pre-fix too, so
it is not a regression — it is the fix's coverage boundary, undocumented
until now). Pinned as a refusal, not fixed — narrowing `is_line_comment`
into a "starts vs. ends" split is a real design decision (the merge
already lost the individual comments' boundaries) that belongs to
whoever next touches this heuristic, not a QA-scope patch. Regression
test: `crates/vlog_formatter/tests/verification.rs::
a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused`.
2. **A trailing comment on a colon-less `default;` breaks the hug and
inserts a space**: `default; // fallback` formats to `default ; //
fallback`. Root cause: `case_item`'s shortcut requires `is_bare(&item.
stmt.meta)`, and a comment trailing the null statement lands in `item.
stmt.meta.trailing`, which is not bare, so the shortcut is skipped and
the general `case_labels` + `stmt_as_body` path inserts its usual
`Doc::Line` between the label and the body. **Not a correctness issue**:
the comment is kept verbatim in its original stream position, `verify.rs`
accepts it (whitespace is not part of the token stream), and it is
idempotent. It does contradict the round's stated design point
("`default;`, not `default ;`") for this one sub-case. Pinned with an
exact-output case rather than fixed, since teaching the shortcut to also
fire with a bare-except-trailing-comment statement (and then print that
comment itself) is a small but real behavior change outside a
verify-and-report QA pass. Regression case:
`crates/vlog_formatter/tests/cases/statements.cases`, "a trailing
comment on a colon-less `default;` keeps the comment and the missing
colon".
**Regression tests added this pass** (2 files, both green):
- `crates/vlog_formatter/tests/verification.rs`:
`a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused`
(finding 1 above, pins the safe refusal).
- `crates/vlog_formatter/tests/cases/statements.cases`: one new case (finding
2 above, pins the current — correct but slightly odd — output).
**Overall verdict**: **SHIP.** Both bucket-2 fixes claimed (11/12 files,
verification failures 12→1) are reproduced exactly against the live
OpenTitan checkout and the pinned 813/820 corpus, `verify.rs` is
byte-for-byte untouched, and every crafted adversarial input across all
three shapes either formats correctly with every comment preserved in place
and idempotently, or is safely refused with the file left untouched — never
corrupted. The two findings are both informational nits with permanent
regression tests now guarding them; neither is a hard-invariant violation
and neither blocks merge.
## Review
**2026-08-29 — lead, round 2 (bucket-2 round-trip bugs).** Reviewed
after QA's SHIP; gates re-run on the worktree (fmt clean, formatter
suite green). Three shapes, three root causes, all fixed where the bug
lived — format.rs — with verify.rs, the parser and the semantics
provably untouched, and the standing template honored: rejection tests
added anyway, four of them attacking the fixed paths specifically.
The dev's best decision was the one it did NOT make: the twelfth file
is a parser bug (take_before_open draining the pending-comment queue),
and it was filed as a specified Handshake instead of a cross-lane
edit — the directive round is delivering it. QA's two informational
pins are accepted as filed: the block-plus-line trailing-comment
boundary stays a clean refusal (the safety net's job, done), and the
`default ; // comment` stray space is a style wrinkle, not a token
change. 11 of 12 files independently confirmed on the real checkout,
corpus exactly at baseline. Formatter output changed, so the release
bumps the workspace version per the format-cache rule — flagged and
carried. Accepted; merged by the lead.
**2026-08-19 — lead. Verdict: accepted and committed as-is; no lead fixes
needed.**