Add dynamic-types and one-parse (round 19)

dynamic-types: queues ($ as an expression primary -- one grammar
addition and [$], [$:N], q[$-1] all fall out of existing machinery),
dynamic [] and wildcard [*] dims (DimKind, the round's one
non-additive AST change: three consumers, all updated), empty {}
literals, named call arguments f(.a(x)) as ExprKind::NamedArg,
case ... inside with range labels, bare @event sensitivities (also
fixing a pre-existing invented-parens refusal), and macro items
before ident-dot statements. Everything structural, nothing
verbatim; verify.rs and fence.rs byte-identical. Corpus 578 ->
636/820 formattable (70.5% -> 77.6%), parse-error 242 -> 184, 58
gained / 0 lost by path, all 636 round-tripped, all 578 previously-
formattable files byte-compared old-vs-new with zero differences.
Two newly-reachable comment drops fixed in-round (one pre-existing,
one this round's own new code -- split documented honestly post-QA).
New top blockers: interface (25), the `else head-swap (13).

one-parse: LintContext::from_parse accepts pre-built parse products
(Backing enum forced by SourceFile: !Clone; new() stays a one-line
wrapper -- all 12 rule files byte-untouched); ParsedSource::parse
lexes once; vfmt check parses once per file; the server lints from
Document's own products, eliminating the per-keystroke second parse.
Behavior identity proven at the byte level (2.4MB corpus JSON, 13
server publishes, corpus-wide --fix); check --threads 1 20% faster,
server didChange latency roughly halved. protected_regions left
alone per its documented anti-drift signature. Lead fixes on
acceptance: the from_parse contract-cost doc sentence, and a stale-
tree guard test in the server (QA's sabotage passed all 773 tests --
nothing pinned text/tree agreement; now one test does, through the
merged diagnostics path where the stale warning actually lives).

791 workspace tests. Dev: 2 Fable agents; QA: 2 Opus agents; reviews
in docs/features/{dynamic-types,one-parse}/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-19 20:22:18 -07:00
1 parent e9008b680c
commit da1448ecd0
20 files changed
+2478 -96

No files matched your search

+760
View File
@@ -0,0 +1,760 @@
# dynamic-types
## Goal
Parse and format the dynamic-type declarations and the call syntax that are the
corpus's top remaining parse blockers after the classes round: queues
(`T name[$]`), dynamic arrays (`T name[]`), associative arrays
(`T name[string]`, `T name[*]`), named function/task call arguments
(`f(.a(x), .b(y))`), and `case (expr) inside`. The whole-corpus first-blocker
histogram going in: `$` 41 files, `]` 23, `.` 21, `inside` 7 — together 92 of
the 242 parse errors. All of it is DV/UVM code under `ibex/dv`,
`google_riscv-dv`, `lowrisc_ip/dv` and `common_cells/test`; every shape below
is taken from a real blocked file, cited.
## What is structural, and what is verbatim
Everything in this round is **structural** — real AST, canonical layout.
Nothing new is captured verbatim, so no new normalization was needed and
`verify.rs` is untouched (see Handshakes).
| construct | corpus evidence |
|---|---|
| `T q[$]` in class properties, module/function locals | `riscv_instr.sv:23`, `str_utils_pkg.sv:80`, `uart_scoreboard.sv:34` |
| `[$]` after multi-dim unpacked dims (`x [A][B][$]`) | `stream_xbar_tb.sv:52`, `rr_arb_tree_tb.sv:224` |
| queue of parameterized type (`item #(A, B) q[$]`) | `push_pull_device_seq.sv:54` |
| `[$]` in function/task args, all directions (`output string instrs[$]`, `ref ... flds[$]`) | `riscv_privileged_common_seq.sv:37`, `dv_base_reg_pkg.sv:90` |
| `q[$]` / `q[$-1]` as an expression index (`instr_list[$].label = x`) | `ibex_directed_instr_lib.sv:43`, `riscv_directed_instr_lib.sv:34` |
| bounded queue `T q[$:N]` | **zero corpus hits** (`grep -rEn '\[\$:'`), taken anyway — it is the same `Range` dim the unbounded spelling produces, zero extra grammar |
| `T a[]` dynamic arrays, same positions | `riscv_amo_instr_lib.sv:22`, `riscv_pmp_cfg.sv:62`, `riscv_asm_program_gen.sv:32` (`[NUM_HARTS][]`) |
| `= {}` / `= {A, B}` queue/dyn-array initializers | `ibex_icache_scoreboard.sv:31` (`= {}`), `riscv_core_setting.sv:27` (×12 targets), `riscv_instr_pkg.sv:1214` |
| `T a[*]` wildcard associative | `cb_filter_tb.sv:51` |
| named call arguments `f(.a(x))`, incl. scoped callees and multi-line lists | `uart_base_vseq.sv:156`, `prim_lfsr_tb.sv:297`, `uart_noise_filter_vseq.sv:42` |
| `case (expr) inside` with `[lo:hi]` and plain labels | `riscv_privil_reg.sv:28,189`, `riscv_zbs_instr.sv:42` (7 files, 40 occurrences) |
| `@hier.name;` event control without parens | `ibex_mem_intf_response_seq_lib.sv:60` |
**Verified already parsing (no work needed, pinned by cases):**
`T a[string]` and `T a[user_key_t]` associative arrays (`string` is a
TYPE_KEYWORD and parses as a type expression inside the brackets; an
identifier key parses as an expression — both round-trip); `x = new[expr]`
(`new` is deliberately not a keyword, so this is an index on an ordinary
name — `core_ibex_test_lib.sv:475`, `str_utils_pkg.sv:169`); queue method
calls (`q.push_back(x)`, `q.size()`) are ordinary member calls.
## Assumptions
- **`$` is an ordinary primary expression, not a keyword.** In real code a
bare `$` stands only where a queue bound belongs (`q[$]`, `[$:N]`,
`q[$-1]`), but vfmt does not check legality anywhere else either, and one
`ExprKind::Ident("$")` leaf makes every position — dims, indexes, ranges,
arithmetic — work through the existing expression grammar. This follows the
`new`/`this`/`super` precedent from the classes round. The lexer already
emits a lone `$` as a one-char Symbol token; nothing lexes differently.
- **`{}` is accepted as an empty concatenation** (`ExprKind::Concat(vec![])`)
because SystemVerilog's empty queue literal is spelled that way
(`mem_states[$] = {};`). Plain Verilog forbids `{}`; vfmt is a formatter,
not a compiler, and refusing it would keep a real corpus file blocked.
- **A named call argument is recognized by `.` + identifier at an expression
*element* start.** `parse_expr_item` is shared by call arguments, concats,
replications and case labels; the `.name(...)` prefix is only legal in the
first, but accepting it in the others changes no existing parse (no
expression can start with `.` today) and cannot corrupt (same tokens out).
Same argument for `[lo:hi]` value-range elements, which `case ... inside`
labels need and no expression could previously start with.
- **`case (x) inside` is the same statement with one extra token.** The
`inside` flag is stored on `StmtKind::Case` and printed back; item labels
are the ordinary label list plus `[lo:hi]` ranges. vfmt does not restrict
range labels to inside-mode cases — a plain `case` with a `[1:2]:` label is
not legal SV but parses; same tokens out, no corruption possible.
- **A bare `@name;` (no parens) is printed back without parens.** Before this
round the parser accepted `@ev;` and the formatter printed `@(ev)` — a
token-stream change the net *refused* (pre-existing, zero corpus files hit
it, found while extending the arm). `SensList::Bare` records the spelling;
`@(ev)` stays a `List`. The bare arm now also takes a `.`-chain
(`@p_sequencer.monitor_tick;`).
- **A macro invocation followed by `ident.` is standalone.** `at_macro_item`'s
identifier arm gains one clause (next-next token `.`), mirroring the `#(`
clause the classes round added: `` `WAIT_FOR_RESET`` ⏎ `cov.cg.sample(...)`
is a standalone macro and a call statement, never a declaration — a
declarator name is never followed by `.`. Wrong guesses still cannot
corrupt: both readings emit the same tokens.
- **Two comment drops were fixed mid-round** (the classes-round protocol: a
refusal the corpus can now hit is fixed, not documented away). They are
not the same category, stated precisely per QA-1:
- **pre-existing** — a comment beside a procedural assignment's operator
(`instr[6:0] /* opcode */ = OPCODE_JALR;`, both sides) reproduces on
HEAD with no new syntax: it was left in the pending buffers and the net
refused the file. `StmtKind::Assign` gained `op_comments`/`rhs_comments`,
captured with the same `take_around` marks a continuous assignment's
`rhs_comments` use. Found by `ibex_compressed_decoder.sv:89` the moment
its earlier blocker (named call args at line 62) was gone.
- **this round's own new code** — a comment before a named argument's
closing `)` (`.src(5'd0 /* x0 */)`) cannot reproduce at HEAD because
`NamedArg` did not exist there (the `Connection` analog it is modelled
on formats cleanly on HEAD). The first `NamedArg` version lacked the
before-`)` slot a `Connection` has; `close_comments` was added when the
corpus caught it (same file, line 139) — a gap caught and fixed inside
the round.
- **Blocked-but-out-of-scope shapes stay parse errors**, with evidence:
`` `uvm_field_int (x, y)`` (space before `(`) is the documented macro-items
lexer gap, 10 files, not touched; `interface` declarations (25 files) are
README roadmap item 8; the `wait(...)` / `with` / DPI shapes are single
files each and listed in the corpus results below.
## Handshakes
**Changed in `vlog_parser::ast` (consumed by `vlog_formatter`):**
- `Dim` is now `{ kind: DimKind, span }` with
`DimKind::Range { a: Expr, b: Option<Expr> }` (every pre-existing dim, plus
`[$]`/`[$:N]`/`[string]`/`[key_t]` via ordinary exprs), `DimKind::Dynamic`
(`[]`) and `DimKind::Wildcard` (`[*]`). This is the one **non-additive**
change of the round; every consumer was found by grep and updated:
`Fmt::dim` (format.rs), `bind_dims` (`vlog_semantic/src/bind.rs`, see
below), and the spans walker (reads only `span`, unchanged).
- `ExprKind::NamedArg { name, name_span, value: Box<Expr>, close_comments }`
— a named call argument. `value` is `ExprKind::Empty(comments)` for
`.a()`, exactly as a connection's empty `()` is; `close_comments` is the
before-`)` slot a `Connection` has. Printed tight: `.name(value)`.
- `SensList::Bare(Expr)` — `@name` / `@a.b` with no parens, printed back
without parens. `SensList::List` still always prints `@( ... )`.
- `StmtKind::Case` gained `inside: bool`; `StmtKind::Assign` gained
`op_comments` / `rhs_comments` (see Assumptions). Additive for every `..`
match; `Fmt::stmt_kind` (exhaustive) updated in the same change.
- `ExprKind::Concat(items)` may now be empty (`{}`); `Fmt::expr_list` →
`delimited` already prints an empty list as `{}`.
- `parse_ident_item`'s parameterized-type lookahead refined: `[` after the
declarator is an instance array range only when its matching `]` is
followed by `(`, so `item_t #(A, B) q[$];` is a declaration while
`sub #(8) u[3:0] (...);` stays an instance. The statement-level twin in
`parse_assign_or_expr_stmt` already read it correctly.
**Consumed from / required of `vlog_semantic` (minimal, documented):**
`bind.rs` is expression- and dim-exhaustive, so three small arms were
required to compile; each is the semantically correct minimum, not a stub:
- `bind_dims` matches `DimKind::Range` (binds `a`/`b` exactly as before) and
skips `Dynamic`/`Wildcard` (no expressions to bind — nothing skipped).
- `ExprKind::NamedArg { value, .. }` binds `value`; the argument *name* is
the callee's formal, which this crate does not model (same rule as
`Connection` port names).
- `TimingControl::Event(SensList::Bare(e))` binds `e`.
**Required of `vlog_linter`: nothing.** `visit.rs` walks items/statements
only (no expression walk) and its `StmtKind::Case` matches use `..`; the
crate compiles unmodified. Not touched — the concurrent one-parse-two-tools
round owns it.
**`verify.rs` is untouched** (`git diff --quiet -- crates/vlog_formatter/src/verify.rs`
exits 0). Nothing new is verbatim and no normalization was added, so hard
invariant #4 does not bind. Six rejection tests went into
`tests/verification.rs` anyway (a dropped `$`, `[]` widened to `[*]`, a
dropped named-arg name, a dropped `inside` keyword, parens invented around a
bare event, an emptied `{}` initializer — all asserted rejected; the
legitimate re-indent asserted accepted).
**Recursion/chain budgets:** nothing new to charge. `$` is a leaf;
`NamedArg` wraps its value once and is built inside the existing
argument-list loop (not a postfix chain); `DimKind` adds no depth. The dim
loop and label loop were already flat.
**Spans:** every new node carries a span. `NamedArg` keeps
`src[name_span] == name` (checked by the walker's new arm);
`ValueRange`/`Bare` reuse existing walker arms; two dynamic-type sources were
added to `SOURCES`.
**Not touched, by scope:** `crates/vfmt`, `crates/vfmt_core`,
`crates/vfmt_server`, `crates/vlog_linter`, `verify.rs`, `fence.rs`,
`editors/`, `tools/`, `corpus/`. A concurrent agent owns `vlog_linter` /
`vfmt` / `vfmt_server` this round; `cargo fmt` was run per-package
(`-p vlog_parser -p vlog_formatter -p vlog_semantic`), never `--all`.
## Status / TODO
- [x] `$` as a primary expression (`q[$]`, `q[$-1]`, `[$]`, `[$:N]`).
- [x] `DimKind::{Range, Dynamic, Wildcard}`; every consumer updated.
- [x] `{}` empty concatenation/queue literal.
- [x] Named call arguments (`ExprKind::NamedArg`), `.a()` empty value,
multi-line lists, scoped callees.
- [x] `case (expr) inside` with `[lo:hi]` labels (`StmtKind::Case.inside`).
- [x] `SensList::Bare` — `@name;` / `@a.b;` without parens (also fixes the
pre-existing `@ev;` refusal).
- [x] `at_macro_item`: identifier followed by `.` means the macro stands
alone.
- [x] Comments beside a procedural assignment's operator and before a named
argument's `)` (the two newly-reachable pre-existing drops; see
Assumptions).
- [x] Verified already parsing, pinned by cases: `[string]`, `[key_t]`,
`new[expr]`, queue method calls.
- [x] 34 cases in `crates/vlog_formatter/tests/cases/dynamic_types.cases`
(397 → 431 overall).
- [x] 13 parser unit tests, 7 `tests/verification.rs` tests (6 rejection,
1 acceptance), 2 new `spans.rs` sources + the `NamedArg` walker arm
(name-span exactness checked).
- [x] Corpus re-run: by-path diff, 0 regressions, round-trip of **all 636**
formattable files, TSV deterministic across three runs (two before
the final `cargo fmt`, one after — byte-identical).
- [x] `README.md` roadmap item 4 struck + supported-syntax updated; TODO.md
corpus annotation.
- [ ] **Not done — `interface` declarations** (25 files, the new top
blocker). Roadmap item 8; a header-and-modport grammar of its own.
- [ ] **Not done — a directive inside an element** (13 files now show
`` `else`` as their first blocker, 12 of them the
`riscv_core_setting.sv` copies advancing past `[]`): the shape is
`` `ifdef DSIM`` ⏎ `privileged_reg_t implemented_csr[] = {` ⏎
`` `else`` ⏎ `const ... = {` ⏎ `` `endif`` ⏎ *shared elements* — two
alternative declaration *heads* over one initializer body
(`target/ml/riscv_core_setting.sv:98-102`). This is the
directives-in-lists round's documented non-goal ("a directive inside
an element stays a parse error"), now measured at 13 files; unparking
it is a design round of its own, not a list-machinery patch.
- [ ] **Not done — `` `uvm_field_int (x, y)``** (11 files): the documented
macro-items lexer gap (space before `(`); its fix lives in the lexer
and has a known expression-position side effect. Still not this
feature's to make.
- [ ] **Not done — `randomize() with { ... }`** (7 files, e.g.
`cb_filter_tb.sv:272`, `ibex_mem_intf_response_driver.sv:94`): an
inline-constraint clause — the constraint sub-language again, so the
classes round's verbatim treatment is the natural vehicle when a
round takes it.
- [ ] **Not done — `foreach` over a hierarchical index** (2 files, both
advanced from `]`): `foreach (program_h[id].sub_program_id[k])`
(`riscv_callstack_gen.sv:183`) and `foreach (page_table[i].pte[j])`
(`riscv_page_table_list.sv:130`). The `foreach` header grammar takes a
plain name plus loop variables, not a member chain with per-level
indexes — its own small construct, not dim machinery. These two are why
the `.` *token* still appears as a first blocker (QA-2).
- [ ] **Not done — a `[lo:hi]` value range as the *first* call argument**
(`f([1:2])` is a parse error while `f(x, [1:2])` parses): the postfix
`(` branch's first-argument dispatch gained the `.` case but not the
`[` case. No legal SystemVerilog is affected — a value range is not a
call argument — and `case … inside` labels go through
`parse_expr_item` at every position including the first. Recorded per
QA-8 so the asymmetry is not mistaken for a bug later.
- [ ] **Not done — associative-array *typed* keys beyond what already
parses** (e.g. `[bit [31:0]]`): zero corpus hits. Parked until a file
demands it.
## Corpus results
`./tools/corpus_check.sh corpus` over the same pinned 820-file corpus, release
build, exit 0. Three runs (two mid-round, one after the final `cargo fmt`):
byte-identical TSVs, md5 `e6f12eb7964e22e452655cf517cae766`. All four corpus
repos verified unmodified afterwards (`git status --porcelain` clean apart
from the pre-existing untracked `.vfmt-corpus-rev` stamps).
| metric | before | after |
|---|---|---|
| **parsed & formattable** | 578/820 (**70.5%**) | **636/820 (77.6%)** |
| would-reformat | 568 | 626 |
| ok-unchanged | 10 | 10 |
| parse-error | 242 (29.5%) | **184 (22.4%)** |
| verification-error | 0 | **0** |
| crash | 0 | **0** |
**Diffed by path against the baseline TSV, not just by count:**
| transition | files |
|---|---|
| parse-error → would-reformat | 58 |
| would-reformat → would-reformat | 568 |
| ok-unchanged → ok-unchanged | 10 |
| parse-error → parse-error | 184 |
| **any regression** | **0** |
58 files gained, 0 lost, no already-parsing file changed status. Gained by
tree: `google_riscv-dv` 24, `lowrisc_ip` 14, `opentitan/hw/ip` 8,
`common_cells/test` 7, `ibex/dv/uvm` 4, `ibex/rtl` 1
(`ibex_compressed_decoder.sv` — an RTL file, blocked on named call args).
**Per target blocker, the honest ledger** (each baseline-blocked file's
after-status checked individually):
| blocker | files | now format | advanced | their next blockers |
|---|---|---|---|---|
| `$` (queues) | 41 | **28** | 13 | `with` 3, one each: `assert` (`fifo_tb.sv:155`), `@` (`stream_register_tb.sv:75`), `;` (`ibex_cosim_scoreboard.sv:307`), `,` (`ibex_debug_triggers_overrides.sv:116`), `::` (`riscv_instr.sv:156`), `cp_sign_cross` (`riscv_instr_cover_group.sv:514`, a covergroup cross), `` `else`` (`riscv_instr_pkg.sv:1252`), `import` (`dv_base_reg_field.sv:97`), `` `TX_IGNORED_PERIOD`` (`uart_scoreboard.sv:155`) |
| `]` (dynamic arrays) | 23 | **6** | 17 | `` `else`` 12 (the `riscv_core_setting` head-swap shape, see Status/TODO), `::` 2, `.` 2, `with` 1 |
| `.` (named args) | 21 | **17** | 4 | `randcase` 3 (its weight labels are the reported `1`/`5` tokens), `with` 1 |
| `inside` | 7 | **7** | 0 | — |
**New whole-corpus first-blocker histogram:** `interface` 25, `` `else`` 13,
`` `uvm_field_int `` 11, `with` 7, `"DPI-C"` 7, `'` 7 (lex, `` '` `` in
macro bodies and unbased literals), `$error` 6, `virtual` 4, `export` 4.
No *shape* this round targeted remains a first blocker anywhere; the `.`
*token* remains first in 2 files, whose blocker is a different shape —
`foreach` over a hierarchical index (`foreach (a[i].b[j])`), parked under
Status/TODO with the evidence.
**Every formattable file was round-tripped, not sampled:** all 636 copied to
a scratch directory, formatted in place, then re-checked with `--check` —
exit 0 both passes, so every one is a verified fixed point.
**Two verification errors appeared mid-round and both were fixed, not
documented away** (both pre-existing comment drops reproducible without any
new syntax; see Assumptions): the corpus count went 1 → 1 → **0** as the
assignment-operator fix exposed the named-arg-paren drop in the same file.
## Work log
### 2026-08-19 — dev agent
- Read `CLAUDE.md`, `README.md`, `TODO.md`, and the `classes`,
`directives-in-lists` and `directives-in-instances` READMEs before touching
code. Baseline measured on this working tree, not taken from any README:
`cargo test --workspace` **768 passed** (verified suite-by-suite), clippy
silent, fmt clean; corpus 578/820 formattable, 242 parse-error, 0
verification errors, 0 crashes — matching the brief exactly.
- **Read the actual blocked lines of all 92 target files first** (a script
pulled each parse error's line from its file), and the reading changed the
design three times over:
(a) `[string]`, `[key_t]` and `new[expr]` **already parse** — `string` is
a TYPE_KEYWORD that goes through `parse_type_expr`, and `new` is
deliberately not a keyword, so `new[n]` is an ordinary index. Half of
"associative arrays" was already done and just needed pinning.
(b) The `.` blocker is *named call arguments* in 17 of 21 files, plus one
`@hier.name` event control and one macro-then-`cov.` shape — three
different fixes, not one.
(c) `inside` is `case (expr) inside` in all 7 files — the expression
operator was never the problem.
- **`$` became one `ExprKind::Ident` leaf, not a keyword and not a dim
special case.** The first sketch had a `DimKind::Queue` variant; reading
`instr_list[$].label = x` killed it — `$` stands in *expression* position
there, so a dim-only spelling would have needed a second rule for indexes.
One primary-expression arm makes `[$]`, `[$:N]`, `q[$]` and `q[$-1]` all
fall out of the existing grammar, following the classes round's
`new`/`this`/`super` precedent. `[$:N]` ships tested with zero corpus
demand because it is literally the same `Range` dim.
- **`DimKind` is the round's one non-additive AST change**, and its blast
radius was measured before the edit: grep found exactly three consumers
reading `Dim`'s fields (`Fmt::dim`, `bind_dims`, and the spans walker,
which reads only `span`). The alternative — sentinel expressions for `[]`
and `[*]` — would have made the formatter print from lies.
- **Named args went into `parse_expr_item`, the shared element parse**, plus
one dispatch in the postfix `(` branch (the *first* argument does not go
through `parse_expr_item`; found when `csr_wr(.ptr(p), ...)` parsed its
first arg as an error). Value-range labels (`[lo:hi]`) ride the same
dispatch, which is what makes `case ... inside` labels work at every
position without touching `parse_expr_list`. Accepting both shapes in
lists that cannot legally hold them is recorded under Assumptions: no
expression could previously start with `.` or `[`, so nothing re-parses.
- **The bare-event fix started as a parse extension and became a formatter
bug fix.** Extending `@ident` to `@a.b` was two lines — and then the probe
showed plain `@ev;` had *always* been refused at runtime (the parser
accepted it, the formatter printed `@(ev)`, the net refused the invented
parens; zero corpus files hit it, which is why it survived). Hence
`SensList::Bare`: record the spelling, print the spelling.
- **`parse_ident_item`'s `#(` heuristic said `[` means instance; a queue
declarator disproved it.** `item_t #(A, B) q[$];` read as an instance
array and died at `;`. The refinement — `[` is an instance range only when
its matching `]` is followed by `(` — is the same after-the-brackets test
the plain-ident branch already used. The classes README's "a wrong guess
cannot corrupt" argument still holds, and the statement-level twin already
did this correctly.
- **Two verification errors surfaced at the first corpus runs and both were
fixed rather than parked** (details under Assumptions). Both reproduce on
inputs with no dynamic-type syntax whatsoever, i.e. they are pre-existing
drops this round made reachable — the exact situation the classes round
hit with the `` `define`` lexer bug, resolved the same way: fix, pin with
cases, state it. `StmtKind::Assign` gained the comment slots a
`ContAssign`'s pairs already had; `NamedArg` gained the `close_comments` a
`Connection` already had. Neither touched `verify.rs`.
- **The case table was generated from real formatter output and then
reviewed**, not hand-typed: every expected block is the binary's own
output for the crafted input (each already runtime-verified for
equivalence + convergence by the format call itself), eyeballed against
house style before committing. 34 cases, every shape in the Goal table, in
module/class/package/typedef/function positions, with comments and an
`` `ifdef`` interleaved.
- **Corpus delta verified by path** (58 gained, 0 lost, 0 category changes),
per-target ledgers computed by joining the two TSVs, all 636 formattable
files round-tripped individually, TSVs byte-identical across three runs,
corpus repos confirmed clean. The `` `else`` 13 and `with` 7 next-blockers
were read at their sites and filed under Status/TODO with the evidence.
- **Scope discipline:** did not touch `verify.rs`, `fence.rs`,
`crates/vfmt*`, `crates/vlog_linter` (its `visit.rs` needed no arm — it
has no expression walk and its `Case` matches use `..`), `tools/`,
`corpus/`. The concurrent one-parse-two-tools agent's files churned in the
same tree throughout; `cargo fmt` was run per-package
(`-p vlog_parser -p vlog_formatter -p vlog_semantic`), never `--all`, and
the one transient `vfmt_server` test failure observed mid-round was
re-run and confirmed to be their in-flight edit, not this diff. Did not
run `git commit` / `git push`.
- **Session note:** the session was interrupted by a usage limit mid-way
through the `vlog_semantic` compile fixes and resumed; the tree state was
re-verified from disk before continuing (the missing piece was the
`bind_expr` `NamedArg` arm).
**Results:** `cargo test --workspace` **791 passed, 0 failed** (768 baseline
+ 13 `vlog_parser` unit + 7 `vlog_formatter` verification, + 3 the
concurrent agent landed mid-round; the case table grew 397 → 431 inside its
single test). `cargo clippy --workspace --all-targets` silent, 0 warnings.
`cargo fmt -p vlog_parser -p vlog_formatter -p vlog_semantic -- --check`
clean. Corpus: **636/820 formattable (77.6%**, up from 578/70.5%), **184
parse-error** (down from 242), **0 verification errors, 0 crashes, 0
regressions by path**; `tools/corpus_check.sh` exits 0.
Files touched: `crates/vlog_parser/src/{ast,parser}.rs`,
`crates/vlog_parser/tests/spans.rs`, `crates/vlog_formatter/src/format.rs`,
`crates/vlog_formatter/tests/verification.rs`,
`crates/vlog_formatter/tests/cases/dynamic_types.cases` (new),
`crates/vlog_semantic/src/bind.rs` (three small arms, documented under
Handshakes), `README.md`, `TODO.md`, this README.
### 2026-08-19 — dev agent, post-QA corrections (all four LOW findings)
- **QA-1 correction, for the record:** the earlier entry's claim that *both*
comment-drop fixes "reproduce on inputs with no dynamic-type syntax
whatsoever" was half-true. Only the assignment-operator drop is
pre-existing on HEAD. The named-argument `close_comments` gap was in this
round's own new code — `NamedArg` did not exist at HEAD, and the
`Connection` analog it is modelled on formats cleanly there. One
pre-existing bug fixed, one own-code gap caught and fixed inside the
round; the Assumptions section now states the split precisely. The earlier
entry above stands as written, per the append-don't-rewrite rule.
- **QA-2:** "no token this round targeted remains a first blocker" reworded
to "no *shape*" — `.` remains first in 2 files whose real blocker is
`foreach` over a hierarchical index; parked under Status/TODO with both
file:line cites.
- **QA-3:** the `$` row's next-blocker enumeration completed to all 13
(adding `import` at `dv_base_reg_field.sv:97` and `` `TX_IGNORED_PERIOD``
at `uart_scoreboard.sv:155`) and the phantom "lex error" removed — all 13
are parse errors.
- **QA-4:** every header in `dynamic_types.cases` was off by one for cases
1–32 (a 0- vs 1-indexed array slip in the generation script: case 1 had an
empty header, each later header described the case above it, case 32 had
none). Realigned all 32 and verified each header against its case's actual
content pair by pair, not by blind shifting; cases 33–34 were already
correct. `cargo test -p vlog_formatter` green after the edit
(`case_tables` still 431 cases), fmt clean.
- Also recorded QA-8's first-call-argument `[lo:hi]` dispatch asymmetry as a
parked item. No code changed in this pass — the four fixes are one test
data file and this README.
## QA log
### 2026-08-19 — QA
**Setup.** Verified in the merged working tree (the concurrent one-parse round
is uncommitted here too; its files were attributed, not flagged — see
*Attribution* below). Baseline binary: the dev's HEAD worktree at
`scratchpad/head-wt`, provenance re-verified — `git rev-parse HEAD` =
`e9008b680c2df86c7bea6d29095250958c132306`, `git status --porcelain` empty,
`cargo build --release` a no-op (binary genuinely fresh at `e9008b6`, md5
`feaa240d`). "New" binary: this tree's `target/release/vfmt` (md5 `957e2ad6`),
also confirmed up to date. `corpus/` never written to; all four corpus repos
`git status --porcelain` clean afterwards apart from the pre-existing
untracked `.vfmt-corpus-rev` stamps.
**Claim-by-claim.**
1. *All-structural; `verify.rs` / `fence.rs` untouched* — **PASS.**
`git diff --quiet` exits 0 for both, and md5 equality against
`git show HEAD:` confirms it independently
(`verify.rs` `18797ffb…`, `fence.rs` `b119bb8c…`). Nothing new is captured
verbatim, so hard invariant #4 does not bind. Verified anyway that the net
is load-bearing for every new shape — see *Sabotage* below.
2. *Corpus* — **PASS, reproduced end to end, every number.**
`./tools/corpus_check.sh corpus` (release, exit 0): **636/820 (77.6 %)**
formattable, 626 would-reformat, 10 ok-unchanged, **184 parse-error**, 0
verification-error, 0 other-error, 0 crash. HEAD-binary baseline over the
same corpus: **578/820 (70.5 %)**, 242 parse-error. TSV md5
**`e6f12eb7964e22e452655cf517cae766`** — exactly the README's value, and
byte-identical across **three** independent runs on this machine.
- **By path** (joined on the path column, all 820 rows matched):
`parse-error → would-reformat` **58**, `would-reformat → would-reformat`
**568**, `ok-unchanged → ok-unchanged` **10**,
`parse-error → parse-error` **184**, **any regression 0**.
- **Gained by tree**: `google_riscv-dv` 24, `lowrisc_ip` 14,
`opentitan/hw/ip` 8, `common_cells/test` 7, `ibex/dv/uvm` 4, `ibex/rtl` 1
— every figure reproduces.
- **Per-target ledger**, recomputed from the two TSVs: `$` 41 baseline-
blocked → **28 format, 13 advance**; `]` 23 → **6 / 17**; `.` 21 →
**17 / 4**; `inside` 7 → **7 / 0**. All four match.
- **New histogram** reproduces exactly: `interface` 25, `` `else`` 13,
`` `uvm_field_int`` 11, `'` 7, `with` 7, `"DPI-C"` 7, `$error` 6,
`virtual` 4, `export` 4.
- **Round-trip of all 636**, not sampled: copied to a scratch directory,
`vfmt format` in place (0 failures), then `vfmt --check` (0 failures) —
every one a verified fixed point.
- **Stronger than asked: all 578 previously-formattable files were
compared byte-for-byte old-vs-new**, not a 20-file sample.
`differing = 0` over 578 files (stdout and exit code both compared). No
regression by path *or* by bytes.
3. *The two comment-drop fixes* — **PASS on substance, with a documentation
correction (QA-1).**
- Assignment operator: **genuinely pre-existing, zero new syntax.**
`module m;\n initial begin\n instr[6:0] /* opcode */ = OPCODE_JALR;\n
end\nendmodule` refuses on the HEAD binary (`token stream diverges …
input has comment "/* opcode */"`) and formats cleanly now. Same for the
non-blocking twin `a /* l */ <= /* r */ b;`, and for multi-comment and
line-comment variants (`q[6:0] /* p1 */ /* p2 */ = /* r1 */ /* r2 */ 5;`,
`n /* nl */ = // rl` ⏎ `6;`) — all clean, all idempotent.
- Named-argument `close_comments`: **not reproducible without new syntax.**
The `Connection` analog `sub u (.src(5'd0 /* x0 */));` already formats
cleanly on the HEAD binary. See finding QA-1.
4. *`bind.rs` three arms; `vlog_linter` untouched* — **PASS.**
`git diff crates/vlog_semantic/src/bind.rs` is exactly three arms:
`TimingControl::Event(SensList::Bare(e))`, the `bind_dims` `DimKind` match
(`Range` binds `a`/`b` as before, `Dynamic`/`Wildcard` bind nothing —
correct, they hold no expressions), and
`ExprKind::NamedArg { value, .. }`. Nothing else in the crate changed.
**Attribution:** `crates/vlog_linter/{src/context.rs,src/lib.rs,tests/rules.rs}`,
`crates/vfmt/src/lint.rs`, `crates/vfmt_server/{lint,state}.rs` are the
one-parse round's own file list (its README §Handshakes / §Work log), and
`crates/vfmt_server/src/diagnostics.rs` is the lead's QA-1 fix recorded in
that round's Review §4. `git diff crates/vlog_linter/` contains **no**
dynamic-types symbol (`DimKind`/`NamedArg`/`SensList`/`inside`/
`op_comments`) — this feature really did not touch it.
5. *Gates* — **PASS.** `cargo test --workspace` **791 passed, 0 failed**
(re-run after all sabotage was reverted: still 791/0).
`cargo clippy --workspace --all-targets` **zero warnings** — re-run after
`touch`ing all four changed source files so it could not be a cache
replay. `cargo fmt -p vlog_parser -p vlog_formatter -p vlog_semantic --
--check` clean, and `cargo fmt --all -- --check` clean too. The case table
holds **34** cases (33 `====` separators + 1). Seven new
`tests/verification.rs` tests (6 rejection + 1 acceptance) present and
green; the spans walker's `NamedArg` arm and both new `SOURCES` entries are
present and exercised — proven load-bearing by sabotage 5 below.
**Attacks (release binary; every probe formatted, re-formatted and, where it
succeeded, re-parsed by the net's own equivalence + convergence check).**
- *The `$` primary.* `q[$]`, `q[$-1]`, `q[$:2]`, `q[0:$]`, `[$:8]`,
`q[$][$][$]`, `{$, $}`, `[$]` behind three unpacked ranges — all format and
are idempotent. **Illegal positions are accepted and round-trip losslessly**:
`assign x = $;`, `x = $ + 1;`, `x = $$;`, `f($, $)`, `logic [$:0] w;` all
emit the same tokens back. That is consistent with the documented
Assumption ("vfmt does not check legality anywhere else either") and cannot
corrupt. **No identifier collision:** `int $;` is a parse error
(`expected identifier (found "$")`), so `$` cannot be declared.
`$display`/`$bits(int)`/`$error`/`$time`/`$finish` are byte-unaffected.
- *`DimKind`.* `[]`, `[*]`, `[8]`, `[7:0]`, `[string]` and the nested
combinations `[][$][7:0]`, `[$][*][]`, `[][][][][$][*][7:0]` in **every**
declaration position — module net, class property, class-function local,
`typedef`, function/task argument in every direction, module parameter port,
ANSI port, `localparam`. All format, all idempotent, HEAD parse-errors every
one of them. The spacing (`wire d [7:0];`) is **pre-existing house style**,
confirmed byte-identical old-vs-new on a plain `[7:0]`/`[3][4]` declaration.
- *`NamedArg`.* `f(.a(x), .b())`, `.a()` empty, named-in-`$display`
(`$display(.fmt("%d"), .v(x))`), scoped callees, and **mixed positional +
named in both orders** (`g(x, .b(y))`, `h(.a(x), y)`) all parse — SV forbids
the mix, vfmt accepts it and emits the same tokens, matching the documented
"vfmt is not a legality checker" stance. A nested `k(.a(.b(x)))` is a parse
error (refusal, safe). **Disambiguation holds:** `sub #(.W(8), .D()) u0
(.clk(clk), .d(), .q(q));`, `sub u1 (.*);` and `sub u2 (.a(1), .b);` are
byte-identical old-vs-new — instantiation connections still take the
`Connection` path. Comment slots: see QA-6.
- *`case … inside`.* Range labels, mixed `[1:5], 7, [9:11]`, plain labels,
`default`, `casex … inside`, `unique case … inside`,
`priority casez … inside`, inside a class method, and a plain `case` with a
`[1:2]:` label (illegal SV, accepted, same tokens out) — all format and
re-parse. Head-trailing, item-leading, item-trailing and dangling comments
all survive in source order. `[1:2][3:4]:` is a parse error (safe).
- *`SensList::Bare`.* `@ev;` and `@hier.a.b;` format without parens; `@(ev)`,
`@(posedge clk)` and `@(*)` keep their own spellings; `x = @ev y;`
(intra-assignment) works. **The old refusal is real and is fixed:** on the
HEAD binary the whole probe file dies at `@hier.a.b`, and `@ev` alone was
the invented-parens refusal the work log describes. Noted in passing:
`always @* y = x;` still prints `@(*)` and is **accepted** — that is a
pre-existing `verify.rs` normalization, byte-identical on the HEAD binary,
untouched by this round.
- *`at_macro_item` ident-dot.* The `` `WAIT_FOR_RESET`` ⏎ `cov.cg.sample(a, b);`
shape formats (HEAD: `expected ';' (found ".")`). Counter-cases all keep
their old reading: `` `MY_TYPE x = 1;``, `` `MY_TYPE y;``, `` `M2 #(1) n;``.
The clause can only fire where HEAD had a parse error, and a wrong guess
emits the same tokens (`` `M3 z.w = 2;`` round-trips).
- *`parse_ident_item` bracket lookahead — the highest-risk edit, attacked
hardest.* `sub #(8) u [3:0] (.a(x), .b(y));`, `sub2 v [1:0] (.c(z));` and
`sub3 #(.W(4)) w [N-1:0] ();` are **byte-identical old-vs-new** — instance
arrays are untouched. **Comments between `]` and `(` do not fool the
lookahead** (`sub #(8) u [3:0] /* c */ (.a(x));` and the `// c` ⏎ `(...)`
variant are both byte-identical old-vs-new): the token vector holds no
comment tokens, so `scan_matching`'s "next token is `(`" test is safe.
`sub #(8) u [3:0];` and `item_t #(A, B) r[3:0];` move from parse-error to a
declaration — strict gains, same tokens out. The 578-file byte-identity run
is the empirical proof that nothing already parsing changed reading.
- *Empty `{}` and value ranges.* `{}`, `{{}}`, `{{}, {}}`, `'{}`, `{3{{}}}`,
`{} + 1`, `{[1:2]}`, `{3{[1:2]}}`, `y inside {[1:2], 3}` — all format and
are idempotent; nonsense in, same nonsense out.
- *Everything at once, three passes.* A 35-line file combining queues, bounded
queues, dynamic/wildcard/string/typed-key associative arrays, a
parameterized-type queue declarator, `$`-indexing, `new[n]`, `{}`,
assignment-operator comments on both sides, named args with `close_comments`,
`case … inside`, both bare event controls, the macro-then-`cov.` shape, and
an `` `ifndef``/`` `endif`` wrapper: **format(format(format(x))) == format(x)**,
and all six embedded comments present in the output.
- *Lint path over the new syntax.* `vfmt check` over the probe files runs
clean and `case-missing-default` correctly fires on `case … inside`. See
QA-7 for the corpus-wide `vfmt check` delta.
**Sabotage (each applied, caught, reverted, and the revert proven by `cmp`
against a pre-sabotage byte copy).**
1. `op_comments` not printed → `cases.rs` fails at `dynamic_types.cases:397`
with the net's own message (`input has comment "/* opcode */"`).
2. `close_comments` not printed → fails at `:414`
(`input has comment "/* x0 */"`).
3. `inside` not printed → fails at `:264` and `:285`
(`input has keyword "inside"`).
4. `DimKind::Dynamic` printed as `[*]` → fails at five separate cases
(`:81`, `:92`, `:101`, `:128`, `:139`).
5. `NamedArg::name_span` shifted one byte left → `spans.rs`
`every_node_span_nests_inside_its_parent` fails with *"the named argument
span does not slice back to its name", left: `".ptr"`* — the new walker arm
is genuinely load-bearing, not decorative.
Every one is caught by the **runtime safety net** (equivalence/convergence
inside `format_source`), not merely by an expected-output mismatch — which is
the property that matters for invariants #1 and #3. After the last revert:
`format.rs` md5 `90530948…` and `parser.rs` md5 `37323362…` both equal their
pre-sabotage copies, and `cargo test --workspace` is back to **791 passed, 0
failed**.
**Findings.**
- **QA-1 (LOW — documentation accuracy).** Assumptions says of the two comment
drops: *"Both reproduce on inputs with no new syntax in them."* Only the
first does. The second — a comment before a named argument's `)` — cannot
reproduce at HEAD, because `ExprKind::NamedArg` did not exist there; the
`Connection` analog it is modelled on (`sub u (.src(5'd0 /* x0 */));`)
formats **cleanly** on the HEAD binary (verified both binaries, identical
output, exit 0). Accurate framing: *one* pre-existing drop was fixed
(the assignment operator), and *one* gap in this round's own new code was
caught and fixed inside the round — which is good practice, just not the
same category. Worth correcting because invariant #3's history is exactly
what CLAUDE.md asks agents to keep honest.
- **QA-2 (LOW — documentation accuracy).** Corpus results claims *"No token
this round targeted remains a first blocker anywhere."* `.` remains the
first blocker in **2** files, both advanced from `]`:
`corpus/ibex/vendor/google_riscv-dv/src/riscv_callstack_gen.sv:183`
(`foreach(program_h[id].sub_program_id[k])`) and
`.../riscv_page_table_list.sv:130` (`foreach(page_table[i].pte[j])`). The
*shape* this round targeted (named call arguments) is indeed gone
everywhere; the token is not. Suggested wording: "no *shape* this round
targeted".
- **QA-3 (LOW — documentation accuracy).** The `$` row's next-blocker
enumeration ("`with` 3, one each: `assert`, `@`, `;`, `,`, `::`,
`` `else``, a covergroup cross, a lex error") accounts for 11 of the 13
advanced files, and the "lex error" is not among them — all 13 are parse
errors. The full recomputed set is: `with` 3; and one each of `assert`
(`fifo_tb.sv:155`), `@` (`stream_register_tb.sv:75`), `;`
(`ibex_cosim_scoreboard.sv:307`), `,`
(`ibex_debug_triggers_overrides.sv:116`), `::` (`riscv_instr.sv:156`),
`cp_sign_cross` (`riscv_instr_cover_group.sv:514` — the covergroup cross),
`` `else`` (`riscv_instr_pkg.sv:1252`), **`import`**
(`dv_base_reg_field.sv:97`) and **`` `TX_IGNORED_PERIOD``**
(`uart_scoreboard.sv:155`). The last two are unlisted.
- **QA-4 (LOW — test hygiene, not fixed: outside this agent's write scope).**
Every case header in `crates/vlog_formatter/tests/cases/dynamic_types.cases`
is **off by one** for cases 1–32: case 1 carries an empty `# ` header, and
each subsequent `#` line describes the *previous* case (line 12 "queue-typed
class properties, with and without qualifiers" sits above the
function-locals case; line 264 "a named-argument list that does not fit
breaks one per line" sits above a `case … inside` case; and so on). Cases 33
and 34 are labelled correctly, and case 32 (the `static`/`local` queue
properties) has no description at all. Harmless to behavior — the harness
ignores the text — but the labels are what a future failure prints, and
sabotage 3 above duly reported a `case … inside` failure under the
named-argument-list heading. Mechanical fix: shift headers 2–32 up one slot
and write one for case 32.
- **QA-5 (INFORMATIONAL — pre-existing, byte-identical on HEAD, out of
scope).** Two comment shapes adjacent to the fixed one still refuse, and
refuse *identically* on the HEAD binary, so this round neither caused nor
widened them:
- `assign a /* l */ = /* r */ b;` — a **continuous** assignment has
`rhs_comments` but no `op_comments`, so the operator-side comment is still
dropped and the net refuses. This is the exact twin of what landed on
`StmtKind::Assign`; worth naming because Assumptions describes the fix as
mirroring "a continuous assignment's `rhs_comments` use", which may read as
if the continuous form were already whole.
- `w <= #1 /* d */ 3;` and `v = @(posedge clk) /* e */ 4;` — `rhs_comments`
is taken immediately after the operator, *before* the intra-assignment
timing control is parsed, so a comment between the timing control and the
RHS is still lost and refused.
- **QA-6 (INFORMATIONAL — parity confirmed, not a new refusal class).**
`f(.a(/* in */ x))` (comment between `(` and the value) and
`f(.a /* mid */ (x))` (comment between the name and `(`) are refused by the
net — comments relocated across a token, never dropped from the output.
Both refuse **byte-identically** in the `Connection` form on the HEAD binary
(`sub u (.a(/* in */ x));`, `sub u (.a /* mid */ (x));`, same divergence
indices). So `NamedArg` inherits `Connection`'s comment behavior exactly, as
Handshakes promises — including its pre-existing limitation. The shapes that
*do* work in a connection also work in a named argument (`.a(x /* post */)`,
`.a(/* only */)`, `.a(x // line` ⏎ `)`).
- **QA-7 (INFORMATIONAL — cross-round note for the lead).** `vfmt check
corpus` differs from the HEAD binary by **10 lines, net +6 findings** (7921
→ 7927), entirely as a consequence of files that now parse: 7 new, correct
`case-missing-default` findings on `case … inside` statements, and at
`corpus/ibex/vendor/google_riscv-dv/src/isa/riscv_zbb_instr.sv` one
**spurious** old finding (`187:5: generate 'case' has no 'default'` — line
187 is an `endcase`, i.e. an error-recovery artifact) replaced by three
correct ones (`26:5`, `140:5`, `195:9`). Strictly an improvement, and
Handshakes' "Required of `vlog_linter`: nothing" is correct *at the
compilation level*. Flagged only because the concurrent one-parse round
proved its lint output byte-identical against a tree that did not contain
this round: in the merged tree `vfmt check` output is no longer identical to
`e9008b6`'s, and those 10 lines are why.
- **QA-8 (INFORMATIONAL).** A `[lo:hi]` value range is accepted at every
expression-element position **except the first call argument**:
`f([1:2])` is a parse error while `f(x, [1:2])` parses, because the postfix
`(` branch's first-argument dispatch gained the `.` case but not the `[`
case. No legal SystemVerilog is affected (a value range is not a call
argument), and `case … inside` labels are unaffected — their list goes
through `parse_expr_item` at **every** position including the first, which
probes confirm (`[1:5]:` as the first label of the first item formats).
Noted so the asymmetry is not mistaken for a bug later.
**Verdict: no BLOCKING findings.** No regression by path (0/820) and none by
bytes (578/578 previously-formattable files byte-identical old-vs-new); no
comment loss anywhere — every comment-adjacent shape either round-trips or is
refused by the untouched safety net, and five sabotages confirm the net, not
luck, is what holds invariants #1 and #3 for the new shapes; no `$` misparse —
`$` is a leaf that cannot collide with an identifier and emits the same token
wherever it stands. All five claims verified independently, including the
corpus TSV md5 `e6f12eb7964e22e452655cf517cae766` reproduced three times. The
findings above are four documentation/hygiene corrections and four notes; none
of them change the shipped behavior.
## Review
**2026-08-19 — lead. Verdict: accepted after one fix pass; commits
jointly with one-parse (round 19). Corpus 70.5% → 77.6% formattable —
the second-largest jump in the project — with everything structural
and nothing verbatim.**
Points reviewed and accepted:
1. **`$` as an expression primary** is the round's insight: one
grammar addition and queues, bounds, and `$`-arithmetic indexes all
fall out of machinery that already existed. QA attacked it at
illegal positions and found no identifier collision and lossless
round-trips. `DimKind` as the one non-additive AST change had
exactly three consumers, all updated — blast radius measured before
the cut.
2. **Fixing the newly-reachable comment drops instead of parking
them** — with the honest post-QA split: one was genuinely
pre-existing on HEAD, the other was this round's own new code
caught inside the round. The dated correction entry (rather than
rewriting the work log) is how the record should be amended.
3. **The QA-4 root cause** (a 0-vs-1-indexed array slip in a header
generation script) was traced, not patched around, and the
realignment verified against case *content* including the four
ambiguous `task t;` quartuplets. Tooling that generates test
artifacts is code too.
4. **By-path discipline throughout**: 58 gained / 0 lost / 0 category
changes, all 636 round-tripped, all 578 previously-formattable
files byte-compared old-vs-new with zero differences — the
regression bar at its strongest.
5. **QA-7's cross-round interaction recorded here**: this round's
`case inside` support correctly grew the lint corpus baseline by
net +6 (real case-missing-default findings in newly-parsing code,
plus a recovery-artifact swap for the better). one-parse's
byte-identity claim was measured before this round landed; both
claims are true at their respective tree states.
Parked with evidence and cites: `foreach` over hierarchical indexes
(2 files), the `f([1:2])` first-argument dispatch asymmetry (no legal
SV affected), `randomize() with` (7 files, the constraint-verbatim
vehicle when taken), and the new top blockers — `interface` (25) and
the `` `else`` head-swap shape (13) — which are the next parse
frontier when wanted.
+7 -1
View File
@@ -95,6 +95,10 @@ existed.
tools" is **not** done; `check` and `format` each call the parser. Nothing in
this crate's API prevents sharing a parse later — `LintContext` is the only
thing that would need to accept a pre-built tree.
~~is **not** done~~ **Delivered by one-parse (round 19):
`LintContext::from_parse` accepts pre-built products, `ParsedSource::parse`
is the parse-once bundle, and both `vfmt check` and the server lint from
one parse — see `docs/features/one-parse/README.md`.**
## Status / TODO
@@ -125,7 +129,9 @@ existed.
of scope this round; needs a file format, a discovery rule and a
precedence story against inline waivers.
- [ ] `lint` config key in `vfmt.toml` — handshake above.
- [ ] One parse shared by `check` and `format` — handshake above.
- [x] One parse shared by `check` and `format` — handshake above.
**Delivered by one-parse (round 19)** for the linter's consumers;
`format` keeps its own strict parse by design.
- [ ] Naming rules by regex, `--generate_markdown` rule reference, `--explain`
(`Rule::doc` exists so these can be generated, but nothing generates
them yet).
+515
View File
@@ -0,0 +1,515 @@
# one-parse
## Goal
TODO §4's "one parse, two tools", delivered on the linter side: parse a file
once and lint from those products, instead of every consumer re-lexing and
re-parsing text somebody already parsed. `LintContext` gains a constructor
that accepts pre-built parse products; `vfmt check` builds the products once
per file; and `vfmt_server` — which already holds a fully analyzed `Document`
per buffer — lints from that document's own tokens and tree rather than
paying two extra lexes and an extra tolerant parse per keystroke. Behavior is
the hard gate: every finding, position, fix, diagnostic and exit code is
byte-identical to before; only duplicated work is removed.
## Assumptions
- **Behavior identity over speed.** Anywhere "share the parse" and "identical
output" could conflict, identity wins. Concretely: on a file that fails to
*lex*, the shared-parse paths fall back to `parse_source_tolerant` (which
re-lexes the rare broken file once more) rather than hand-rolling the
lex-error tree, so the tree and diagnostics are the old code path's own.
- **The token stream and the tree are two products, and the parser consumes
its tokens.** `parse_tolerant(tokens, source)` takes `Vec<Token>` by value,
so a consumer that needs both (the linter does: waivers and text rules read
tokens, AST rules read the tree) clones the token vector once. One clone is
cheaper than the lex it replaces, and changing `vlog_parser`'s signature is
out of scope (that crate is another round's).
- **`SourceFile` is not `Clone`.** This is what forces the borrowing design
below: the server's `Document` owns one tree that must serve semantics,
diagnostics *and* linting, so the lint context has to borrow it —
`std::borrow::Cow` cannot hold a non-`Clone` type, and a per-request tree
clone is exactly the duplicated work this round removes.
- **Parse diagnostics are not a lint product.** No rule reads them
(`LintContext::new` always discarded them), so `from_parse` does not take
them and `ParsedSource` does not store them. The server, which does publish
them, keeps them where they always were: on `Document`.
- **The `--fix` loop's per-round re-parse is inherent.** Each round rewrites
the text, and products of the old text describe nothing. Only the *first*
round of `vfmt check --fix` (and all of a plain `vfmt check`) saves work.
- **Per-change recompute stays the server's model.** This round removes
duplicate work *within* one change/request; it adds no caching or
invalidation machinery beyond what `Document` already is (TODO §6:
"per-file recompute is fine at Verilog file sizes").
## Handshakes
**Promised by `vlog_linter`** (additive; everything previously public is
unchanged in behavior):
- `LintContext` is now `LintContext<'a>`. Rule authors are untouched: the
`Rule::check(&self, ctx: &LintContext)` signature, and every accessor
(`source()`, `tokens()`, `file()`, `line_index()`, ...), read exactly as
before — the lifetime elides.
- `pub fn LintContext::from_parse(source: &'a str, tokens: &'a [Token],
file: &'a SourceFile, line_index: &'a LineIndex, path: Option<PathBuf>)
-> LintContext<'a>` — the pre-built-products constructor linter-core's
Handshakes predicted. Borrows everything big; `path` stays owned because a
`PathBuf` clone per lint run is noise. **Caller contract (documented at the
item): the four products must describe the same text** — tokens lexed from
`source`, `file` the tolerant parse of those tokens, `line_index` built
over `source`. `Document` and `ParsedSource` both satisfy it by
construction.
- `pub struct ParsedSource` + `ParsedSource::parse(source) -> ParsedSource` +
`ParsedSource::context(&self, path) -> LintContext<'_>` — the owned bundle
of products for callers with no `Document` of their own (`vfmt check`, and
`run`/`LintContext::new` internally). `parse` lexes **once** and builds the
tree from a clone of the token stream.
- `LintContext::new(source, path)` **stays**, as the convenience wrapper the
task requires: it is one line, `Backing::Owned(ParsedSource::parse(source))`
through the same private assembly `from_parse` uses — a single code path
derives the string-literal spans and defaults. (`new` cannot literally call
`from_parse` and then own the products — that would be a self-borrow — so
"single code path" is the shared assembly function, and `ParsedSource::parse`
is the single place the parse recipe lives.)
- Dependency list unchanged: `vlog_parser` + std.
**Consumed**
- `vlog_parser::parse_tolerant(tokens, source)` — newly consumed by
`vlog_linter` and `vfmt_server` (both already depended on the crate; it was
already `pub`). Relied on: with the same tokens it returns exactly the tree
`parse_source_tolerant(source)` would (that function *is* `tokenize` +
`parse_tolerant`), and on a well-formed file the tree equals `parse`'s.
- `vlog_formatter::fence::protected_regions(&str)` — still called with text,
still re-parses internally, **on purpose**; see the decision below.
**Changed call sites**
- `crates/vfmt/src/lint.rs::run_rules` — parses once via `ParsedSource` and
hands the products to the context.
- `crates/vfmt_server/src/state.rs::Document` — gains the `tree: SourceFile`
field (it was parsed and thrown away after `analyze`), and `Document::new`
lexes once instead of twice.
- `crates/vfmt_server/src/lint.rs::{violations, fixable}` — the one call site
server-lint's README predicted: both lint from the document's own products
via `from_parse` instead of re-parsing `doc.text`.
## The server's redundant-work catalog
Every place the server re-tokenized or re-parsed text it already held
products for, per request, as of the start of this round:
| Site | Duplicate work per request | Verdict |
|---|---|---|
| `lint::violations` (every didOpen/didChange/didSave publish) | 2 lexes + 1 tolerant parse of `doc.text` (via `vlog_linter::run` → `LintContext::new`) | **Eliminated** — `from_parse` over `Document`'s products |
| `lint::fixable` (every codeAction request) | 2 lexes + 1 tolerant parse (via `LintContext::new`) | **Eliminated** — same |
| `lint::fixable` → `fence::protected_regions(&doc.text)` | 1 lex + 1 tolerant parse inside `vlog_formatter` | **Kept** — see the protected_regions decision below |
| `Document::new` (every buffer change) | the text lexed twice: `tokenize` for `doc.tokens`, then `parse_source_tolerant`'s internal `tokenize` | **Eliminated** — one lex, tree built by `parse_tolerant` over a clone of the tokens; the lex-error fallback still goes through `parse_source_tolerant` so the error tree and diagnostic are byte-identical |
| `format::formatting` / `range_formatting` | `format_source`/`format_range` lex+parse strictly inside `vlog_formatter` | **Kept** — the formatter's parse is the *strict* one (a tree `Document` does not hold), and the runtime safety net (equivalence + convergence) is defined over `format_source` doing its own work; sharing would need `vlog_formatter` API changes, which is the concurrent round's crate and a different feature |
| `Workspace::rebuild_index` (initialize + every didSave) | re-reads and re-parses every workspace file inside `WorkspaceIndex::build`, open unchanged buffers included | **Kept** — the documented full-scan index model (TODO §6 defers incrementality to salsa); making it incremental is invalidation machinery this round explicitly must not build |
| `semanticTokens`, `hover`, `definition`, `references`, `documentSymbol`, `workspace/symbol`, `diagnostics::diagnostics` | none — all already read `doc.tokens` / `doc.semantics` / `doc.defines` / `doc.diagnostics` | already clean (verified by grep for `tokenize`/`parse` over `crates/vfmt_server/src`) |
## The protected_regions decision: left alone
`fence::protected_regions` takes `&str` and re-parses internally.
shared-fence-filter's Assumptions choose that signature deliberately: a
products-accepting variant would let the two front ends feed different trees
and get different fence answers, which is the exact drift that feature exists
to end. Could this round argue both callers "always hold the same tree by
construction"? Almost — the server would pass `doc.tree` and the CLI its
current round's tree — but "almost" is the problem: the CLI's `--fix` loop
rebuilds text every round, and a future caller passing last round's tree is
precisely the bug the `&str` signature makes unwritable. The cost lands only
on fix-application paths (`vfmt check --fix`, `textDocument/codeAction`),
never on the per-keystroke diagnostics path. Two further reasons to leave
it: it is `vlog_formatter`'s code, which belongs to the concurrent
dynamic-types round this session; and the interior parse is of the *current*
text by construction, which is the property being bought. **Decision: keep
the double parse there, documented as the acceptable price of one fence
answer.**
## Status / TODO
- [x] `vlog_linter`: `LintContext<'a>`, `from_parse`, `ParsedSource`,
`new` kept as the wrapper; single-lex parse recipe in one place.
- [x] Rules, visitors, waivers untouched (they compile and read unchanged).
- [x] `crates/vfmt/src/lint.rs`: `run_rules` parses once via `ParsedSource`.
- [x] `crates/vfmt_server`: `Document.tree` kept; `Document::new` single-lex;
`lint::violations`/`fixable` lint from the document's products.
- [x] Server catalog above; semanticTokens/hover verified already clean.
- [x] protected_regions decision written (left alone).
- [x] Tests: products-in == source-in property over rule-test inputs;
lex-error and broken-file paths; existing CLI + server suites green
**unmodified**.
- [x] Byte-identity: corpus `vfmt check` (text + JSON) vs a HEAD worktree
binary; server diagnostics vs a HEAD worktree binary over a real stdio
session.
- [x] Timing before/after.
- [x] TODO §4 checkbox + linter-core / server-lint annotation lines.
- [ ] **Not done, deliberately:** `vfmt format` sharing the parse. The
formatter requires a *strict* parse and runs its safety net over its own
products; wiring `vfmt check --fix --format` workflows is a future
feature and is not blocked by anything here.
- [ ] **Not done, deliberately:** any caching/invalidation in the server
beyond `Document`'s per-change recompute.
## Work log
### 2026-08-19 — dev
- Read `CLAUDE.md`, TODO §4, and the linter-core / server-lint /
shared-fence-filter READMEs in full (QA logs and Reviews included) before
writing anything, then the code: `vlog_linter`'s `context.rs`/`lib.rs`,
`crates/vfmt/src/lint.rs`, and every file in `crates/vfmt_server/src`.
- **The design was forced by one fact: `SourceFile` is not `Clone`.** The
server's `Document` owns one tree that must serve semantics, published
diagnostics *and* linting, so the products constructor has to borrow —
and the task's requirement that `LintContext::new(source, path)` survive
as a self-contained convenience means the context must also be able to
own. Hence the private `Backing` enum (`Owned(ParsedSource)` /
`Borrowed { .. }`) rather than `Cow` fields (`Cow` needs `Clone`) or a
lifetime-only struct (which would have killed `new`). Every accessor
signature is unchanged, so the twelve rule files, `visit.rs` and
`waiver.rs` compile byte-for-byte untouched — verified by `git diff`
(only `context.rs`, `lib.rs`'s one `pub use` line, and the test helper
changed in the crate).
- **`new` cannot literally call `from_parse`** — that would borrow a local
and return it — so the single code path is `assemble` (one place derives
string-literal spans and defaults) plus `ParsedSource::parse` (one place
holds the parse recipe). Recorded here so nobody "fixes" it into a
self-borrow later.
- **The single-lex recipe and its one deliberate exception.** Today's
`LintContext::new` lexed the text twice (its own `tokenize`, then
`parse_source_tolerant`'s internal one). `ParsedSource::parse` and
`Document::new` now lex once and build the tree via
`parse_tolerant(tokens.clone(), source)` — identical tree by definition,
since `parse_source_tolerant` *is* `tokenize` + `parse_tolerant`. A text
that fails to lex keeps the old `parse_source_tolerant` path (a second lex
of a rare broken file) because `parser::error_file` is `pub(crate)` and
hand-rolling the all-error tree here is how two subtly different trees
are born. The recipe exists in exactly two places because they need
different outputs: `ParsedSource` discards diagnostics (no rule reads
them), `Document` publishes them.
- Server: `Document` gained the `tree: SourceFile` field it was already
paying to build (it parsed, analyzed, and threw the tree away);
`lint::violations` and `lint::fixable` now share a four-line `context(doc)`
helper over `from_parse`. `vlog_linter::run` is no longer imported there.
The catalog above was compiled by grepping `tokenize|parse` over
`crates/vfmt_server/src` and reading each hit.
- **Tests.** The products-in == source-in property was put where it covers
the most ground: inside the rule-test harness's `assert_lint_with`, so all
55 inline-marker cases (every rule × fires/quiet/waived/unused-waiver,
plus the fence and class-body cases) assert that `ParsedSource` products
produce a `Debug`-identical violation list — rule, message, span and fix.
Two new unit tests in `context.rs`: borrowed-vs-owned accessor equality,
and the lex-error fallback producing the exact old error tree. Existing
CLI and server suites pass **unmodified** (`git diff` on
`crates/vfmt/tests`, `crates/vfmt_server` tests: empty).
- Did not touch `vlog_parser`, `vlog_formatter`, `vlog_semantic`,
`vfmt_core`, `editors/**`, or any `Cargo.toml`/`Cargo.lock` (no dependency
moved; `parse_tolerant` was already `pub`). Did not run
`git commit`/`git push`.
- **Concurrency note.** A dynamic-types round was announced live in
`vlog_parser`/`vlog_formatter` this session. `git status` stayed clean of
their crates for the whole round (only this feature's files are modified),
so the scratchpad-copy fallback was prepared but never needed; the HEAD
worktree used for baselines doubles as the clean snapshot. Gates below are
from the real tree.
**Results.**
- `cargo test -p vlog_linter`: 118 unit + 55 integration + 1 doctest, green
(118 was 116: the two new `context.rs` tests). `cargo test -p vfmt`:
green including all 69 CLI integration tests, unmodified.
`cargo test -p vfmt_server`: 115 unit + 6 e2e, green, unmodified.
`cargo test --workspace`: **770 passed, 0 failed**.
- `cargo clippy --workspace --all-targets`: silent. `cargo fmt -p
vlog_linter -p vfmt -p vfmt_server -- --check`: clean (scoped, per the
concurrency rule). No `#[allow]`, no `unwrap`/`expect`/`panic!`/`unsafe`
outside `#[cfg(test)]` in anything touched.
- **Byte-identity, CLI** (HEAD worktree binary at `e9008b6` vs this tree,
both release):
- `vfmt check corpus/`: stdout, stderr and exit code (1) identical.
- `vfmt check corpus/ --output-format json`: **2 418 071 bytes of JSON,
byte-identical**, stderr identical, exit identical.
- `check --fix` over ten crafted shapes in twin directories (tabs +
trailing whitespace, fence, fence-in-broken-file, waiver, lex failure,
case-missing-default, module-filename mismatch, multi-byte + tab,
unclosed fence, empty file): every rewritten file byte-identical,
stdout/stderr identical (paths normalized), exit 1 from both.
- **Byte-identity, server**: a real stdio session (hand-framed JSON-RPC,
`scratchpad/lsp_probe.py`) over three scratch files — lint-only, parse
error + lint + module-filename, and error-recovery + fence + lex-error —
each opened and then edited once (edits flip the filename rule, add a
waiver, and heal the lex error). All **6 published diagnostic lists
byte-identical** between the two binaries, canonicalized only by
stripping the differing scratch-dir prefix from the URI.
- **Timing, CLI** (release, median of 7, 860-file corpus):
`vfmt check corpus/` **265.5 → 207.9 ms** at `--threads 1` (−22 %),
**79.7 → 70.5 ms** at the default thread count (−12 %). The single-thread
number is the honest one (the pool hides latency); the saving matches the
arithmetic — the lint pipeline did 2 lexes + 1 parse per file and now does
1 lex + 1 token-clone + 1 parse.
- **Timing, server** (informational): didChange → publishDiagnostics,
median of 15 full-text changes, empty workspace root:
`picorv32.v` (3049 lines) **18.0 → 11.0 ms**, `ibex_core.sv` (2026 lines)
**7.6 → 3.4 ms**. Larger than the CLI's relative win because the server
was paying the duplicate work twice over — `Document::new`'s double lex
*and* the lint path's full re-lex-and-parse — and now pays one lex, one
clone, one parse per change.
### 2026-08-19 — dev (post-interruption verification)
- The session was cut by a usage limit after the results above were captured;
on resume, disk state was re-verified intact (all six code files, this
README, TODO §4, both annotation files — nothing lost).
- Mid-resume the concurrent dynamic-types round landed in-progress edits to
`vlog_parser`/`vlog_formatter`/`vlog_semantic` that briefly broke the
workspace *test* build (`tests/spans.rs` vs their new `ExprKind::NamedArg`
— their crate, their fix). Gates were therefore re-run with the
scratchpad-copy technique: a fresh worktree at HEAD `e9008b6` with **only
this round's six files** overlaid — `cargo test --workspace` **770 passed,
0 failed**, `cargo clippy --workspace --all-targets` **silent**, scoped
`cargo fmt -- --check` **clean**. Identical numbers to the pre-drift
merged run recorded above.
- The merged tree recovered while this was running (the other agent fixed
their spans test): merged `cargo test --workspace` **770 passed, 0
failed**, clippy clean, as of this writing — noted with the caveat that
their round is still in motion, so the isolated-copy numbers are this
feature's own evidence.
- Provenance of the identity/timing evidence above: captured **before** any
concurrent drift existed — at capture time `git status` showed only this
round's files modified, so the "new" binaries were exactly HEAD +
one-parse, vs. the HEAD-worktree baseline binaries. That evidence stands
as recorded.
## QA log
### 2026-08-19 — QA
**Setup / isolation.** The concurrent dynamic-types round had by now modified
`vlog_parser/src/{ast,parser}.rs`, `vlog_parser/tests/spans.rs`,
`vlog_formatter/src/format.rs`, `vlog_formatter/tests/verification.rs` and
`vlog_semantic/src/bind.rs` in the shared tree, so every gate and every
identity run below was done in an **isolated copy**: `scratchpad/qa-new` =
a byte copy of the dev's HEAD worktree (`scratchpad/head-wt`, verified clean
at `e9008b6`) with **exactly this round's six code files** overlaid.
`diff -rq head-wt qa-new` reports those six files and nothing else. The
baseline binaries are `head-wt/target/release/{vfmt,vfmt-server}`; the "new"
ones were rebuilt from `qa-new`. `corpus/` was never written to — the `--fix`
runs used copies.
**Claim-by-claim.**
1. *Constructor design* — **PASS.** `SourceFile` is `#[derive(Debug)]` only at
`e9008b6:crates/vlog_parser/src/ast.rs:125`, so `Cow` is genuinely
unavailable and the `Backing` enum is forced. `git diff --name-only HEAD --
crates/vlog_linter` returns exactly `src/context.rs`, `src/lib.rs`,
`tests/rules.rs` — all twelve rule files, `visit.rs`, `waiver.rs`,
`registry.rs`, `naming.rs`, `violation.rs`, `rule_docs.rs` byte-untouched.
`crates/vlog_linter/Cargo.toml` still lists `vlog_parser` and nothing else.
Diagnostics genuinely unread by any rule: `grep -rn diagnostic
crates/vlog_linter/src` hits only doc comments, the discarded binding at
`context.rs:46`, and `visit.rs`'s own `#[cfg(test)]` block. `new` →
`assemble` is the single path, and `parse_source_tolerant`'s Ok arm at
`e9008b6:crates/vlog_parser/src/lib.rs:37` is literally
`parse_tolerant(tokens, source)`, so the substitution is exact by
definition, not by hope.
2. *`ParsedSource::parse` lexes once; lex errors fall back* — **PASS.**
Independent probe (scratch `tests/qa_probe.rs`, deleted after the run) over
four lex-failing texts — unterminated block comment, unterminated string,
a bare `"`, a `/*` at EOF: tokens empty in every case, the `Debug` form of
`ParsedSource::parse(src).context(None).file()` equal to
`parse_source_tolerant(src).0`, and `run(src, …)` equal to
`lint(&parsed.context(None), …)`. End to end the same fallback shows up in
the server session below (`f1 v4 lex error` publishes
`unterminated block comment` + `no-tabs`, identical on both binaries).
3. *Server catalog complete* — **PASS.** `grep -rn
'tokenize|parse_source_tolerant|parse_tolerant|format_source|format_range|
rebuild_index' crates/vfmt_server/src` returns exactly the sites the
catalog names: `state.rs:56-61` (`Document::new`, one lex),
`format.rs:57,87` (kept, strict parse), `state.rs:123/137` +
`server.rs:251` (`rebuild_index`, kept), `lint.rs:54`
(`protected_regions`, kept). The only other `vlog_linter::run` left in the
crate is at `code_action.rs:157`, inside `#[cfg(test)]` — not a per-request
parse. **No uncataloged redundant parse survives.** `doc.tree` is read (not
dead): `lint.rs`'s `context(doc)` and `state.rs:64`'s `analyze(&tree, …)`.
4. *`protected_regions` left alone* — **PASS.**
`git diff --name-only -- crates/vlog_formatter/src/fence.rs` is empty; the
file is untouched by this round (and by the concurrent one).
5. *Behavior identity* — **PASS, re-run from scratch, not taken on trust.**
- `vfmt check corpus/` (820 files): stdout **692 198 bytes identical**,
stderr identical, exit 1 both.
- `--output-format json`: **2 418 071 bytes identical** (matches the dev's
figure exactly), stderr identical, exit 1 both.
- Flag matrix on a 13-file crafted directory, stdout+stderr+exit compared
each time: `--select`, `--ignore`, `--select a,b --output-format json`,
`--indent 4`, `--threads 1`, an unknown rule name (exit 2 both), a
missing file (exit 2 both), `--unsafe-fixes`, a single file, an empty
file, `check - --stdin-filename`, and `--select
case-missing-default,module-filename` over the whole corpus. **12/12
identical.**
- `check --fix` over 13 crafted shapes (multi-round tab+trailing, a real
`// verilog_format: off/on` fence, the `// vfmt: off/on` alias, an
unclosed fence, `// vfmt: waive`, unused + malformed + unknown-rule
waivers, a lex-error file, a filename mismatch, CRLF, multi-byte +
emoji + tab, an empty file, a class body, a parse-error file): every
rewritten file byte-identical, stdout (path-normalized) and stderr
identical, exit 1 both. Fenced regions provably untouched — the tab and
the trailing run inside the fence survive byte-for-byte while the
violations are still *reported*.
- **`check --fix` over a full copy of `corpus/` (820 files, 48 rewritten):
every file byte-identical old-vs-new**, stdout (309 lines) and stderr
identical, exit 1 both. This is a much wider `--fix` net than the ten
shapes in the work log and it holds.
- Server: an independent hand-written stdio driver (`scratchpad/qa_lsp.py`,
not the dev's) over 3 scratch files and **13 publishes** —
parseable → parse-error → clean → lex-error → healed → empty → back;
a filename-rule flip; a fence + error-recovery file losing its fence then
being fixed. All 13 diagnostic lists **byte-identical** between the two
binaries after stripping the scratch-dir prefix.
- Server, `fixable`/codeAction (the other `from_parse` call site, which the
work log did not exercise): `textDocument/codeAction` over the whole
buffer for 6 shapes (plain, fenced, waived, parse-error, lex-error,
multi-byte) — **16 379 bytes of diagnostics + actions, identical**,
including the fence filter correctly withholding quick fixes.
6. *Timing direction* — **PASS.** Release, median of 9, 820-file corpus, warm
cache: `--threads 1` **294.7 → 235.3 ms (−20.2 %)**; default threads
**98.6 → 87.2 ms (−11.6 %)**. Absolute numbers run ~10 % above the dev's on
this machine's load, the *direction and magnitude* reproduce. Server
didChange → publishDiagnostics, median of 15 full-text changes:
`picorv32.v` (3049 lines) **20.1 → 12.6 ms**, `ibex_core.sv` (2026 lines)
**8.2 → 3.7 ms** (informational; dev reported 18.0 → 11.0 and 7.6 → 3.4).
7. *Gates* — **PASS.** In the isolated tree: `cargo test --workspace`
**770 passed, 0 failed** (27 result lines; vlog_linter 118 unit + 55
integration + 1 doctest, vfmt 30 unit + 69 CLI, vfmt_server 115 unit + 6
e2e — every count the work log claims). `cargo clippy --workspace
--all-targets` exit 0, **zero warnings**. `cargo fmt --all -- --check`
clean (not just the scoped set). In the *merged* tree the scoped crates are
also green (`cargo test -p vlog_linter -p vfmt -p vfmt_server`: 30/69/115/
6/118/55/1) with scoped clippy and fmt clean. Test churn is zero:
`git diff --numstat crates/vlog_linter/tests/rules.rs` is **12 added, 0
removed**, and no other test file in `vfmt`/`vfmt_server`/`vlog_linter` is
touched. No `unwrap`/`expect`/`panic!`/`unsafe`/`#[allow]` outside
`#[cfg(test)]` in any of the six files.
**Attacks.**
- *Borrowed vs Owned, beyond the shipped property test.* 14 inputs (plain,
tabs+trailing, fence, waiver, unused waiver, class body, parse-error, two
lex-error shapes, CRLF, CJK+emoji+combining, empty, whitespace-only,
case-without-default) × 3 path values (none, matching, mismatching) × 4
construction routes (`LintContext::new`, `ParsedSource::context`, a
hand-built `from_parse` with independently produced products, and `run`).
All `Debug`-identical violation lists — rule, message, span, fix,
applicability — plus equal `source()`, `tokens().len()`, `Debug` of
`file()`, and `comments().len()`. **No divergence.**
- *The four-products contract, violated on purpose.* Five mismatch shapes
(tree of B over text A, tokens of B over text A, line index of B over text
A, everything-but-the-text from B, and short products over long text), with
A deliberately 14 bytes and B 111. Result: **no panic, no abort, no
unsoundness** — the crate contains no `unsafe`, so it cannot be otherwise.
The cost is exactly *wrong findings*: `module-filename` reported a module
name that is not in the text, and its **reported span (7..33) pointed past
the end of a 14-byte buffer**. Corruption is nonetheless impossible even
then: `apply_fixes` (`crates/vlog_linter/src/violation.rs:118`) already
skips any edit with `end > source.len()` or a non-char-boundary start, and
all five shapes applied cleanly with in-bounds output. See finding QA-2 for
the one thing the README should add.
- *The `--fix` loop.* Multi-round convergence survives the parse-once first
round: `\twire a;\t\n` converges to ` wire a;\n` (tab expanded in one
round, the trailing run removed in a later one), and a second `--fix`
invocation over the already-fixed directory is a **no-op** (`diff -rq`
clean), i.e. the loop still terminates at a fixed point. Fenced fixes are
still refused, for both fence spellings and for an unclosed fence.
- *Server, stale-tree.* The `parseable → broken → parseable` cycle tracks
correctly: the parse diagnostic appears at v2 and is **gone** at v3, the lex
diagnostic appears at v4 and is gone at v5, `module-filename` clears the
moment the module is renamed, a waiver added at v3 clears the lint. Nothing
from an older version leaks into a newer publish. `Document` is rebuilt
whole per change (`Workspace::set_document` → `Document::new`), so there is
no reuse point to go stale.
- *Sabotage.* Made `Workspace::set_document` keep the previous version's tree
(`doc.tree = old.tree`) while everything else refreshed — the exact bug this
round newly makes possible. It **is** a real, user-visible bug: the stdio
session immediately diverges (a stale `module-filename` warning for the old
module name survives the rename and persists into the next version). But see
finding QA-1. Sabotage reverted; `diff` against the working tree's
`state.rs` clean, and a rebuilt server reproduces the baseline 13-publish
log byte-for-byte. The scratch `qa_probe.rs` was deleted; `diff -rq head-wt
qa-new` is back to exactly the six feature files.
**Findings.**
- **QA-1 (MEDIUM — missing coverage, not a defect in shipped behavior).**
The stale-tree bug that this round newly makes possible is caught by **no
test in the workspace**. With the sabotage above in place, `cargo test -p
vfmt_server` passes **115 unit + 6 e2e, 0 failed**, and `cargo test
--workspace` passes **773, 0 failed** (770 + 3 scratch probes). Only a live
stdio session caught it. `Document.tree` is now a cached derivation of
`Document.text`, and nothing asserts they agree. The cheapest guard is one
`#[cfg(test)]` case in `crates/vfmt_server/src/lint.rs` or `state.rs`:
`set_document` a buffer whose module name mismatches the filename, then
`set_document` the renamed text, and assert `violations` no longer contains
`module-filename` — an AST-rule finding, which is exactly the class that
reads `doc.tree`. Reported rather than fixed: writing a new test into
another feature's crate is the dev's call, not QA's.
- **QA-2 (LOW — documentation).** `from_parse`'s caller contract says what the
caller must supply but not what breaking it costs. The measured answer is
worth one sentence at the item and in Assumptions: *violating it yields
wrong findings and spans that may point outside the text; it is never
unsound (no `unsafe`) and never corrupts a file, because `apply_fixes`
independently bounds-checks every edit.* Left for the dev to word, since
Assumptions is theirs.
- **QA-3 (INFORMATIONAL).** `LintContext::new` is declared inside `impl<'a>
LintContext<'a>` but returns `LintContext<'static>`, so its `'a` is unused.
Compiles, clippy-clean, callers unaffected; noted only so a later reader
does not mistake it for an accident.
- **QA-4 (INFORMATIONAL, pre-existing, out of scope).** On CRLF input,
`no-trailing-whitespace` does not fix the run before `\r\n` (observed on a
crafted `crlf.sv`: `wire a; \r\n` survives `--fix`). Byte-identical on
both binaries, so it predates this round entirely — recorded here only
because the CRLF shape was part of the identity matrix and someone will
otherwise re-find it.
**Verdict: no BLOCKING findings.** No behavior divergence old-vs-new was found
anywhere — 820-file corpus check (text and JSON), 820-file corpus `--fix`, a
12-case flag matrix, 13 crafted `--fix` shapes, 13 server publishes and 6
codeAction rounds all byte-identical. No stale-tree reuse in the shipped code.
No memory unsafety is reachable, by construction. The one thing this round
leaves behind is an untested invariant (QA-1), not a broken one.
## Review
**2026-08-19 — lead. Verdict: accepted; commits with round 19. The
duplicated-parse debt is paid: check is 20% faster single-threaded and
the editor's per-keystroke latency roughly halved, with behavior
identity proven at the byte level.**
Points reviewed and accepted:
1. **The Backing enum was forced, not chosen** — SourceFile is !Clone,
so borrowing was the only non-duplicating shape, and QA verified the
constraint at the type level. Keeping `new()` as a one-line wrapper
through the same private assemble is what kept all 12 rule files
byte-untouched: an API migration with zero consumer churn.
2. **The four-products contract was violated on purpose and the cost
measured**: wrong findings, possibly out-of-text spans, never
unsoundness, never a bad write (apply_fixes independently rejects
out-of-range edits). That measured answer is now in the doc comment
(lead fix, QA-2).
3. **The server catalog is complete** — QA's grep found no uncataloged
redundant parse, and the kept-with-reasons list (protected_regions'
anti-drift signature, the strict format parse, the documented
rebuild-on-save index) shows restraint where restraint was correct.
4. **QA-1 closed by lead fix**: the sabotage that kept a stale tree
passed all 773 tests — nothing pinned text/tree agreement. The new
`set_document_rebuilds_the_tree_so_diagnostics_track_the_text`
guard in diagnostics.rs fails on exactly that sabotage (premise
asserted through the merged all() path, where the stale lint
warning actually lives — the first draft checked the parse-only
path and was corrected before landing).
5. QA-3 (the unused 'a on new()) stands as a noted quirk; QA-4 (CRLF
trailing-whitespace fix gap) is pre-existing and joins the linter's
known-gaps list.
+7 -1
View File
@@ -47,6 +47,9 @@ this is protocol-layer wiring, which is all `vfmt_server` is allowed to be.
already redoes per keystroke by design (TODO §6, "per-file recompute is fine
at Verilog file sizes"). When the shared-parse work lands, exactly one call
site here changes.
~~parsed twice per change~~ **Delivered by one-parse (round 19): `lint.rs`
now lints from the `Document`'s own products via `LintContext::from_parse`
— see `docs/features/one-parse/README.md`.**
- **Only Safe fixes are ever offered.** `--unsafe-fixes` is a flag a CLI user
types on purpose; a lightbulb is not that, and a fix that can change what the
circuit does must not be one click away. No rule ships an Unsafe fix today, so
@@ -137,6 +140,8 @@ user setting, not an extension one.
caller with a reason to want `LintContext` to accept a pre-built
`SourceFile`. Nothing here blocks on it; when it lands, `lint.rs` is the one
file that changes.
**Delivered by one-parse (round 19) — `lint.rs` was indeed the one file
(plus `Document` gaining its `tree` field).**
2. *linter-core / config-discovery*: **a `lint` key in `vfmt.toml`.** The server
runs `default_rules()` and nothing else, because there is no configured rule
set to read — `--select`/`--ignore` are CLI-only. When `lint = [...]` lands,
@@ -224,7 +229,8 @@ TODO §2 `--lines`), `completion`, `rename`, `signatureHelp`, and cross-file
not.~~ Delivered by **shared-fence-filter** (round 14).
- [ ] **Not done:** `codeAction/resolve`. Every action is cheap to build in
full; lazy resolution is a payload optimization for actions that are not.
- [ ] **Not done:** sharing one parse with the linter (Handshake 1).
- [x] ~~**Not done:** sharing one parse with the linter (Handshake 1).~~
Delivered by **one-parse** (round 19).
## Work log