Files
lucisv/docs/features/classes/README.md
T

760 lines
44 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# classes
## Goal
Parse and format SystemVerilog `class` declarations well enough to unblock the
DV half of the corpus. `docs/features/corpus-check/README.md` measured
`extends` as the single largest remaining blocker after macro-items — **142 of
820 files**, all of them UVM/DV under `ibex/dv/`, `ibex/vendor/lowrisc_ip/dv/`,
`ibex/vendor/google_riscv-dv/` and `opentitan/hw/ip/uart/dv/`. The design point
is deliberately split: the *shape* of a class (header, `extends`, members,
methods) is a real AST that gets canonical layout, while the two sublanguages a
class body can contain — constraints and covergroups — are captured **verbatim**
by span, exactly the way `` `define`` and macro invocations already are.
Formatting them would mean modelling a second grammar with no payoff and real
corruption risk.
## What is structural, and what is verbatim
Every choice below was made from real corpus files, named here so the next
reader can check the evidence rather than the reasoning.
### Structural (parsed, laid out canonically)
| construct | corpus evidence |
|---|---|
| `class c;` … `endclass[: c]` | everywhere |
| `virtual class c;` | `lowrisc_ip/dv/sv/push_pull_agent/push_pull_driver_lib.sv:85`, `dv_utils/dv_vif_wrap.sv:13` |
| `class c #(parameter int W = 32, ...)` | `push_pull_driver_lib.sv:16` |
| `extends base` | `ibex_icache_core_agent_cfg.sv:5` |
| `extends pkg::base` | scope-qualified bases in `core_ibex_*` |
| `extends base #(.A(x), .B(y))` (named overrides) | `ibex_icache_core_driver.sv:6-8`, `uart_env.sv:5` |
| `extends base #(x)` (ordered overrides) | `ibex_icache_core_agent_cov.sv:5` |
| `implements a, b` | not in the corpus; two lines of grammar, taken for completeness |
| properties with `rand`/`randc`/`local`/`protected`/`static`/`const` | `ibex_icache_core_req_item.sv:8-26` |
| `virtual my_if vif;` / `virtual interface my_if vif;` | `ibex_icache_core_agent_cfg.sv:8` |
| parameterized property types (`uvm_analysis_port #(bit [31:0]) p;`) | `ibex_icache_core_driver.sv:15`, `push_pull_driver_lib.sv:24` |
| `function` / `task`, with `virtual`/`static`/`local`/`protected`/`automatic` | `ibex_icache_core_driver.sv:17-27` |
| `function new(...)` | `ibex_icache_env_cov.sv:21` |
| `endfunction : name` / `endtask : name` | `ibex_icache_env_cov.sv:24` |
| `pure virtual function/task ...;` prototypes | `push_pull_driver_lib.sv:96-102` |
| `extern function/task ...;` prototypes | `dv_base_reg/dv_base_mem.sv:24-46` |
| out-of-body definitions (`function void dv_base_mem::configure(...)`) | `dv_base_mem.sv` |
| `typedef class c;` forward declarations | `push_pull_driver_lib.sv:5-9`, `core_ibex_test_pkg.sv:28` |
| parameterized class references in expressions (`uvm_config_db#(virtual bus_if)::get(...)`) | `ibex_icache_core_agent.sv:20`, `push_pull_driver_lib.sv:34` |
| `disable fork;` | `ibex_icache_core_driver.sv:81` |
| `typedef`, `localparam`, `import`, directives, macro items in a class body | `push_pull_driver_lib.sv:112` (`` `define`` inside a class) |
Class bodies are **item lists**. `parse_class` runs the same
`item_or_recover()` loop a module or package body runs, so everything the item
machinery already supports — `Meta` comments, blank-line preservation,
`` `ifdef`` at item position, macro items, nested classes — works inside a
class without a line of per-site code.
### Verbatim (captured by span, reproduced byte for byte)
| construct | why | corpus evidence |
|---|---|---|
| `constraint c { ... }` | the constraint language is its own grammar — `dist { 0 :/ 5, [1:20] :/ 20 }`, `->` implication, `solve x before y`, `inside`, `foreach`, `if`/`else`. None of it appears anywhere else in lucisv, and there is no layout convention worth inventing for it. | `ibex_icache_core_req_item.sv:28-62` (five blocks, all four of those forms) |
| `covergroup ... endgroup[: label]` | same argument: `coverpoint`, `cross`, `bins`/`ignore_bins`/`illegal_bins`, `binsof ... intersect`, `with function sample`. | `ibex_icache_core_agent_cov.sv:17-46`, `uart_env_cov.sv:8-55` |
| the `#( ... )` of a parameterized **type** reference | its arguments are types as often as expressions (`#(virtual ibex_icache_core_if)`, `#(push_pull_item #(A, B))`), so `parse_expr` cannot represent them. | `push_pull_driver_lib.sv:20-24`, `ibex_icache_core_driver.sv:15` |
`randsequence` is **not** handled: `grep -rn randsequence corpus` finds zero
occurrences in all four repos. Adding a verbatim capture for a construct the
corpus does not contain would be building for a user that does not exist.
Verbatim capture reuses the existing `RawText { text, col, span }` leaf and the
`recover()` pattern that error-recovery already established: skip the tokens,
slice `source[span]`, drop the trivia copies the skip made. This is why
`vlog_parser::parse` now takes the source text (see Handshakes).
## Assumptions
- **The class body is an item list, not a member list.** SystemVerilog's
`class_item` production overlaps almost exactly with what lucisv already
accepts at module scope, so the alternative — a separate `ClassItem` enum —
would have duplicated a dozen variants to gain nothing. The cost is that a
construct only legal at module scope (`always_ff`, an instantiation) parses
inside a class instead of being rejected. lucisv is a formatter, not a
compiler; it does not check legality anywhere else either.
- **A verbatim block's *relative* layout is what survives, not its absolute
layout.** `raw_lines` dedents continuation lines by `col - 1` and the
printer re-indents them, so a `constraint` written entirely at column 1
stays flush with its own opening line after the block is indented into the
class body. This is the same contract multi-line macro invocations have had
since macro-items, and it is what makes the second pass a fixed point.
- **Verbatim `#( ... )` type parameters are emitted with *no* re-indent at
all.** They do not begin the line they are printed on, so the
dedent-by-column trick cannot converge — the dedent has to cancel an indent
the printer adds back, and mid-line there is none. `Fmt::raw_inline` emits
the text unchanged, which is idempotent by construction. A multi-line
`#( ... )` therefore keeps its original absolute alignment even if the line
it hangs off moves. Found by the corpus, not predicted:
`dv_base_reg/dv_base_mubi_cov.sv:63` is a `typedef mubi_cov #(...)` split
over three lines, and the dedent path drifted left on every pass.
- **`class`, `endclass`, `extends`, `implements`, `virtual`, `pure`, `extern`,
`rand`, `randc`, `local`, `protected`, `constraint`, `covergroup` and
`endgroup` are reserved words** and are safe to promote to keywords. Every
one is reserved by IEEE 1800; a file using one as an identifier is not legal
SystemVerilog. Confirmed empirically: the corpus re-run shows **zero** files
regressing.
- **`new`, `this`, `super` and `null` are deliberately *not* keywords.** They
stand in expression position, where they already parse as ordinary names:
`analysis_port = new("analysis_port", this)` is a call, `super.new(...)` a
member access. Promoting them would have broken working code to gain
nothing.
- **A one-token lookahead distinguishes a parameterized-type declaration from
an instantiation.** `port_t #(int) p;` and `sub #(.W(8)) u (...);` open
identically; what follows the name after the overrides decides — a `(` or
`[` means an instance, anything else a declaration. The corpus contains both
shapes and no counterexample. A wrong guess cannot corrupt: both readings
emit the same tokens in the same order, so the safety net still passes and
only the layout would differ.
- **`#( ... )` continues a postfix chain only after a *name*.** `at_postfix_segment`
accepts it when the expression so far is an `Ident` or a `Scope`, so
`uvm_config_db#(...)::get` parses while nothing else in the expression
grammar changes meaning.
- **Class members are not semantically analysed.** See the `vlog_semantic`
handshake below.
## Handshakes
**Changed, and every caller updated: `vlog_parser::parse` now takes the
source text.**
```rust
pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile>
```
It previously took only the tokens and passed `""` for the source, because
only error-recovery (a tolerant-mode-only path) read it. The verbatim class
blocks read it in **strict** mode, which is the mode the formatter uses, so
"strict mode has no source" had to go. Making the parameter mandatory rather
than optional is deliberate: a `parse()` that silently produced empty verbatim
text would be a corruption bug, and the type system now makes it unreachable.
`parse_source` / `parse_source_tolerant` are unchanged; they were the only
callers.
**Promised to `vlog_formatter`:**
- `ItemKind::Class(ClassDecl)` — header parts kept apart (`prefix`,
`lifetime`, `name`/`name_span`, `param_ports` + `param_directives` +
`param_dangling`, `extends`, `implements`, `items`, `dangling`,
`end_label`), so the formatter lays each out with the machinery it already
has: `param_port` for the parameter ports, `connection` for the `extends`
overrides, `item_seq` for the body, `Self::closing` for the footer.
- `ClassExtends { name, name_span, param_comments, params, param_directives,
span }` — `params` is a `Vec<Connection>`, the same node an instantiation's
`#( ... )` overrides use, because both spell named and ordered overrides the
same way.
- `ItemKind::Verbatim(RawText)` — one leaf for both `constraint` and
`covergroup`. `raw.col` is load-bearing exactly as it is for macro items:
it is what `Fmt::raw_lines` dedents continuation lines by.
- `DataType::params: Option<Box<RawText>>` and
`ExprKind::Parameterized { base, params }` — both verbatim, both printed
through `Fmt::raw_inline` (no re-indent). Boxed in `DataType` to keep
`ExprKind::Type` — and through it every `Expr` — small; without the box
clippy's `large_enum_variant` fires on `ItemKind`.
- `FunctionDecl` / `TaskDecl` gained `prefix: Vec<String>` (the qualifiers
written *before* the keyword), `is_prototype: bool` (no body, no
`endfunction`), and `scope: Option<String>` (the `my_class::` of an
out-of-body definition). `scope` is kept apart from `name` so
`src[name_span] == name` still holds, which is the `name-spans` contract
`vlog_semantic` depends on — gluing them broke ten symbols in
`dv_base_mem.sv` and was caught by that crate's corpus test.
- `TypedefKind::ForwardClass` for `typedef class c;`.
**Consumed from / required of `vlog_semantic` (minimal, documented):**
`bind.rs`'s `ItemKind` and `TypedefKind` matches are exhaustive, so the new
variants had to be answered or the crate would not compile. The minimum was
added and nothing more:
- `ItemKind::Class(_) => {}` and `ItemKind::Verbatim(_) => {}` — classes are
parsed and formatted but not modelled. Their scoping rules (inheritance,
`this`/`super`, static vs. instance members, `::` into a class) are a
separate design question, and a half-model would resolve names *wrongly*
rather than not at all.
- `TypedefKind::ForwardClass` declares the name and nothing else, so a
reference to a forward-declared class still resolves.
- `ExprKind::Parameterized { base, .. }` binds the base name and ignores the
verbatim `#( ... )`.
Consequence, stated plainly: **no name declared inside a class body is
indexed, hovered or navigable.** That is a real LSP gap, not an oversight, and
it is the natural next round for that crate. **Delivered 2026-08-19 by
`class-semantics`** — see `docs/features/class-semantics/README.md`.
**Requested of `vlog_formatter::fence` (out of this feature's scope):**
`scan_nested` enumerates the item scopes a fence can live in — module,
package, generate region, generate `if`/`for`/`case` — and ends in a `_ => {}`
catch-all, so a class body is not scanned. Probed and confirmed:
```systemverilog
class c;
// verilog_format: off
int a = 1; // ← re-formatted anyway
// verilog_format: on
endclass
```
is formatted normally, while the identical shape inside a `module` is left
verbatim. The fix is one arm —
`ItemKind::Class(c) => scan_scope(src, &c.items, &c.dangling, out)` — but
`fence.rs` was explicitly outside this round's scope, so it is filed here
rather than done. Nothing is corrupted by the gap; the fence is simply
inactive. *(Lead note, per lint-rules-2 QA: inactive for the FORMATTER
only. `fence::protected_regions`' line-based scan backstop still sees the
fence, so `lucisv check --fix` and the server's quick fixes DO decline to
edit inside it — the asymmetry errs toward hands-off, which is the
harmless direction, but readers should not conclude the fence does
nothing in a class body.)*
**Requested of `vlog_linter` (same shape, lower stakes):** `visit.rs`'s
`items()` walk has a `_ => {}` arm too, so the four **AST-walking** rules
(`case-missing-default`, `always-ff-non-blocking`, `always-comb-blocking`,
`explicit-parameter-storage-type`) do not see class members — a
`case-missing-default` inside a class method will not fire. The
**line/file-based** rules (`no-tabs`, `no-trailing-whitespace`,
`module-filename`, `unused-waiver`) still fire inside class bodies as
normal (QA-verified by probe; wording sharpened by the lead per the QA
log). The walk is additive-compatible — the crate compiles unchanged —
so this is a coverage gap, not a break.
**Requested of `macro-items` (refined here, one line):** `at_macro_item`'s
"next token is a plain identifier" arm now also treats the invocation as
standalone when that identifier is followed by `#(`. Real UVM writes
```systemverilog
`uvm_component_new
uvm_analysis_port #(bit [31:0]) analysis_port;
```
and the old rule read `` `uvm_component_new `` as a *type* and
`uvm_analysis_port` as its declarator, then failed at the `#`. The new clause
cannot regress anything: the old reading was already a parse error, and the
"both readings emit the same tokens" safety property is unchanged.
**Recursion/chain budgets (`docs/features/recursion-limit/README.md`):** no new
budget and none needed. `parse_class` is reached through `parse_item`, which
already charges `enter()`/`leave()`, and its body loop calls
`item_or_recover()` → `parse_item`, so nested classes are charged exactly like
nested packages. Pinned by
`class_bodies_are_charged_against_the_nesting_budget`: 63 nested classes parse,
65 are a clean `nesting too deep (limit 64)` error. The verbatim scans
(`skip_balanced`, the `covergroup` scan) are flat loops over the token vector,
not recursion. `ExprKind::Parameterized` is a postfix segment and charges
`link()` like every other one.
**`verify.rs` is untouched.** No normalization was added, broadened or
weakened, so CLAUDE.md hard invariant #4 does not strictly apply — but the
verbatim capture is new forgiveness-adjacent machinery, so it ships with the
attack tests anyway (see Status/TODO). The reason none was needed is worth
stating: a verbatim block is re-lexed as *ordinary tokens* on both sides, not
as one opaque token, so any changed byte inside it that is not inter-token
whitespace already diverges. And a string literal spanning a line break inside
a constraint is caught by the pre-existing `crosses_line_inside_string` guard
in `Fmt::raw_text`, which emits such a token with no re-indent at all.
## Design notes
### One dispatch for every member qualifier
A run of `virtual` / `pure` / `extern` / `local` / `protected` / `rand` /
`randc` / `static` / `automatic` / `const` / `var` does not say what it
qualifies; the first keyword *past* the run does. `Parser::member_head` walks
that run **without consuming**, and `parse_keyword_item` dispatches on what it
finds — `class`, `function`, `task`, `constraint`, `covergroup`, or (the
default) a data declaration. Each branch then consumes the qualifiers itself
via `take_member_prefix`. The alternative, consuming the run up front and
passing it down, needs every callee to accept a `Vec<String>` it may not want,
and gets `virtual interface my_if h;` wrong (the `interface` is part of the
qualifier, and only after `virtual`).
This also folded the pre-existing `var`/`automatic`/`static`/`const` arm into
the same path, so `static function` and `static constraint` work for free.
### A blank continuation line ends a `` `define`` (lexer bug, found by the corpus)
`dv_utils/dv_vif_wrap.sv:72` is a `` `define`` whose last body line ends in
`\` and is followed by a blank line and then a comment. The lexer *consumed*
the newline before the blank line and then trimmed the text back to the last
`\`, so the attachment phase saw one newline instead of two and the comment
lost its `blank_before` flag. The formatter then printed the comment directly
under a line ending in `\`, and the re-lexed output had the directive
swallowing the comment — a genuine equivalence failure, caught by the safety
net.
The fix is in the lexer's continuation loop: a blank continuation line is
*not* part of the directive, so the position is restored before the newline
that would have been consumed and the gap keeps both newlines. This is a
pre-existing bug — it reproduces on a file with no class syntax in it
(`` `define A \ `` ⏎ ` x \ ` ⏎ ⏎ `// c`) — that this feature merely made
reachable, and it is fixed here because the alternative was shipping a
non-zero verification-error count.
## Status / TODO
- [x] Keywords: 14 class-related reserved words, with `new`/`this`/`super`/
`null` deliberately excluded and the reason recorded in `token.rs`.
- [x] AST: `ClassDecl`, `ClassExtends`, `ItemKind::Class`,
`ItemKind::Verbatim`, `TypedefKind::ForwardClass`, `DataType::params`,
`ExprKind::Parameterized`, `FunctionDecl`/`TaskDecl` `prefix` /
`is_prototype` / `scope`.
- [x] Parser: `parse_class`, `parse_class_extends`, `parse_constraint`,
`parse_covergroup`, `skip_balanced`, `verbatim_since`, `member_head`,
`take_member_prefix`, `parse_method_name`, `parse_type_params`.
- [x] `parse_param_port_list` extracted from `parse_module` so module and
class headers share one parse (no duplicated list machinery).
- [x] Formatter: `Fmt::class`, `Fmt::raw_inline`, prototype and `scope`
handling in `function`/`task`, `DataType::params` in `data_type`.
- [x] `parse` takes the source; `slice()` is meaningful in strict mode.
- [x] Lexer: a blank continuation line ends a `` `define`` and stays a blank
line (pre-existing bug, see Design notes).
- [x] 38 cases in `crates/vlog_formatter/tests/cases/classes.cases`.
- [x] 10 parser unit tests, 2 lexer unit tests.
- [x] 11 verification tests in `tests/verification.rs` — the invariant-#4
attack set for the verbatim capture: a changed constraint expression, a
dropped constraint line, a dropped comment inside a constraint, a
re-indented string inside a constraint, a changed covergroup bin, a
dropped `endgroup` label, a changed `#( ... )` type argument, a dropped
`endclass` label and a dropped method qualifier are all asserted
**rejected**; a plain re-indent is asserted **accepted** (so the tests
are not vacuous).
- [x] Spans: three class sources added to `tests/spans.rs`'s `SOURCES`, and
`check_item` gained arms for `ItemKind::Class` (name, end label,
`implements` names, parameter ports, the `extends` clause and its
overrides, and every body item recursively) and `ItemKind::Verbatim`.
- [x] Corpus re-run: 0 regressions, 0 verification errors, 0 crashes.
- [x] `README.md` roadmap item 2 struck and supported-syntax updated.
- [ ] **Not done, deliberately:** semantic analysis of classes. See the
`vlog_semantic` handshake — an inheritance-aware scope model is its own
round, and a half-model resolves names wrongly.
- [ ] **Not done, deliberately:** canonical layout for constraint and
covergroup bodies. Two grammars, no layout convention worth inventing,
and the verbatim path is corruption-proof by construction.
- [ ] **Not done, out of scope:** fences inside class bodies (`fence.rs`, one
arm) and lint-rule coverage of class members (`visit.rs`, one arm).
Both filed under Handshakes.
- [ ] **Not done:** `` `uvm_field_int (x, y)`` — a macro invocation with a
space before its `(`. Ten of the 70 still-blocked ex-`extends` files die
on this, and it is the documented `macro-items` gap (their Assumptions,
2026-08-19), whose fix belongs in the lexer and has a known side effect
in expression position. Not this feature's to make.
## Corpus results
`./tools/corpus_check.sh corpus` over the same pinned 820-file corpus. All four
repos verified unmodified afterwards (`git status --porcelain` clean apart from
the pre-existing untracked `.lucisv-corpus-rev` stamps).
| metric | before | after |
|---|---|---|
| **parsed & formattable** | 476/820 (**58.0%**) | 578/820 (**70.5%**) |
| would-reformat | 468 | 568 |
| ok-unchanged (already clean) | 8 | 10 |
| parse-error | 344 (42.0%) | 242 (29.5%) |
| verification-error | 0 | **0** |
| crash | 0 | **0** |
```
outcome files share
-------------------- ----- -------
ok-unchanged 10 1.2%
would-reformat 568 69.3%
parse-error 242 29.5%
verification-error 0 0.0%
other-error 0 0.0%
crash 0 0.0%
-------------------- ----- -------
total 820 100.0%
```
**Diffed by path against the baseline TSV, not just by count:**
| transition | files |
|---|---|
| parse-error → would-reformat | 100 |
| parse-error → ok-unchanged | 2 |
| would-reformat → would-reformat | 468 |
| ok-unchanged → ok-unchanged | 8 |
| parse-error → parse-error | 242 |
| **any regression** | **0** |
102 files gained, **0 lost**, and no already-parsing file changed status in any
direction. Gained files by tree: `ibex/dv` 55, `ibex/vendor` 34,
`opentitan/hw` 11, `common_cells/test` 2.
**Honest reading of the numbers.**
- The corpus README predicted 142 files blocked on `extends`. **72 of those 142
now format**; the other **70 hit a second blocker**, which is exactly the
under-counting macro-items warned about. The remaining 30 of the 102 gained
files were blocked one token *earlier* than `extends` — 25 on the `#` of a
class parameter list or a parameterized type, and 5 on assorted shapes.
- **New first-blocker histogram for the 70 ex-`extends` files that are still
stuck**, which is the honest answer to "what is next":
| blocking token | files | what it is |
|---|---|---|
| `$` | 25 | queues — `bit x[$]`, `q[$] = {}` |
| `.` | 12 | named function arguments (`f(.arg(x))`) and `@hier.name` event control |
| `` `uvm_field_int `` | 9 | macro invocation with a space before `(` — the documented macro-items gap |
| `]` | 9 | dynamic arrays — `int q[]` |
| `inside` | 7 | `inside` used as a constraint/expression operator outside a constraint block |
| others (1 each) | 8 | `with`, `import` at statement position, assorted |
**34 of the 70 are queues and dynamic arrays** — README roadmap item 4,
untouched here by design. That, not classes, is now the top blocker.
- **Whole-corpus first-blocker histogram** after this round: `$` 41,
`interface` 25, `]` 23, `.` 21, `` `uvm_field_int `` 10, `inside` 7,
`"DPI-C"` 7, `'` 7, `$error` 6.
- **Verification errors stayed at 0.** Two appeared mid-round as files reached
the safety net for the first time, and both were fixed rather than
documented away: the `` `define``-blank-continuation lexer bug (Design
notes) and the mid-line verbatim re-indent drift (`Fmt::raw_inline`, see
Assumptions). Neither was caused by class syntax; both were caused by class
syntax letting the formatter reach code it had never seen.
- **Every formattable file was round-tripped**, not sampled: all 578 were
copied to a scratch directory, formatted in place and re-checked with
`--check`. All 578 are fixed points; none failed to format.
## Work log
### 2026-08-19 — dev agent
- Read `CLAUDE.md`, `README.md`, and the `macro-items`, `spans`,
`directives-in-lists` and `directives-in-instances` READMEs before touching
code. Baseline recorded first: `cargo test --workspace` **589 passed**,
clippy silent (0 warnings), fmt clean, corpus 476/820 formattable, 344
parse-error, 0 verification-error, 0 crash.
- **Read 15+ real corpus files before designing anything**, per the brief, and
let their shapes decide the split. Three things fell out of that reading that
I would not have guessed: (a) class parameter lists and `extends` override
lists are the *same* two list grammars module headers and instantiations
already have, so the machinery was reusable rather than new; (b) the DV
corpus leans on parameterized *type references* (`uvm_analysis_port #(...)`)
as heavily as on `extends`, which is why the `#` blocker at 40 files was
really part of this feature; (c) constraints and covergroups are big, common,
and completely disjoint from every grammar lucisv already has.
- **Chose verbatim for constraints and covergroups before writing a line of
parser.** The deciding argument is not effort but risk symmetry: a verbatim
block is re-lexed as ordinary tokens by the safety net, so a wrong byte is
caught, while a hand-rolled constraint grammar would be a new place to drop a
token that *looks* like formatting. The verbatim path also costs one AST leaf
instead of a dozen nodes.
- **Kept `new`, `this`, `super` and `null` as identifiers.** Adding them to the
keyword table was the obvious move and it is wrong: they only ever appear in
expression position, where the existing grammar already handles them, and
promoting them would have broken `x = new(...)` and `super.f()` to gain
nothing. Recorded in `token.rs` next to the list so the next person does not
re-add them.
- **`member_head` looks without consuming.** First attempt consumed the
qualifier run in `parse_keyword_item` and passed it down; that made every
callee take a `Vec<String>` and got `virtual interface my_if h;` wrong.
Rewrote it as a pure lookahead and let each construct consume its own prefix.
- **`parse` had to take the source.** Verbatim capture slices `source[span]`,
and strict mode was passing `""`. Made the parameter mandatory rather than
adding an optional variant: a `parse()` that silently produced empty verbatim
text is a corruption bug, and there was exactly one caller.
- **Comment plumbing for verbatim blocks was the one subtle part.** Copying
`recover()`'s `take_dangling()` would have been wrong — it also drains the
*next* token's leading comments, which are outside the block. Filtered by
span instead (`verbatim_since`), which drops exactly the comments inside the
block and keeps the one written after its closing brace on the same line.
Pinned by `a_comment_after_a_verbatim_block_stays_outside_it`.
- **Split the method scope out of the method name after `vlog_semantic`'s
corpus test failed.** First version stored `dv_base_mem::configure` in
`name`, following the `Instantiation::module` precedent. That precedent does
not apply: `vlog_semantic` re-derives `name_span` by scanning for identifier
*tokens*, and `a::b` is not one, so ten symbols in `dv_base_mem.sv` became
unplaceable. The fix is better design anyway — an LSP wants `configure`, not
the qualified spelling.
- **Two verification errors appeared at the corpus run and both were fixed, not
documented.** The first was a pre-existing lexer bug (`` `define`` with a
blank continuation line); reproduced it on a class-free input first to be
sure it was not mine, then fixed it in the continuation loop. The second was
mine: `raw_lines`'s dedent-by-column does not converge for text that starts
mid-line, which a three-line `typedef mubi_cov #(...)` exposed. Added
`raw_inline` for the mid-line case — idempotent by construction rather than
by argument, the same reasoning macro-items used for string-crossing tokens.
- **Removed `class` from `SYNC_OPENERS` after the tolerant-parse test caught
it.** I had added it by analogy with `package`, but unlike a module or a
package a class *nests*, so recovery stopping before one ended the enclosing
package body at the wrong place. The error-recovery suite's
"tolerant tree == strict tree" property found this within seconds, which is
the whole point of that test.
- **Boxed `DataType::params` because clippy asked.** Growing `DataType` grows
`ExprKind::Type`, which grows `Expr`, which grows `ItemKind::GenFor` past
`large_enum_variant`'s threshold. Verified the baseline was genuinely silent
before assuming the warning was mine.
- Corpus re-run diffed **by path** against the baseline TSV: 102 gained, 0
lost, 0 status changes among already-parsing files. Every one of the 578
formattable files was round-tripped through a real format + `--check`, not
sampled. All four corpus repos confirmed unmodified.
- Did not touch `verify.rs`, `fence.rs`, `tools/`, `corpus/`, `editors/`, or
the top-level release docs (a second agent is working there). The two
`vlog_semantic` arms are the documented minimum to keep the crate compiling.
Did not run `git commit` / `git push`.
- **TODO.md**: no checkbox matches this feature — the syntax-coverage roadmap
lives in `README.md`, which is updated. Added a corpus-delta annotation under
§5's corpus-check item, in the style the `directives-in-lists` round used,
leaving the item text intact.
**Results:** `cargo test --workspace` **612 passed, 0 failed** (up from 589:
+11 `vlog_formatter` verification, +10 `vlog_parser` parser unit, +2
`vlog_parser` lexer unit; the case table grew 359 → 397 cases inside its single
test). `cargo clippy --workspace --all-targets` silent, 0 warnings.
`cargo fmt --all --check` clean. Corpus: 578/820 formattable (70.5%, up from
476/58.0%), 242 parse-error (down from 344), **0 verification errors, 0
crashes, 0 regressions by path**; `tools/corpus_check.sh` exits 0.
Files touched: `crates/vlog_parser/src/{token,ast,lexer,parser,lib}.rs`,
`crates/vlog_parser/tests/spans.rs`,
`crates/vlog_formatter/src/format.rs`,
`crates/vlog_formatter/tests/verification.rs`,
`crates/vlog_formatter/tests/cases/classes.cases` (new),
`crates/vlog_semantic/src/bind.rs` (two skip arms, documented),
`README.md`, `TODO.md`, this README.
## QA log
### 2026-08-19 — QA agent
Read `CLAUDE.md`, this README (514 lines) and the full diff before touching
anything. All verification below was run against the working tree as handed
off (uncommitted); nothing was committed. Every sabotage described below was
reverted immediately after observing the result — confirmed by `git diff
--stat` matching the pre-sabotage numbers exactly and the full suite going
back to 612/612 green before moving on.
**Gates.** `cargo test --workspace`: **612 passed, 0 failed** (recount by
summing every `test result:` line, not trusted from the log alone).
`cargo clippy --workspace --all-targets`: silent, 0 warnings.
`cargo fmt --all --check`: clean. All three **PASS**, matching the claim.
**Corpus (claim 1).** Built the pre-feature parser/formatter in a separate
`git worktree` at HEAD (no stash, so the working tree was never disturbed)
and ran `tools/corpus_check.sh corpus` with both binaries against the same
pinned 820-file corpus, then diffed the two per-file TSVs **by path** in
Python (not just by count).
- Baseline: 476/820 formattable (58.0%), 344 parse-error, 0
verification-error, 0 crash — matches the README's "before" column exactly.
- After (working tree): 578/820 formattable (70.5%), 242 parse-error, 10
ok-unchanged, 568 would-reformat, 0 verification-error, 0 crash — matches
the README's "after" column exactly, including the whole-corpus blocker
histogram (`$` 41, `interface` 25, `]` 23, `.` 21, `` `uvm_field_int `` 10,
`inside` 7, `"DPI-C"` 7, `'` 7, `$error` 6 — all exact).
- By-path diff: parse-error→would-reformat 100, parse-error→ok-unchanged 2,
**0 files regressed in either direction**, 0 files changed status any other
way. Exact match to the claimed table.
- Re-derived the `extends`-blocked-142 breakdown independently (grepped the
baseline TSV for `found "extends"` diagnostics, then checked each of those
142 files' after-status): 72 now format, 70 still stuck, and the still-stuck
blocker histogram is `$` 25, `.` 12, `` `uvm_field_int `` 9, `]` 9, `inside`
7, others 8 (one each) — exact match, including the "34 of 70 are
queues/dynamic arrays" arithmetic (25+9).
- Round-tripped **all 578** formattable files (not sampled): copied each to a
scratch dir, `lucisv <file>` then `lucisv --check <file>`. **0 failures, 0
non-fixed-points.**
- Corpus repos confirmed unmodified: `git -C <repo> status --porcelain` clean
in all four (only the pre-existing untracked `.lucisv-corpus-rev` stamps),
before and after the round-trip.
- **Claim 1: PASS**, every number independently reproduced, not just
eyeballed against the README.
**randsequence (claim 3).** `grep -rln randsequence corpus` → 0 hits, all four
repos. **PASS.**
**Attack tests are real pins (claim 4).** Two sabotage experiments, both
reverted:
1. Weakened `Parser::verbatim_since` (`crates/vlog_parser/src/parser.rs`) to
drop the captured verbatim block's last content line. Result: `cargo test
-p vlog_formatter --test cases` failed on `classes.cases:224` (a covergroup
case) with `verification failed: token stream diverges` — `format_source`
refused to emit the corrupted output rather than silently producing it.
`cargo test -p vlog_parser` also caught it directly in
`constraints_and_covergroups_are_captured_verbatim`. This is the
invariant-#1 backstop working end-to-end, not just the crafted tests.
2. Widened `verify.rs::normalize` (untouched by this feature, so this
sabotage is *of* the safety net, testing whether the new attack tests
would catch a real weakening of it) to apply the historical
trim-blindly-not-string-aware treatment to `TokenKind::String` — i.e.
recreated the exact corruption class CLAUDE.md's history note warns about
(multi-line string re-indented and silently accepted). Result: exactly one
of the 9 rejection tests turned red —
`a_reindented_string_inside_a_constraint_is_rejected` — while the other 8
and the pre-existing macro/directive string-crossing tests stayed green.
This is precise evidence the test is a real, narrowly-targeted pin, not a
vacuous pass.
- `verify.rs`: confirmed byte-identical to HEAD both before and after these
experiments (`git diff` empty, not in `git status --porcelain`).
- **Claim 4: PASS.**
**Two mid-round fixes (claim 5).**
- (a) Lexer blank-continuation bug: built the pre-feature binary in the HEAD
worktree and fed it the exact class-free repro from the Design notes
(`` `define A \ `` / ` x \ ` / blank / `// c` / `wire w;`). It reproduces:
`verification failed: token stream diverges ... input has directive
"...x \\" ..., output has directive "...x \\\n// c"`. The fixed (working
tree) binary round-trips the same input cleanly (`--check` exit 0, blank
line preserved). Confirmed pre-existing and confirmed fixed. **PASS.**
- (b) `raw_inline` convergence: reverted `raw_inline` to call `raw_lines`
(the dedent-by-column path) and ran the **real** corpus file
`corpus/ibex/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_mubi_cov.sv`
(the file named in the Assumptions section) through the sabotaged binary:
it hit `verification failed: formatting is not idempotent; line 66 changed
from " .ValueTrue(...)," to ".ValueTrue(...),"` — reproducing the exact
documented drift on the exact documented file. The real (fixed) binary
formats this file cleanly and idempotently (`--check` exit 0 after one
reformat). A synthetic 3-line `typedef ... #(...)` case converges under the
real binary on all 3 passes. **PASS.**
**Handshakes (claim 6).**
- Fence inactive inside a class body: `// lucisv: off` around a member inside
`class c; ... endclass` is ignored (`int a = 1;` gets reformatted to
`int a = 1;`); the identical shape inside `module m; ... endmodule` is left
byte-for-byte alone. Also checked the *complementary* case not mentioned in
the README — a class **nested inside** a module-level fence — and confirmed
the fence still works there (the whole class, member formatting included,
stays byte-identical), since the module-scope fence copies the fenced
source span verbatim regardless of what is inside it. Nothing corrupted
either way. **PASS**, and the two cases don't contradict each other.
- vlog_semantic skips class bodies: built a throwaway probe crate
(path-dependency on `vlog_semantic`/`vlog_parser`, not added to the repo)
and called `Semantics::definition_of` on an identifier used inside a class
method body, and on a property's own declaration site. Both return `None`,
no panic, `symbols().len() == 0` for the whole file — matches "no name
declared inside a class body is indexed, hovered or navigable" exactly.
Separately confirmed `TypedefKind::ForwardClass` **is** indexed:
`typedef class fwd;` followed by a use of `fwd` as a type resolves
`definition_of` to `Some(("fwd", Typedef))`. **PASS.**
- `parse(tokens, source)`: grepped the whole workspace for callers; the only
caller is `parse_source` in `crates/vlog_parser/src/lib.rs`, which is
updated. `parse_source_tolerant` already took `source` before this feature
(calls `parse_tolerant`, a different function) and is untouched, matching
the README's claim. **PASS.**
- Lint rule coverage — **finding, not blocking**, see below.
**Lint-rule finding (non-blocking, documentation precision).** The
Handshakes section says plainly: *"`visit.rs`'s `items()` walk has a `_ =>
{}` arm too, so lint rules do not see class members."* That is broader than
what's actually true. Only the 4 rules that walk the tree through
`visit.rs`'s `walk_items`/`walk_all_stmts`
(`always_comb_blocking`, `always_ff_non_blocking`, `case_missing_default`,
`explicit_parameter_storage_type`) miss class members. The other 4 rules
(`module_filename`, `no_tabs`, `no_trailing_whitespace`, `unused_waiver`)
read raw source/line data directly and are unaffected. Probed directly:
```
class c;
int a; // ← literal tab
function void f(int x);
case (x)
1: a = 1;
endcase // ← no default
endfunction
endclass
```
`lucisv check` on this file reports `no-tabs` (line 2) but **not**
`case-missing-default` for the `case` inside the method — exactly the
asymmetry the broad wording obscures. Suggest tightening the sentence to name
which rules are affected (the 4 AST-walk ones), so a reader doesn't conclude
*no* lint rule fires inside a class. Left the Handshakes section itself
alone, per the QA/lead split in `CLAUDE.md` — filing this as a QA finding
for the lead rather than editing someone else's section.
**Structural support (claim 2) and UVM torture.** All of the following parse,
format, and are stable across 3 formatting passes (checked pass1==pass2==
pass3 byte-for-byte on every case, not just `--check` once):
class in package in `` `ifdef``; nested class-in-class; a class exercising
every member qualifier combination at once (`rand`/`randc`/`local`/
`protected`/`static`/`const`/`local rand`/`protected randc`/`local static`/
`virtual`/`virtual interface`/`pure virtual function`/`extern virtual task`);
`extern function` whose return type is a parameterized class
(`uvm_object_wrapper#(c)`), plus its out-of-body `c::get_wrapper()`
definition; a constraint containing a string literal with literal `{`/`}`
inside it (not mistaken for block delimiters) alongside an `inside {...}`
constraint; a covergroup with `option.per_instance`, `option.name`, an
empty-bracket array bin (`bins low[] = {[1:3]}`), `illegal_bins ... default`,
and a `cross` with `binsof ... intersect`; `` `uvm_object_utils_begin/end ``
with `` `uvm_field_* `` macro items between them as class items; `` `ifdef``/
`` `else``/`` `endif`` directives between ordinary class members; `endclass :
d` where the label doesn't match the class name `c` — **parses and is
preserved verbatim, not rejected and not "corrected"** (consistent with the
Assumptions section: lucisv does not check semantic legality); an empty class;
a 5-deep `extends` chain (`c5 extends c4 extends c3 extends c2 extends c1`);
and a combined case exercising `typedef class` forward declaration, class
parameters referenced in an `extends #(.W(W))` override, multiple
`implements`, a virtual-interface property, a parameterized property type,
`function new`, `fork`/`join_none`/`disable fork`, and a scoped parameterized
call (`uvm_config_db#(virtual my_if)::set(...)`) all in one file — every one
of these formatted correctly (or was already clean) with no dropped tokens,
no corrupted braces/strings, and no divergence from the input's semantic
content.
**Recursion budgets.** A class containing a function containing 60 nested
`begin`/`end` blocks: n=59 succeeds, n=60 hits `nesting too deep (limit 64)`
at a clean, correctly-located parse error — no stack overflow, no crash,
consistent with the class contributing exactly one level to the shared
budget as documented. A 300-member flat class body: parses and formats in
~5 ms, idempotent, no chain-length issue (flat item lists aren't recursive
per-item, as expected). **PASS.**
**Case table count.** `crates/vlog_formatter/tests/cases/classes.cases` has
37 `====` separators (38 cases, matching the claimed count). Total across all
`.cases` files, computed with the same last-block-may-be-empty rule the
harness (`parse_cases` in `tests/cases.rs`) uses: **397**, matching
"359 → 397" (359 = 397 − 38). **PASS.**
**Summary.** All 7 claims **PASS**. No corruption, no comma/label loss, no
verbatim byte alteration, no corpus regression found anywhere — including
under two independent, reverted sabotage experiments designed to surface
exactly those failure modes. One non-blocking documentation-precision finding
filed above (lint-rule handshake wording); no code changes were needed or
made.
## Review
**2026-08-19 — lead. Verdict: accepted and committed. The largest
corpus jump in the project's history: 58.0% → 70.5% formattable, +102
files, zero regressions — verified by path, all 578 formattable files
round-tripped individually.**
Points reviewed and accepted:
1. **The structural-vs-verbatim line was drawn by corpus evidence, not
taste**: constraints and covergroups verbatim (their internals are a
distinct sub-language with no formatting payoff and high corruption
risk — the attack tests exist precisely because verbatim capture is
where the historical corruption class lives), parameterized-type
`#()` args verbatim (they are types, not expressions), randsequence
absent because the corpus has zero. Class bodies reusing the item
loop is why Meta/directives/macros/nesting all worked for free.
2. **Voluntary invariant-#4 compliance**: verify.rs untouched, yet the
9 rejection + 2 acceptance attack tests shipped anyway — and QA's
sabotage recreated the exact historical in-string re-indent
corruption and found precisely one test turning red. That is the
masked-corruption discipline fully internalized.
3. **The two mid-round verification failures were triaged correctly**:
the lexer blank-line bug proven pre-existing on a HEAD worktree
before being fixed; raw_inline's convergence made true by
construction. Both reproduced independently by QA.
4. **The honest ledger**: 72 of 142 extends-blocked files format; 70
advanced to named next blockers, histogrammed. Queues/dynamic
arrays are now the top corpus blocker (41 files) — that data sets
the next parse round's priority.
5. **The handshakes are the right escalations**: fence-inactive inside
class bodies (one-arm fix, filed), lint AST-rule coverage
(lead-sharpened per QA: line-based rules still fire; only the four
AST-walking rules skip class bodies), and the real LSP gap — no
name inside a class body is indexed or navigable — stated plainly
as vlog_semantic's natural next round. The parse(tokens, source)
signature change made mandatory-not-optional for exactly the right
reason: an empty verbatim slice would be a corruption bug.
With this, lucisv formats the majority of real-world DV code as well as
RTL. Next per the owner's directive: alignment inference, content-hash
cache, range formatting, remaining lint rules — and the corpus says
queues/dynamic arrays after that.