Add error-recovery and format-fences (jointly: entangled in format.rs)

error-recovery (vlog_parser): parse_source_tolerant never fails —
errors become positioned ParseDiagnostics and ItemKind::Error /
StmtKind::Error leaves (raw text + span, nesting invariant intact),
with recovery at documented sync tokens, bracket-balanced skipping,
and stray-closer collapse. Strict parse_source is byte-identical in
behavior (shared grammar, tolerant flag). Guarantees tested:
tolerant==strict on 500 valid sources; depth/links budgets neither
reset nor leak across recovery (mutation-tested); no panic across
27k+ truncation cuts, every single-char fixture deletion, 1MB of
semicolons (500k recoveries, 344ms). The future LSP parses mid-edit
code; the formatter still refuses on the first error.

format-fences (vlog_formatter): // verilog_format: off|on and
// vfmt: off|on emit fenced item ranges as exact source bytes via
spans (Doc::Verbatim), Verible-style item-level regions per scope,
unmatched off to end of scope, byte-exact including indentation and
idempotent at every join (24 adversarial probes). ~2000 corpus fence
injections: zero region byte changes, zero new verification
failures. verify.rs untouched; with no fences output is
byte-identical (corpus TSV md5 unchanged).

Also surfaced and queued in TODO: comment-in-list refusals
(112/1868 injection trials) and the double-blank leading-comment
nit — the next comments round.

Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{error-recovery,format-fences}/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-19 05:23:05 -07:00
1 parent 901a78ccb2
commit 02f68655b5
16 files changed
+3069 -70

No files matched your search

+522
View File
@@ -0,0 +1,522 @@
# error-recovery
## Goal
A formatter may refuse broken input; a language server may not — an editor
buffer is mid-edit most of the time, and "no symbols, no highlighting, no
diagnostics until the file parses" is exactly the experience TODO.md §6 exists
to avoid. This feature adds a second entry point to `vlog_parser`,
`parse_source_tolerant(src) -> (SourceFile, Vec<ParseDiagnostic>)`, that never
fails: where the grammar gives up it records a diagnostic, skips to a sync
token, wraps the skipped text in an `ItemKind::Error` / `StmtKind::Error` leaf
and carries on. The strict `parse_source` keeps its exact behavior — the two
entry points share the grammar code, not a copy of it, so there is no second
parser to keep in sync. On a file that parses cleanly the tolerant tree is
*the same tree* and the diagnostic list is empty, which is what lets the
formatter keep its "zero errors or nothing" contract unchanged.
## The recovery strategy
Deliberately one paragraph long, because a recovery strategy nobody can
predict is worse than a crude one everybody can:
1. **Recovery happens only in item and statement *lists*.** Those are the
places a parse can resume from: file scope, module and package bodies,
generate regions and generate blocks, `begin`/`end` and `fork`/`join`
bodies, function and task bodies, and a case item's statement. An error
deeper inside a construct (a for-header, a port list, a case label) is not
caught where it happens — it propagates out to the nearest enclosing list,
and that whole item or statement becomes one error node. Nothing else in
the grammar knows recovery exists.
2. **Record, then skip.** The diagnostic is the `ParseError` the strict parser
would have returned — same message, same line:col — plus the byte span of
the token the parser gave up on.
3. **Skip to a sync token.** From the failure point, skip forward until one
of:
- **`;`** — consumed; it terminated the broken construct.
- a **sync-stop keyword** — *not* consumed, because the construct it closes
or opens is somebody else's to parse (see the table below).
- **end of file**.
Brackets opened while skipping are skipped as a unit, so the `;`s inside a
broken `for (i = 0; ...)` header do not end the skip early.
4. **Wrap.** The text from where the failed construct started through the
sync point becomes an `ItemKind::Error(RawText)` or
`StmtKind::Error(RawText)` — a verbatim AST leaf exactly like `MacroCall`
and `Directive` already are, carrying `text`, `col` and `span`.
5. **Always advance.** If the failed construct consumed no tokens at all, the
skip takes one anyway, so an enclosing loop can never spin.
### The sync tokens, and why each one
| token | consumed? | why |
|---|---|---|
| `;` | yes | The statement/declaration terminator: the one token that reliably ends a construct in this grammar, and the only one worth *eating* — the broken text ended there. |
| `end`, `endmodule`, `endpackage`, `endgenerate`, `endfunction`, `endtask`, `endcase`, `join`, `join_any`, `join_none` | no | Each closes a construct whose parse loop is still on the stack. Consuming one would leave that construct unclosed and cascade the damage outward — this is exactly what "an error inside a generate block must not eat the `endgenerate`" means. `endcase` and the `join`s are in the set for the same reason the ones the task named are, and are cheap to add. |
| `module`, `macromodule`, `package` | no | These can only *begin* a construct at file scope. Without them, garbage written between two modules skips forward looking for a `;` and swallows the second module's header. With them, garbage between two modules costs exactly one error node. |
| end of file | — | Nothing left to sync to. |
| a closing `)`/`]`/`}` **with a matching open in the skipped range** | yes | Part of the garbage being skipped. |
| a closing `)`/`]`/`}` **with nothing open** | yes | Also skipped. Recovery only ever runs in an item or statement list, and no such list sits inside brackets, so a stray `)` belongs to the broken expression, not to a caller. Treating it as a stop point was tried first and made every leftover `)` of `assign x = (((1 + )));` its own error node — 26 diagnostics for one typo. |
### Unclosed constructs
The sync-token rules alone would turn a file whose `endmodule` is not typed
yet into one file-sized error node — the single most common mid-edit state,
and the one where an LSP most needs the tree. So two small companions:
- In tolerant mode a body loop also ends at any sync stop, not just at its own
closing keyword. An unclosed `begin` therefore ends where the next construct
begins instead of eating the rest of the file.
- `expect_closer` (used for every `end*`/`join` keyword) records
``expected `end` `` as a diagnostic instead of failing, and treats the
construct as closed where the parser stopped.
The result: `module m; initial begin x = 1; endmodule` yields one diagnostic
(missing `end`), a module with its `initial` block, and the block with its
statement — no error node at all.
### A file that is all garbage
…becomes one error item covering it. So does a file the *lexer* rejects (see
Assumptions), which is the only case where the tolerant tree carries no
structure at all.
## Assumptions
- **Recovery is a parse-level mechanism; the lexer stays all-or-nothing.** An
unterminated string or block comment has no sensible resumption point
(everything after it is inside the string), so `parse_source_tolerant` turns
a `LexError` into one diagnostic plus one file-wide error item rather than
guessing. Making the lexer tolerant is a separate, larger decision;
truncated files hit this path often enough that it is worth revisiting if
the LSP finds it too coarse.
- **A missing `;` costs the construct after it.** The sync point is the next
`;`, not the next line, so `wire a` (no semicolon) followed by `wire b;`
produces one error node covering both. Line-based heuristics ("resync at a
token that starts a line") would do better on this one shape and worse on
wrapped constructs; the boring rule is the one that is predictable.
- **A broken construct can produce more than one diagnostic.** A half-typed
`for (i = 0; i < ; i = i + 1)` fails inside the header, resyncs at the `;`
*inside* the header, and reports again on the remains. Every extra
diagnostic is at a real position and the file still parses to the end; no
attempt is made to suppress cascades.
- **Comments attached to a construct that failed to parse are dropped from the
tolerant tree.** They were harvested into the failed node's `Meta` before
the error, and comments *inside* the skipped range survive only as bytes of
the error node's raw text. This does not weaken CLAUDE.md invariant #3:
that invariant is about what the *formatter* emits, and the formatter never
parses tolerantly (see Handshakes). An LSP consuming a broken buffer can
still reach every comment through the token stream.
- **Every successful item/statement parse consumes at least one token.** The
termination argument rests on it (with the always-advance rule covering the
failure side). It is true of every arm in the grammar today; a future arm
that could succeed on zero tokens would need the loops to guard against it.
- **`source` must be the exact text the tokens were lexed from.**
`parse_tolerant(tokens, source)` copies spans out of it; a mismatched string
would put wrong text in the error nodes. `parse_source_tolerant(src)` is the
entry point that cannot get this wrong, and is what callers should use.
## Handshakes
**Promised to `vlog_formatter` — the formatter must not format a file with
diagnostics, and this round did not change how it formats anything:**
- `format_source` still calls `vlog_parser::parse_source`, i.e. the strict
parser, which still fails on the **first** error and makes the CLI leave the
file untouched. Error nodes cannot appear in a tree the formatter builds.
- **Four lines were added to `format.rs` anyway, and they are the one thing
this feature could not do inside its own crate**: adding a variant to
`ItemKind`/`StmtKind` makes the formatter's exhaustive `match`es fail to
compile, so each got one arm (`ItemKind::Error(d) => self.raw_text(d)`, and
the statement twin) plus a comment saying it is unreachable from
`format_source`. Verbatim pass-through was chosen over emitting nothing so
that, if a future entry point ever did hand the formatter such a tree,
`verify.rs`'s token-equivalence check would see the tokens rather than
silently lose them. No behavior change: the full `.cases`, fixture,
snapshot and idempotency suite is green with zero churn.
- **`verify.rs` is untouched.** No normalization was added, broadened or
weakened, so CLAUDE.md hard invariant #4 does not apply to this round.
- When the LSP lands, its contract with the formatter is: *format only when
the diagnostic list is empty*; otherwise publish the diagnostics and serve
the partial tree for everything else (symbols, highlighting, hover).
**Consumed from `docs/features/recursion-limit/README.md` (the handshake that
was written for this feature):** recovery **must not reset `depth` or
`links`**. It does not touch either. It cannot need to: both are released by
the gated frames themselves on every path out, including error paths
(`leave()` after the inner call, `self.links = outer_links` after it), so by
the time an error reaches the list loop that recovers, both counters are back
at exactly that loop's level. Recovery resumes there. Two tests pin it — one
white-box (both counters are 0 after a tolerant parse of a broken file), one
black-box in each direction: 100 broken 25-deep expressions in a row produce
100 diagnostics and never a `nesting too deep` (no leak), and a broken
statement 55 blocks deep followed by 20 more blocks *does* produce one (no
reset). Both were mutation-tested by injecting `self.depth = 0` and
`self.depth += 1` into `recover`; each mutation fails a test.
**Consumed from `docs/features/spans/README.md`:** error nodes are ordinary
AST leaves under the existing span convention — span = code extent, comments
excluded, so a child's span nests inside its parent's. `tests/spans.rs`'s
exhaustive nesting walker now runs over recovered trees too
(`recovered_error_nodes_nest_inside_their_parent`), which is deliberate reuse:
a new node shape cannot quietly skip the invariant. An error node's `text` is
asserted to be its own source slice, so `source[span] == text` holds for the
new leaf as it does for `RawText` elsewhere.
**Requested of nobody.** No other module needs a change.
## API
```rust
// vlog_parser
pub fn parse_source_tolerant(source: &str) -> (ast::SourceFile, Vec<ParseDiagnostic>);
pub fn parse_tolerant(tokens: Vec<Token>, source: &str) -> (SourceFile, Vec<ParseDiagnostic>);
pub struct ParseDiagnostic {
pub message: String, // exactly what ParseError would have said
pub line: u32, // 1-based, as on ParseError
pub col: u32, // 1-based, in bytes
pub span: TextRange, // extent of the token the parser gave up on
}
```
`ParseDiagnostic` displays as `line:col: message`, like `ParseError`. Its
`span` and its `line:col` are two views of *the same token* — asserted, so a
terminal that prints the position and an editor that highlights the range
agree. The extent that was *skipped* is not on the diagnostic; it is the error
node's span in the tree, which is where a consumer that wants it should look.
`parse(tokens)` and `parse_source(source)` are unchanged, including their
signatures.
## Status / TODO
- [x] `parse_tolerant` / `parse_source_tolerant`; `ParseDiagnostic` with
message, line, col and span.
- [x] `ItemKind::Error(RawText)` / `StmtKind::Error(RawText)` leaves carrying
the skipped text and its span.
- [x] Sync-token set documented above; skipping balances brackets.
- [x] Recovery at all nine item/statement list sites; nothing else in the
grammar changed shape.
- [x] Unclosed constructs: tolerant body-loop exit + `expect_closer`.
- [x] Lex errors → one diagnostic + one file-wide error item.
- [x] Guarantee (a): tolerant == strict on 500 valid sources (fixtures + every
`.cases` input *and* expected output), asserted on the `Debug` shape of
the whole tree, with zero diagnostics.
- [x] Guarantee (b): diagnostics inside the file, positions consistent with
spans, error-node text == its source slice, error nodes nest (in
`tests/spans.rs`, via the existing exhaustive walker).
- [x] Guarantee (c): budgets neither leak nor reset; mutation-tested.
- [x] Guarantee (d): 5299 byte-prefix truncations of the fixtures, ~11k
token-boundary truncations of the case-table sources (the exact count
grows with the case table; QA re-measured 11570), and every
single-character deletion of every fixture — no panic, no hang, all
invariants hold on every one.
- [x] Mid-edit shapes tested by name: missing `;`, unclosed `begin`, unclosed
`module`, `wire [7:`, `sub u0 (.a(`, garbage between two modules (six
kinds), error inside a generate block, error inside a function body,
all-garbage file, stray `endmodule`, lex error, empty file.
- [x] `cargo test --workspace` green, `cargo clippy -p vlog_parser
--all-targets` silent, `cargo fmt --check` clean.
- [x] TODO.md §6 error-tolerant checkbox.
- [ ] **Not done, deliberately:** a tolerant *lexer*. See Assumptions.
- [ ] **Not done:** cascade suppression (a "don't report twice within N
tokens" rule). Wait for the LSP to show whether the cascades are
actually noisy in practice.
- [ ] **Not done:** recovery inside headers and lists (port lists, parameter
lists, for-headers). Those need per-construct resync points, and the
first consumer should say whether the coarse-grained answer is enough.
Note (QA finding, lead-confirmed): today a broken *header* doesn't just
go unrecovered — it distorts the surrounding tree (the module body
re-parses as file-scope items and the orphaned `endmodule` becomes a
second error item, 2 diagnostics for one typo). The LSP consumer
should expect that shape until header recovery lands.
## Work log
### 2026-08-19 — dev agent
- Read CLAUDE.md, README.md, TODO.md §6, `docs/features/spans/README.md` and
the recursion-limit Handshakes before touching code. Baseline:
`cargo test --workspace` **161 passed**, clippy silent, fmt clean.
- **Chose "recover in list loops only".** The alternative — recovery points
inside every construct — multiplies the number of places that can invent a
resync rule, and each one is a new way for the two entry points to diverge.
One `item_or_recover` / `stmt_or_recover` pair, called from the nine loops
that build a `Vec<Item>`/`Vec<Stmt>`, keeps the grammar code shared
literally rather than by convention: every other function is untouched and
cannot tell which mode it is running in.
- **`tolerant` is a flag on `Parser`, not a second parser.** `parse` and
`parse_tolerant` differ by that flag and by the `source` slice recovery
copies error-node text from. Strict mode passes `""` because it never
recovers, which is stated at the field.
- **Two changes to the strict path's *shape*, none to its behavior**: body
loop conditions moved into `at_body_end(kw)` (identical when `tolerant` is
false) and `expect_kw("end…")` became `expect_closer("end…")` (identical
error, identical message, when `tolerant` is false). The formatter's whole
suite, including snapshots and `.cases`, is green with zero churn, and a
unit test asserts strict parsing still stops at the *first* error with the
same message tolerant mode files first.
- **The stray-closing-bracket rule was wrong on the first try, and the tests
caught it.** `)` with nothing open originally *stopped* the skip, on the
theory that it belonged to an enclosing construct. It does not — recovery
never runs inside brackets — and the price was one error node per leftover
`)`: the 100-broken-expressions budget test reported 2600 diagnostics
instead of 100, and the depth-limit test 32 instead of 1. Skipping them
fixed both and is what the table above now documents.
- **Unclosed constructs got two companions on purpose.** With sync tokens
alone, `module m; wire a;` (no `endmodule` yet) is one file-sized error node
— i.e. the tolerant parser would be useless in the state an editor is in
most often. The tolerant body-loop exit plus `expect_closer` cost about
fifteen lines and turn that case into "one diagnostic, whole tree intact".
- **Comments attached to a failed construct are dropped from the tree** — they
went into the failed node's `Meta` before the error was raised, and pulling
them back out would mean restructuring where `take_meta` is called. Wrote it
down in Assumptions instead of hiding it; it is sound only because the
formatter never parses tolerantly, which is the handshake above.
- **Reused `tests/spans.rs`'s exhaustive nesting walker** for the recovered
trees rather than writing a second one. It is compiler-checked exhaustive,
so the new leaves had to be handled there anyway; running it on broken
sources costs ten lines and makes the nesting guarantee total.
- **Mutation-tested the budget claim rather than asserting it from the code**:
`self.depth = 0` in `recover` fails both budget tests, `self.depth += 1`
fails the leak test. Reverted; `grep MUTATION` is 0.
- **Probed behavior with a throwaway `examples/probe.rs`** (mid-edit shapes,
then every byte prefix of every fixture) before writing any assertions, so
the tests encode measured behavior rather than hoped-for behavior. The
example was deleted; it is not part of the diff.
- Did not touch `verify.rs`, `tools/`, `corpus/`, or `crates/vfmt`. Did not
run `git commit`/`git push`.
- **Concurrency note:** another agent's format-off-fence work
(`crates/vlog_formatter/src/fence.rs`, `doc.rs`, `format.rs`, `printer.rs`,
`docs/features/format-fences/`) is live in the same working tree. My only
edit inside that crate is the four lines described in Handshakes, made with
exact-string edits so their in-progress work was not disturbed; their diff
in `format.rs` is untouched around them. One clippy warning currently comes
from their `fence.rs:58` (`map_or` → `is_none_or`) — theirs to fix, left
alone; `cargo clippy -p vlog_parser --all-targets` is silent.
**Results:** `cargo test --workspace` **188 passed, 0 failed** (up from 161:
+2 `vlog_parser` unit tests, +19 in the new `tests/error_recovery.rs`, +1 in
`tests/spans.rs`; the rest is the concurrent fence work). `cargo clippy -p
vlog_parser --all-targets` silent. `cargo fmt --all --check` clean. Files
touched: `crates/vlog_parser/src/{parser,ast,lib}.rs`,
`crates/vlog_parser/tests/error_recovery.rs` (new),
`crates/vlog_parser/tests/spans.rs` (one test + two match arms),
`crates/vlog_formatter/src/format.rs` (four lines, see Handshakes), `TODO.md`
(§6 checkbox), this README.
## QA log
### 2026-08-19 — QA agent
Read CLAUDE.md, this README, the diffs in `crates/vlog_parser/src/{lib,ast,parser}.rs`,
`crates/vlog_parser/tests/{error_recovery.rs,spans.rs}`, and the four added
`format.rs` match arms before testing. Scope: `-p vlog_parser`; did not touch
the concurrent format-fences work. Verdict: **no BLOCKING findings.** All
claims verified, two LOW-severity documentation/behavior notes below.
**Tool results (exact):**
- `cargo test -p vlog_parser`: unit 49 passed, `error_recovery.rs` 19 passed,
`spans.rs` 12 passed — 80/80, 0 failed.
- `cargo clippy -p vlog_parser --all-targets`: silent, 0 warnings.
- `cargo fmt --check -p vlog_parser`: clean.
- `cargo test --workspace`: green, 194 passed total (up from the dev's
logged 188 — the delta is the concurrent format-fences suite, confirmed by
reading its test file names, not this feature).
- `cargo test -p vlog_formatter`: 55/55 green (8+1+4+6+2+32+0 doctests) — the
strict-path/snapshot/`.cases`/idempotency suite has zero churn from this
feature, confirming the Handshakes claim.
**Claim 1 (parse/parse_source unchanged, one Parser + tolerant flag):** PASS.
Traced the code: `parse`/`parse_source` build `Parser::new(tokens, "", false)`;
every recovery call site (`item_or_recover`/`stmt_or_recover`) only diverges
from the strict `Err` propagation when `self.tolerant` is true (`Err(e) if
self.tolerant => …`, `other => other`), so strict mode is byte-identical to
before. `strict_parsing_still_stops_at_the_first_error` (parser.rs) and
`format_source`'s green suite both confirm no observable change.
**Claim 2 (sync tokens, bracket balancing, stray closers, unclosed
constructs):** PASS on every sub-claim, confirmed both by the dev's own
tests and independently in a scratch harness
(`/private/tmp/…/scratchpad/qa_probe`, deleted nothing in-repo):
- `module`/`endmodule`/`endgenerate`/`join*` etc. correctly left unconsumed
even when the literal text "module" appears inside a *string* or a
*comment* inside a broken construct — the lexer tags those as
`String`/`Comment` tokens, not `Keyword`, so `at_sync_stop` never
misfires on them. Verified with three adversarial sources (`"module
fake"` in a string, `// … module …` in a line comment, `/* module … */`
in a block comment) — each produced exactly 1 diagnostic, no false stop.
- Stray closing brackets do not cascade: 50 consecutive stray `)` between
two modules collapsed into **one** error node / one diagnostic, not 50 —
matches the work log's account of the fix.
- Unclosed constructs: `module m; initial begin x=1; endmodule` shape
(dev's own `an_unclosed_begin_keeps_the_statements_inside_it`) gives
exactly 1 diagnostic (`expected \`end\``), both statements intact, zero
error nodes. Confirmed.
- Bracket-balanced skipping confirmed at 10 levels of nested `generate`/`if`
with a broken `wire ;` at the bottom: 1 diagnostic, the error node sits at
the correct innermost level, and the outer 10 levels of structure plus the
module's trailing sibling item are all intact (probe5/probe2 output).
**Claim 3a (tolerant == strict on ≥500 valid sources):** PASS. Dev's test
reports 550 valid sources (fixtures + `.cases` inputs/outputs), all
Debug-equal, all zero-diagnostic. Independently re-verified with my own
extractor (not reusing `tests/error_recovery.rs`'s helper) over 30
pseudo-randomly sampled `.cases` inputs: 30/30 consistent (Debug-equal tree,
empty diagnostics).
**Claim 3b (spans, char-boundary safety, LineIndex agreement, nesting):**
PASS. Independently re-checked char-boundary-safety and
`LineIndex::offset` agreement on a case the dev's `BROKEN` list doesn't
include — a BOM-prefixed file (`\u{FEFF}module m; …`), both well-formed and
broken — no panic, diagnostic span is in-file and char-boundary-safe, and
`LineIndex::offset(line, col) == span.start` held. `spans.rs`'s exhaustive
walker running over `recovered_error_nodes_nest_inside_their_parent`
confirmed as claimed.
**Claim 3c (depth/links neither leak nor reset):** PASS, and independently
stress-tested beyond the dev's fixed-shape tests: 50 valid expression chains
each at `MAX_CHAIN_LENGTH - 1` (255 links), each interleaved with a broken
statement forcing a recovery in between — 50 diagnostics (one per broken
statement), **zero** `chain too long` / `nesting too deep` anywhere (no
leak across the 50 recoveries), and all 100 items survived as siblings of
the module. Complement: one expression at 306 links (over the 256 limit)
between two good statements produced **exactly one** diagnostic
(`expression chain too long (limit 256)`), recovered as a single clean
error node, with both the preceding and following good statements intact
in the tree — the "restore discipline" claim holds in both directions.
**Claim 3d (no panic, extended):** PASS. Re-ran the dev's approach and then
extended it: independently re-implemented the `.cases`-file input extractor
(not reusing the dev's) and byte-truncated (not just token-boundary) every
`.cases` **input** section at every char-boundary offset — 21,988 cuts,
well under the 3-minute time-box (66 ms), zero panics, all spans in-file and
char-boundary-safe. A second independent pass did token-boundary truncation
(5,510 cuts) with the same result. Also fuzzed: `;;;;` alone (2 diagnostics,
each swallowing two `;`s per the always-advance rule — expected, not a
bug), a 1 MB file of only `;` (500,000 diagnostics/items, 344 ms release
build, no hang), an unterminated string at EOF and an unterminated block
comment (both correctly hit the lex-error path: 1 diagnostic, 1 file-wide
error item), and a BOM'd file (no panic; see note below). None panicked.
**Minor discrepancy in claim 3d's exact number:** the README's Status/TODO
line says "10756 token-boundary truncations of the case-table sources";
re-running the *exact same* dev test today (`cargo test -p vlog_parser
--test error_recovery -- --nocapture truncating_a_case_table_source_never_panics`)
prints **11570**. The byte-prefix number (5299) still matches exactly. The
drift is because the case-table corpus has grown since that number was
written (concurrent `.cases` files added by other in-flight feature work in
this same tree), not a functional problem — but a number stated this
precisely will keep silently rotting as the corpus grows. Suggest wording
it approximately (or dropping the exact count) rather than re-chasing it
every time a `.cases` file is added.
**Claim 4 (lex errors are all-or-nothing):** PASS. Confirmed via dev tests
plus independently on an unterminated string, an unterminated block
comment, and a BOM'd file — each produces exactly one diagnostic and one
file-wide `ItemKind::Error` covering the whole source, never a partial tree.
**Claim 5 (tool results, unreachable format.rs arms):** PASS. Tool results
above. Confirmed the two added `format.rs` arms
(`ItemKind::Error(d) => self.raw_text(d)` at line 493,
`StmtKind::Error(d) => self.raw_text(d)` at line 1565) are exact-string
minimal (one line of code each, plus a comment) and genuinely unreachable
from `format_source`: `format_once` calls `vlog_parser::parse_source`,
which is strict (`tolerant: false`), and `ItemKind::Error`/`StmtKind::Error`
are constructed *only* inside `item_or_recover`/`stmt_or_recover`'s
`Err(e) if self.tolerant` arm — a path strict parsing never takes. `git
diff --stat crates/vlog_formatter/src/verify.rs` is empty, confirming
"`verify.rs` is untouched" (CLAUDE.md invariant #4 does not apply to this
round, as claimed).
**Finding — LOW, non-blocking (header/list recovery produces a garbage
tree, not a clean single failure):** the README's Status/TODO already
records header/port-list/for-header recovery as **not done**, and asked me
to check which of the two documented possibilities ("clean single failure"
vs. "garbage tree") actually happens. Answer: **garbage tree.** For
`module m #(parameter W = , parameter X = 4) (input a); wire ok;
endmodule`, the tree is *not* one error item — it's three top-level items:
one error item covering the header through its closing `;`, then `wire ok;`
re-parsed as an ordinary **top-level** `DataDecl` item (not inside any
module — semantically wrong shape for the tree), then a second, spurious
error item covering the orphaned `endmodule` keyword. That's 2 diagnostics
for one typo, and a module body statement now appears to live at file
scope. This doesn't break any stated guarantee (the module's body content
is still `src[span]`-correct in whichever node it ends up in, and nothing
panics), and it's explicitly flagged as a follow-up decision for "the first
consumer" in the TODO — but "not covered" undersells it: it's not just that
the header itself isn't recovered, the *tree shape after it* is
misleading. Recommend the Assumptions section say this explicitly (a header
failure produces extra, oddly-placed items/diagnostics, not just "one
failure covering the header") so a future LSP author isn't surprised.
Reproduction: see probe5 sources above; any of the four listed there
reproduces it.
**Finding — LOW, out of scope for this feature (BOM lex-error message is
mojibake, pre-existing):** a BOM-prefixed file (`\u{FEFF}module m; …`)
correctly takes the lex-error path (1 diagnostic, 1 file-wide error item,
no panic, span char-boundary-safe and in-file — all of this feature's
guarantees hold). But the message itself, `"unexpected character 'ï'"`, is
mojibake: it looks like the lexer is decoding a single byte of the BOM's
UTF-8 encoding rather than the codepoint. `crates/vlog_parser/src/lexer.rs`
is untouched by this diff (`git diff --stat` confirms), so this is
pre-existing and out of this feature's scope — flagging for whoever next
touches `lexer.rs`, since BOM'd files are a common artifact from
Windows/VS Code and will reach the LSP path this feature exists to serve.
**CLAUDE.md compliance:** public items documented (`ParseDiagnostic` and its
fields, `parse_tolerant`, `parse_source_tolerant`, `ItemKind::Error`,
`StmtKind::Error` all carry doc comments). No `unwrap()`/`expect()`/`panic!`
in library code paths — the three hits from `grep` are inside
`#[cfg(test)] mod tests`, which CLAUDE.md permits. README has all required
sections, current and honest (TODO.md §6 checkbox matches what's actually
shipped, non-goals — tolerant lexer, cascade suppression, header/list
recovery — are recorded). Did not edit the Review section.
**Not independently reproduced:** the mutation-testing claim in the
Handshakes section (`self.depth = 0` / `self.depth += 1` injected into
`recover`, each failing a test) — took it on the dev's word since
mutating shipped code to re-verify a already-passing regression class
was judged lower value than the adversarial probing above; the black-box
budget tests (3c) independently exercise the same invariant from the
outside and passed.
## Review
**2026-08-19 — lead. Verdict: accepted; commits jointly with
format-fences (the two features interlock in `format.rs` via the new
`Error` variants' match arms, so separate commits would not compile).**
The LSP's parser is now real: never fails, positioned diagnostics,
Error leaves that obey the span nesting invariant, and — the part that
took discipline — the strict path provably untouched (shared grammar
code with a flag, not a fork; byte-identical behavior traced by QA).
The evidence standard here was the best yet: truncation fuzz at byte
and token granularity (27k+ cuts, zero panics), budget guarantees
mutation-tested in both directions, and the stray-closer cascade bug
caught by the dev's own tests before QA ever saw it.
Points reviewed and accepted:
1. **Sync-token set**: consuming `;` but not the closers/openers is the
right asymmetry, and treating `module`/`package` as recovery
openers is what keeps garbage from swallowing the next module.
Bracket-balanced skipping (the `;`-inside-broken-for case) is the
subtle rule; it's tested.
2. **Lex errors stay all-or-nothing** — honest scoping; a tolerant
lexer is its own feature and the Assumption says so.
3. **The 4 exhaustive-match arms in format.rs** were structurally
unavoidable, exact-string minimal, and QA traced their
unreachability from `format_source`. Accepted as the one
cross-scope touch.
4. QA's low findings both addressed at review: the truncation count is
now stated approximately (it grows with the case table), and the
Assumptions now say plainly that a broken *header* distorts the
surrounding tree shape (2 diagnostics, body re-parsed at file
scope) — the LSP consumer must expect that until header recovery
lands. Cascade suppression and header recovery remain deliberate
non-goals awaiting a real consumer.
The BOM mojibake message QA noticed in passing is a lexer
message-quality nit; it can ride with the `@(* )` lexer item already
on TODO §1.
+566
View File
@@ -0,0 +1,566 @@
# format-fences
## Goal
Let an author switch the formatter off for a stretch of code with
`// verilog_format: off` … `// verilog_format: on` (Verible's spelling, plus a
short `// vfmt: off` / `// vfmt: on` alias) and get those bytes back exactly
as they were written. Hand-aligned lookup tables, generated blocks, and
column-aligned instance connections are the cases every RTL codebase has;
without an escape hatch they are the reason a formatter never gets adopted.
The region is emitted as a raw slice of the original source — the AST inside
it is never consulted — so "verbatim" is true by construction rather than by
careful re-printing. This is the first consumer of the byte spans landed by
`docs/features/spans/README.md`.
## Fence grammar
A fence is a **line comment** whose text, after stripping the leading `//` and
trimming whitespace on both sides, is *exactly* one of:
```
verilog_format: off vfmt: off
verilog_format: on vfmt: on
```
Consequences, all deliberate and all tested:
- `//verilog_format: off` (no space) and `// vfmt: on ` are fences —
the text is trimmed. `// verilog_format:off` is **not** (no space after the
colon; the match is exact, not fuzzy).
- **A fence with trailing text is not a fence.** `// vfmt: off (for now)`
formats as an ordinary comment. Rationale: the alternative — prefix
matching — silently turns `// vfmt: off-by-one bug here` into a formatting
switch, and a fence that fires by accident is worse than one that does not
fire at all. If the author wants a note, it goes on its own line.
- **Block comments are not fences.** `/* verilog_format: off */` is an
ordinary comment. Restricting fences to `//` keeps a fence a whole-line
thing and keeps the region boundaries at line granularity.
- **A fence must be a leading comment**, i.e. it must start a line (nothing
but whitespace, or another comment, before it on that line). A comment on
the same line as preceding *code* is attached to that code as *trailing*
trivia, and `Meta.trailing` is an `Option<String>` with no span — there is
nothing to splice from. So `wire a; // vfmt: off` is an ordinary comment.
See Handshakes for the parser change that would lift this.
- The alias and the long form are interchangeable: an `off` in either
spelling is closed by an `on` in either spelling.
## Semantics
Fences select whole **items** (module items, package items, top-level items),
Verible-style. Think of an item list as a flat stream of *units*: each item's
leading comments, then the item's own code (its `(* … *)` attributes and
trailing comment included), and finally the scope's dangling comments.
- A region **opens** at the first `off` fence in that stream and **closes**
at the first `on` fence after it. The emitted byte range runs from the
first byte of the `off` fence's line through the last byte of the `on`
fence — the fence comments themselves are part of the region.
- Everything in between — items, their comments, their attributes — is
skipped by the formatter and comes out of the source slice instead.
- **Indentation is preserved, including on the region's first line.** The
region starts at the *start of the line* the `off` fence sits on (when only
whitespace precedes it there), and the printer emits the slice at column 0,
so every line of the region is byte-identical to the input. Normal
formatting, at the enclosing indent level, resumes on the line after the
region.
- **A second `off` inside an open region is a no-op**, as is an `on` with no
open `off`; both are just bytes inside the region, or an ordinary comment.
Fences do not nest and do not count.
- **An unmatched `off` runs to the end of its scope** — the last byte of the
containing item list, which is the end of the last item (its same-line
trailing comment included) or of the last dangling comment, whichever comes
last. At file scope that is the last byte of content in the file. It does
**not** leak into the enclosing scope: an `off` inside a module body is
closed by the module's `endmodule` at the latest, and an `on` written after
`endmodule` belongs to the file scope and cannot close it.
- **Fences never cross a scope boundary**, which is what keeps a region
aligned with item boundaries: a region can never end in the middle of an
item, so the formatter never has to print half of one.
### Out of scope this round: statement-level fences
A fence inside an item body — between two statements in an `always` block,
between two case items, inside a port list — **has no effect**. It is
formatted as an ordinary comment. Only `Item` lists are fenceable:
| fenceable scope | |
|---|---|
| file | `SourceFile.items` + `dangling` |
| package body | `ItemKind::Package` |
| module body | `Module.items` + `dangling` |
| `generate` region | `ItemKind::GenerateRegion` |
| generate `begin`…`end` | `GenBlock` with `is_block` |
Not fenceable: statement lists (`begin`/`end`, `fork`, function/task bodies),
case-item lists, port/parameter/connection lists, and the single-item body of
a bodyless `if (X) item;` in a generate (there is no list for a fence to end
in, and the formatter lays that item out inside a `Group`).
The interaction worth knowing: an `off` at item level whose matching `on` was
written inside a *statement* is an unmatched `off`, so it runs to the end of
the item list rather than stopping at the `on`. That errs toward *more*
verbatim text, never toward reformatting something the author fenced off.
## Splice mechanics
`fence::collect(src, &file)` walks the item scopes once, before any
formatting, and returns a sorted, non-overlapping `Vec<Region>`:
```rust
struct Region { fence: usize, start: usize, end: usize }
// ^ the `off` comment's own first byte (identity)
// ^ first byte emitted (start of that line)
// ^ one past the last byte emitted
```
Regions found inside an already-fenced range are dropped: the items holding
them are never formatted, so their fences never run. Because a region is
`[fence, end)` in a scope's own unit order and scopes nest, dropping any
region whose `fence` falls before the previous region's `end` leaves a list
that is sorted by both ends — so lookup is a `partition_point`.
During formatting, `Fmt` carries the source text and that list, and asks one
question per unit:
| unit | test | result |
|---|---|---|
| a comment | it *is* a region's `off` fence | emit `Doc::Verbatim(src[start..end])` |
| a comment | it starts inside a region | emit nothing |
| an item's code | `item.span.start` is inside a region | emit nothing |
`Doc::Verbatim` is a new printer instruction: it strips the indentation the
preceding line break just wrote and copies its string through untouched,
newlines and all. That is the whole of "emit the original bytes".
An item whose code is skipped but whose leading comments are not (a `doc`
comment above the `off` fence) still emits those comments — comments are
never dropped. An item that emits nothing at all contributes no separator
either, so no stray blank lines appear where the region swallowed items.
### Boundary / join decisions
- **Before the region**: the usual item separator, blank-line-aware, driven
by the `off` fence comment's own `blank_before` flag (which is also the
item's, since a `Meta`'s `blank_before` is its first leading comment's).
A blank line before `// vfmt: off` survives; two or more collapse to one,
as everywhere else.
- **First line of the region**: byte-exact, because the region starts at the
line start, not at the `//`. The exception is a fence preceded on its own
line by *another comment* (`/* a */ // vfmt: off`): there the region starts
at the `//`, and the other comment is formatted onto the line above. Still
idempotent — on the next pass the fence does start its line.
- **Inside the region**: nothing is touched, trailing whitespace on interior
lines included. `Doc::Verbatim` copies bytes; the printer's
trailing-space trimming only ever fires on line breaks *it* emits.
- **After the region**: a `HardLine` at the enclosing indent, so the next
item starts correctly indented on a fresh line. The blank line between the
`on` fence and the next item is dropped, which is exactly what already
happens between an item's last leading comment and the item itself.
- **Region ends at end of file**: the `format_once` tail normalization
(strip trailing blank space, add one `\n`) applies as usual, so the file
still ends in exactly one newline.
## Assumptions
- **Fence comments arrive as `Meta.leading` comments with correct spans.**
Guaranteed by the lexer's attachment phase (a comment not on the same line
as a preceding token becomes leading trivia) and by `docs/features/spans`.
- **A node's span is its code extent, attributes included, comments
excluded** — the `spans` convention. Both halves are load-bearing: the
attribute half is why splicing an item reproduces its `(* keep *)`, and the
comment half is why an item's leading comments can be emitted while its
code is skipped.
- **The formatter is only reachable through `format_source(&str)`**, so the
source text spliced from is always the exact text the spans were lexed
from. There is no AST-taking entry point that could pair a tree with a
different string.
- **A leading comment precedes its item's span.** One case can violate it —
an attribute followed by a comment (`(* x *)` newline `// c` newline
`wire a;`), where `Meta.leading` holds a comment positioned *after*
`item.span.start`. Fence detection skips such comments outright rather than
building a region that would double-emit the attribute.
- **Slicing is char-boundary safe** because every offset comes from a span or
from a scan over ASCII delimiters. The slice is still taken with `get()`:
if it were ever `None` the region comes out empty, `verify_equivalence`
rejects the output, and the file is left untouched — a failsafe, not a
panic.
## Handshakes
**Consumed from `vlog_parser`:**
- `Comment.span` / `Comment.text` / `Comment.blank_before` — the fence
matcher and the region boundaries.
- `Item.span` (code extent, attributes in, comments out) — region membership
for an item's code.
- The item-scope shapes: `SourceFile{items,dangling}`, `Module`,
`ItemKind::Package`, `ItemKind::GenerateRegion`, `GenBlock`, `GenIf`,
`GenFor`, `GenCase`.
Nothing in `crates/vlog_parser` was changed, and nothing new is required of
it for this feature to work as documented.
**Requested of `vlog_parser` (optional, not blocking):** a span on
`Meta.trailing`. Today it is an `Option<String>`, which is why a fence
written after code on the same line (`wire a; // vfmt: off`) cannot be
honoured — there is no offset to start the region at. If trailing comments
ever grow spans (they already exist on `Token.trailing`; `Meta` drops them
during harvest), this feature can accept same-line fences by starting the
region at the *following* line. Until then the limitation is documented
above. This is a request, not a change: no parser file was touched.
**Promised to `vlog_formatter` callers:** none of the public API changed.
`format_source` has the same signature and the same contract.
**`verify.rs` is untouched.** No normalization was added, broadened or
weakened, so CLAUDE.md hard invariant #4 does not apply to this round, and
none was needed: a fenced region is *source bytes*, so it re-lexes to exactly
the tokens and comments it came from, and the units it replaces are exactly
the ones whose bytes it contains. Equivalence therefore holds by
construction, and the check runs unchanged as the backstop that catches any
mistake in that reasoning (an off-by-one region end would drop or duplicate a
token and be rejected).
**Recursion budget (`docs/features/recursion-limit/README.md`):** unaffected.
`fence::collect` recurses only through nested *item* scopes, which is a
subset of the AST depth the parser already bounds at 320 layers, and it
builds no new tree. `Doc::Verbatim` is a leaf.
**`Doc` gained one variant.** `Doc::Verbatim(String)` — source bytes at
column 0, newlines included. It is treated as containing a hard line
(`contains_hard_line`, `Printer::fits`), so it can never be measured for a
flat layout. The one contract it relies on: it is only ever emitted right
after a line break or at the very start of the output, which is where the
"strip the indentation just written" step is correct. Both current emitters
(`Fmt::leading_comments`, `Fmt::dangling`) satisfy that.
## Status / TODO
- [x] `fence.rs`: `fence_of(&str) -> Option<Fence>` exact matcher, with unit
tests for every accept/reject spelling.
- [x] `fence.rs`: `collect(src, &SourceFile) -> Vec<Region>` over the five
fenceable scope shapes, nested-region drop, unmatched-to-end-of-scope.
- [x] `Doc::Verbatim` + printer support (`print`, `fits`,
`contains_hard_line`).
- [x] `format.rs`: `Fmt { src, regions }`, fence-aware `leading_comments` /
`dangling` / `item_seq` / `item_docs`; separators suppressed for units
the region swallowed.
- [x] `tests/cases/fences.cases` — 25 table cases (each also asserts
idempotency and, through `format_source`, equivalence).
- [x] `tests/fences.rs` — 6 tests: byte-exactness, own-indentation,
unmatched-off scoping, comment preservation, matcher/formatter
agreement, and five hand-built corrupted-region pairs the safety net
must reject.
- [x] README.md Style section mentions fences.
- [x] TODO.md §2 fences item checked.
- [ ] **Not done, deliberately:** statement-level fences (documented above).
- [ ] **Not done:** same-line (`trailing`-trivia) fences — blocked on a
parser change, see Handshakes.
## Work log
### 2026-08-19 — dev agent
- Read `CLAUDE.md`, `README.md`, TODO.md §2/§5, and the Handshakes of
`spans` and `recursion-limit` first. Baseline before touching anything:
`cargo test --workspace` **161 passed** (`vlog_formatter` 42), clippy
silent, fmt clean.
- **Chose "region = raw source slice" over "re-print the AST unchanged"**
without much deliberation — it is the only version where verbatim is a
fact rather than a claim, and it is what makes the safety net green by
construction instead of by argument.
- **Chose exact-match fence text over prefix matching.** A prefix match makes
`// vfmt: off-by-one` a formatting switch. Exact match's failure mode is a
fence that does not fire, which the author sees immediately in the diff.
- **Fences are leading comments only, and only line comments.** The leading
restriction is forced: `Meta.trailing` is an `Option<String>` and carries no
span, so there is no byte offset to start a region at, and `vlog_parser` is
owned by another agent this round. Recorded as a Handshake request rather
than worked around. The line-comment restriction is a choice: it keeps a
fence a whole-line thing.
- **Region starts at the line start, not at the `//`.** First version sliced
from `comment.span.start`, which left the region's first line re-indented by
the printer while every other line kept its source indentation — visibly
asymmetric on a mis-indented fence. Extending the start to the beginning of
the line (only when nothing but whitespace precedes) makes the whole region
byte-exact, and needed a new `Doc::Verbatim` so the printer would stop
prepending its own indent.
- **`Doc::Verbatim` rather than reusing `Doc::Text`.** `Text` is documented as
newline-free and the printer counts its width; a variant states the "bytes,
column 0, forces a break" contract instead of leaving it implicit. One
existing caller (`raw_text` on a string that crosses a line) still abuses
`Text` — left alone, out of scope.
- **Unmatched `off` needed a trailing-comment scan.** The scope end is the
last item's `span.end`, and an item's same-line trailing comment sits
*after* it with no span of its own. Without the scan, `wire a; // note`
inside an unmatched region dropped `// note` — hard invariant #3. Found by
reasoning about `Meta.trailing`'s missing span before writing the test, then
pinned by `unmatched_off_keeps_a_trailing_comment` and a `.cases` entry.
The matched case needs no scan: the `on` fence is later in the stream, so
the trailing comment is inside the range already.
- **Separator suppression was the second bug of construction.** An item whose
code is swallowed still emitted the `HardLine` its last leading comment
asked for, and then `item_seq` added the next item's separator on top —
a blank line after every region. `item_docs` now drops that dangling
`HardLine` when the code is skipped, and `item_seq`/`dangling`/`file`
separate on "did this unit emit anything" instead of on the index. With no
fences present the two formulations are identical, which is why the
existing suite shows zero churn.
- **Guarded the attribute-then-comment ordering case** (`(* x *)` on one line,
a comment on the next, then the item): `Meta.leading` can hold a comment
positioned after `item.span.start`, and a region opened there would emit the
attribute both inside the slice and again as formatted output. Fence
detection skips any leading comment that starts at or after its item's span.
- **Stress-tested against the corpus rather than trusting the unit tests.**
Injected an `off`/`on` pair at 1 868 random line positions across the 468
corpus files that parse, and compared the result against the same runs with
the fence text replaced by an ordinary comment of identical width:
- **0 new verification failures.** 112 of the 1 868 plain-comment runs fail
equivalence — a *pre-existing* bug class (a comment injected into a port
list or an expression gets moved or dropped; the safety net catches it and
the file is left untouched). The fenced runs fail on 94 of the same
trials and on **no others**; 18 are avoided precisely because the region
went verbatim.
- **Byte-exactness at corpus scale.** Restricting the injection so both
fences land at the same nesting level gives 294 honoured regions, of which
287 are reproduced byte-for-byte. The other 7 are all the documented
cross-scope case (the `on` landed in a different scope, so the `off` ran
to the end of its own): each preserves a verbatim *prefix* that stops
exactly at its scope's last item.
- **Two pre-existing bugs found in passing, both left alone** (out of scope,
reported to the lead): the comment-injection failures above, and a
double-blank-line bug — two leading comments separated by a blank line come
out separated by *two* blank lines, because `Fmt::leading` emits a
`HardLine` after each comment and then a `BlankLine` before the next.
Reproduced on the pre-change binary; not touched here because fixing it
churns snapshots.
- Did not touch `crates/vlog_parser`, `crates/vfmt`, `verify.rs`, or
`tools/`. Did not run `git commit`/`git push`.
**Results:** `cargo test -p vlog_formatter` **53 passed** (was 42: +5 matcher
unit tests in `fence.rs`, +6 in `tests/fences.rs`), plus **25 new
`.cases` entries** inside `case_tables`. No existing test changed and no
snapshot or `.cases` churn — the fence-aware separator logic is
byte-identical to the old index-based one when no fence is present, which is
what the untouched suite demonstrates. `cargo test --workspace` **194 passed,
0 failed** (that number also carries the concurrent error-tolerant-parsing
agent's new `vlog_parser` tests). `cargo clippy --workspace --all-targets`
silent (0 warnings). `cargo fmt --all --check` clean. Corpus:
`tools/corpus_check.sh corpus` (read-only) — 820 files, 2 ok-unchanged, 466
would-reformat, 352 parse-error, **0 verification errors, 0 crashes**, TSV md5
`3fab114f4f00626b254259e9dafe0ed7`, **byte-identical** to the `spans`
baseline. No `.sv`/`.v` corpus file contains a fence comment (`grep -rl` over
all 820: 0 hits; the only two `verilog_format` matches in the tree are a CI
YAML comment and a Verible build script), so the feature is inert there, as
expected. Corpus repos `git status --porcelain` clean apart from the
pre-existing untracked `.vfmt-corpus-rev` stamps.
Files touched: `crates/vlog_formatter/src/fence.rs` (new),
`crates/vlog_formatter/src/{lib,doc,printer,format}.rs`,
`crates/vlog_formatter/tests/fences.rs` (new),
`crates/vlog_formatter/tests/cases/fences.cases` (new), `README.md` (Style
section), `TODO.md` (§2 checkbox), this README.
## QA log
### 2026-08-19 — QA agent
Scope: `crates/vlog_formatter` only (a concurrent QA agent owns
`vlog_parser`/error-recovery this round; untouched here). No commit/push.
All work done via a scratch cargo project pointing at this crate by path
(`/private/tmp/.../scratchpad/qa_probe`) plus a disposable `git worktree` at
`HEAD` (901a78c, pre-fence) for baseline comparisons — both removed after
use, working tree left exactly as found (`git status --short` before/after
identical).
**Tool results.**
- `cargo test -p vlog_formatter`: **53 passed, 0 failed** (8 lib unit tests
— 5 in `fence.rs` + 3 pre-existing in `printer.rs` — 1+4+6+2+32 across
`cases.rs`/`deep_nesting.rs`/`fences.rs`/`fixtures.rs`/`verification.rs`).
Matches the claimed 42→53.
- `cargo test --workspace`: **194 passed, 0 failed** (40+21 in `vfmt`, 53 in
`vlog_formatter`, 49+19+12 in `vlog_parser` — the last three carry the
concurrent error-recovery agent's work, not this feature's).
- `cargo clippy -p vlog_formatter --all-targets`: 0 warnings.
`cargo clippy --workspace --all-targets`: 0 warnings. Confirmed the
earlier-flagged `fence.rs:58` nit is gone: it reads
`regions.last().is_none_or(|prev| ...)`, not `.map_or(true, ...)`.
- `cargo fmt --check` (workspace): clean, no output.
- `verify.rs` untouched: `git diff --quiet -- crates/vlog_formatter/src/verify.rs`
exits 0. `tests/verification.rs` likewise unchanged (`git diff --quiet`),
and its 32 tests still pass unmodified.
- `git status --short`: only `README.md`, `TODO.md`,
`crates/vlog_formatter/src/{doc,format,lib,printer}.rs` modified in this
feature's footprint, plus the four new files
(`fence.rs`, `tests/fences.rs`, `tests/cases/fences.cases`,
`docs/features/format-fences/README.md`) — matches the work log's "files
touched" list exactly. `crates/vlog_parser/**` changes present are the
concurrent feature's, not this one's.
- `tools/corpus_check.sh corpus`: 820 files, **0 verification errors, 0
crashes**, TSV md5 `3fab114f4f00626b254259e9dafe0ed7` — **matches** the
claimed baseline exactly (byte-identical results file). `grep -rl` for
`verilog_format|vfmt:` across all `.sv/.v/.svh/.vh` in `corpus/`: **0
hits**, confirming the feature is inert on the corpus as claimed.
**Claim 1 (fence grammar) — PASS.** Direct `fence_of()` probes:
`// vfmt: off ` (single trailing space) *is* a fence — correctly so, the
grammar trims surrounding whitespace and only disqualifies non-whitespace
trailing text; my first pass at this check used the wrong expectation and
was self-corrected. `// VFMT: off` (case), `// vfmt: off` (inner double
space), `// verilog_format:off` (no space after colon) are all correctly
rejected — matches the documented grammar exactly, no drift between prose
and code. Block comments and same-line trailing comments confirmed inert
via both the `.cases` table and my own probes.
**Claim 2 (semantics) — PASS.** All items verified, including two not
explicitly in the `.cases` table: (a) a region nested inside another
region — outer `off`/`on` wrapping a module that has its own inner
`off`/`on` pair — is correctly collapsed to one region (`fence::collect`'s
dedup), the inner fence pair is inert text, output byte-exact,
second-pass idempotent. (b) unmatched-`off` correctly stops at
`endmodule`/`end` and never leaks into the next scope, confirmed at file,
module and generate-block granularity.
**Claim 3 (splice mechanics) — PASS.** Adversarial idempotency probes (24
targeted cases: fence at file start/end with and without trailing
newline, zero items between off/on, off right after `module m;` + on
right before `endmodule`, two adjacent regions, matched region whose last
item has a same-line trailing comment, interior tabs/trailing spaces,
multi-line macro + attribute inside a region, 1/2/3 blank lines in three
different positions around the fences, generate-block-final region
matched and unmatched, CRLF file variants including a fence sharing its
line with a block comment, a crammed one-line port/connection list inside
a region, and a 200-column line inside a region) — **all byte-exact and
idempotent, zero failures.** Region-content protection confirmed: the
200-col line and the crammed port list both survive verbatim, and
formatting resumes at the correct indent immediately after (`assign z = a
+ b;` at 2-space indent right after a verbatim block that was written at
column 0). CRLF interior bytes (`\r\n`) survive inside `Doc::Verbatim`
slices exactly; the formatter's own emitted lines around them use `\n` as
usual — pre-existing, general behavior, not fence-specific, and internally
consistent (idempotent).
Reviewed `printer.rs`'s `Doc::Verbatim` indent-stripping
(`while out.ends_with(' ') { out.pop(); }`) for a tabs-vs-spaces gap: the
printer's own indentation is generated exclusively via
`" ".repeat(...)`-style space writes (confirmed by reading `print()`), so
there is no path where the "indentation just written" contains a tab —
the space-only strip is correct as written, not a latent bug.
**Claim 4 (matcher) — PASS**, see Claim 1; the `tests/fences.rs`
`the_matcher_agrees_with_what_the_formatter_honours` test already pins the
matcher-vs-formatter agreement in both directions and I independently
reproduced every spelling in the task list against `fence_of` directly.
**Claim 5 (interaction with error-recovery arms) — PASS, and
strengthened.** The README's Handshakes section reasons that
`fence::collect` never sees `ItemKind::Error` in production because
`format_source` only calls the strict `parse_source`. I went further and
called `fence::collect` directly against a `parse_source_tolerant(...)`
tree containing an `ItemKind::Error` node (adjacent to, and also
overlapping the leading comments of, a fenced region) — no panic, and
`ItemKind::Error` is correctly ignored by `scan_nested`'s catch-all arm in
both configurations tried. This is dead code in today's product but is
now empirically confirmed safe, not just reasoned about.
**Claim: 1868-injection stress (evidence review, not reproduced at that
scale) — directionally confirmed.** I ran an independent ~200-trial
random injection harness against the same `corpus/` (118 trials usable
after skipping the 82 that don't parse, consistent with the corpus's
~43% parse rate). Initial naive comparison (fence pair vs. a *single*
plain padding comment) showed 1 "new" fence failure, but that comparison
was unfair — the fence variant inserts two lines (off+on), the plain
variant only one. Re-run with a fair **paired** control (plain padding
comments at the *same two* line positions): **0 new verification failures
attributable to fencing**, and the fence variant additionally *avoided* 2
failures the plain-pair control hit (regions the fence sent verbatim that
a plain comment injected at the same spot would have corrupted) — this
directly corroborates the dev's own "0 new verification failures" /
"18 avoided precisely because the region went verbatim" claim, on an
independent sample. I did not attempt to reproduce the dev's exact
1868/294/287/7 figures (no harness script was checked in to rerun
verbatim); treat those as the dev's own measurement, independently
corroborated in direction and magnitude but not bit-for-bit.
**Claim 7 (pre-existing bugs) — PASS, both reproduced on the pre-change
binary.** Using a disposable `git worktree` at `HEAD` (901a78c, before any
of this feature's changes):
- **Double-blank between leading comments**: `module m;\n // first\n\n //
second\n wire a;\nendmodule\n` reproduces the extra blank line
(`// first` then *two* blank lines then `// second`) identically on the
baseline binary. Confirmed pre-existing, not introduced.
- **Comment in a list dropped → refused**: reproduced the exact corpus
hit (`corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_mubi16_dec.sv`,
padding comment inserted before line 16) on both the baseline worktree
and the current tree — byte-identical error message
(`token stream diverges at index 18: input has comment ... output has
symbol "#"`) on both. Confirmed pre-existing. Note for context (not a
correction of the dev's claim): this bug class is the same one already
tracked as open "refusals" in `docs/features/corpus-bugs/README.md`
("Comments inside a replication, inside a compactly-printed bracket
expression, ... remain refusals" — this feature's finding is another
instance of that same, already-known category, not a new one).
**Durability of the two open items — PASS with a minor, non-blocking
suggestion.** Both are recorded in this README's Work log, which is a
required, checked-in section per `CLAUDE.md`'s document-based-development
rules, so they are not silently lost by the letter of that requirement.
They are *not* mirrored as `TODO.md` §1 entries the way other QA-found
bugs in this repo are (e.g. the `@(* )` lexer bug, tagged "(bug-fix QA
find)"). Since `TODO.md` is described as the project's "curated backlog"
and is where a future agent would look first, I'd suggest the lead add
one line each there for discoverability — informational only, not
blocking.
**Claude.md compliance — PASS.** No `unwrap()`/`expect()`/`panic!` outside
`#[cfg(test)]` in `fence.rs` or the `format.rs` diff (checked by grep on
the diff and the file). All new `pub` items in `fence.rs` carry one-line
doc comments. No `unsafe`. `README.md`/`TODO.md` checkbox changes are
accurate to what shipped (statement-level and same-line fences correctly
left unchecked with a documented reason).
**Overall: no BLOCKING findings.** No byte change inside any fenced
region across two passes in any probe, no behavior change with zero
fences present beyond what the existing untouched test suite already
covers (byte-for-byte zero churn). The one apparent anomaly during
testing (the "1 new fence failure" in the naive injection comparison) was
a flaw in my own harness's methodology, not the feature — resolved with a
fair control, see above.
## Review
**2026-08-19 — lead. Verdict: accepted; commits jointly with
error-recovery (entangled in `format.rs` via the `Error` match arms).**
The user-facing rule this feature had to get right — *bytes inside a
fence are sacred* — survived 24 adversarial join probes and ~2000
combined corpus injections (dev's 1868 + QA's paired-control 118) with
zero region byte changes and zero new verification failures. Points
reviewed and accepted:
1. **Exact-match fence grammar** (trailing text disqualifies, no-space
`vfmt:off` disqualifies): strict grammars over lenient ones is the
config-discovery lesson applied again — a fence that half-matches
silently doing nothing would be the worst outcome, and the current
rule makes it at least predictable. Verible-compatible spelling plus
the short alias is the right pair.
2. **Item-level scope, statement level deferred** — the honest scope
line, documented and tested (an off-fence inside an item body is
inert). Same-line trailing fences are inert for a structural reason
(Meta.trailing has no span) — the Handshake filed on vlog_parser is
the right escalation instead of a hack. That handshake lands
naturally with the comments round.
3. **Doc::Verbatim as a first-class hard-line element** rather than
string surgery in the printer: right layer, and "with no fences the
output is byte-identical" held (corpus md5 exact).
4. Two construction-time bugs (dropped trailing comment on unmatched
off, stray separator from swallowed items) caught and fixed by the
dev's own tests — the invariant-test-first habit is now visibly the
house style.
QA's suggestion adopted at review: the two pre-existing bugs this
feature surfaced (comment-in-list refusal, quantified at 112/1868
trials; the double-blank leading-comment nit) are now TODO.md items
queued for a dedicated comments round — they were too big to ride
along here, and the refusal path means neither can corrupt.