Add dv-statements: with clauses, foreach targets, randcase, let, labels

randomize()/std::randomize() with { ... } (block verbatim), array-method
with (expr), foreach over scoped/hierarchical/indexed arrays, randcase,
wait fork, import as a statement, let declarations, empty call arguments,
general statement labels, and endtask: name; (stray semicolon kept).
Also fixes a pre-existing verification failure for a comment between a
then-branch and its else.

Coverage loop round 1, cluster 8: 772 -> 796 / 820 (94.1% -> 97.1%).
Feature README: docs/features/dv-statements/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-21 01:19:49 -07:00
1 parent c2ea1656e1
commit f1db1e5746
15 files changed
+1566 -44

No files matched your search

+301
View File
@@ -0,0 +1,301 @@
# dv-statements
## Goal
Parse and format the statement- and item-level constructs that DV/UVM code
writes and RTL does not, which together were the corpus's whole remaining
`dv-statements` bucket after the expressions-2 round: 26 files, the top
blocker at 94.1%. Nine shapes, every one taken from a real blocked file and
cited below — `randomize() with { ... }` and the array-method `with (expr)`,
`foreach` over a package-scoped or hierarchical array, `randcase`,
`wait fork;`, `import` among a block's declarations, `let` declarations, an
omitted positional call argument, a statement label, and a stray `;` after a
task/function footer label.
## What is structural, and what is verbatim
Everything is **structural** — a real AST node with a canonical layout —
except one thing:
| construct | corpus evidence | treatment |
|---|---|---|
| `randomize() with { ... }`, `std::randomize(x, y) with { ... }`, `obj.randomize() with { ... }` | `cb_filter_tb.sv:272`, `ibex_mem_intf_response_driver.sv:94` (`dist { }` inside), `ibex_mem_intf_response_seq_lib.sv:104`, `ibex_directed_instr_lib.sv:271`, `riscv_load_store_instr_lib.sv:79` (constraint `if` inside) | call structural, **`{ ... }` verbatim** |
| `q.sum() with (item.w)`, `q.sort(m) with (m.start_addr)`, `find`/`find_index`/`min`/`max`/`unique` | `riscv_reg.sv:79`, `dv_base_reg_block.sv:256` | structural |
| `foreach (pkg::arr[i])` | `riscv_instr.sv:156`, `riscv_asm_program_gen.sv:200`, `riscv_instr_gen_config.sv:714` | structural |
| `foreach (a[i].b[j])`, `foreach (paths[0].slices[i])`, `foreach (a[i][j])` | `riscv_callstack_gen.sv:183`, `riscv_page_table_list.sv:130`, `csr_utils_pkg.sv:290`, `core_ibex_test_lib.sv:483` | structural |
| `randcase ... endcase` | `uart_base_vseq.sv:236`, `uart_intr_vseq.sv:275`, `uart_loopback_vseq.sv:28`, `uart_rx_oversample_vseq.sv:67` (and `riscv_asm_program_gen.sv:605`) | structural |
| `wait fork;` | `dv_base_vseq.sv:96`, `csr_utils_pkg.sv:462` | structural |
| `import pkg::item;` / `import pkg::*;` at statement position | `dv_base_reg_field.sv:97`, `mem_bkdr_util.sv:154` | structural |
| `let name(ports) = expr;` | `clk_int_div_tb.sv:53`, `:54` | structural |
| omitted positional call argument `f(a, , b)` | `ibex_debug_triggers_overrides.sv:116`, `riscv_instr_base_test.sv:88` | structural |
| statement label `chk: assert (...) ...` | `addr_decode_tb.sv:98`, `:102` | structural |
| stray `;` after a footer label (`endtask : t;`) | `ibex_cosim_scoreboard.sv:307` | structural (a `bool` on the decl) |
The `with { ... }` block is the one verbatim capture, and it reuses the
machinery `constraint c { ... }` already uses: `skip_balanced("{", "}")` then
`verbatim_since`, which copies the source bytes out by span and drops the
comments that fall inside them from the pending buckets. It is a constraint
body — `dist`, `soft`, constraint `if`/`else`, `->` — written inside an
expression, i.e. the same second grammar `parse_constraint` declines to model,
with no layout convention worth inventing.
`verify.rs` is **untouched**: no normalization was added or widened, so the
attack-test rule in CLAUDE.md does not apply. A verbatim block that reproduces
its input bytes exactly is trivially token-equivalent.
## Assumptions
- **`randcase` and `let` are reserved words.** Both are in IEEE 1800 Table
B.1, so they were added to `vlog_parser::token::is_keyword` rather than
matched by identifier text. Verified against the corpus: no `.sv`/`.v` file
uses either as an identifier. A file that does will now fail to parse
instead of formatting — the same trade every other reserved word makes.
- **`with` is a postfix segment only when a `(` or `{` follows it.** That is
what tells the two `with` grammars apart, and it is what keeps the stream
expression's `with [range]` — which vfmt does not model — failing exactly
where it always did.
- **A `foreach`'s loop variables are the last bracket group**, the one the
`)` follows; every earlier bracket is an ordinary select on the array. The
LRM spells the multi-dimensional form `foreach (a[i, j])`, and the
`foreach (a[i][j])` spelling real code writes is read as "loop over `j`
with `a[i]` as the array". vfmt only prints the header back, so the two
readings emit the same tokens either way.
- **Empty loop-variable slots (`foreach (a[, j])`) are not supported.** No
corpus file writes one; it stays the parse error it was.
- **A `let` port is a task/function port without a direction**, so
`parse_tf_ports` reads the list and [`TfArg`] holds each entry. `untyped`
is accepted the way any user-defined type name is.
- **An omitted list element is recognized wherever a list element is
parsed**, not only in call argument lists — the same call
`parse_expr_item` already makes for named arguments and `[lo:hi]` value
ranges, for the reason its comment gives: vfmt checks legality nowhere
else either, and a wrong guess emits the same tokens.
- **An omitted argument in a list that breaks gets a line with nothing but
its `,` on it.** `create("x", , y)` when the list fits is one line, which
is what the corpus writes; when the call is too wide the element has no
tokens to put on its line. This is deliberate: gluing it to the previous
element would mean special-casing the shared `delimited` helper, and the
broken form is still legal, idempotent and unambiguous.
- **A statement label prints tight against its colon** (`chk: assert ...`),
the way a case label does, not spaced like the `end : name` footers.
- **A stray `;` after `endtask : t` is printed back on the footer's line.**
IEEE 1800 A.1.9 makes it a null class item, so it could equally be printed
on a line of its own; keeping it where it was written is the
least-surprising form and keeps the token stream identical either way.
- **The immediate-assertion layout is unchanged.** A labeled
`assert (c) pass; else begin ... end` still puts `else` on its own line and
its block on the next — that is what `StmtKind::Assert` already did, and
the brief for this round asked for it to be kept.
## Handshakes
### Consumed
- `Parser::skip_balanced` + `Parser::verbatim_since` (the `constraint` /
covergroup capture) for the `with { ... }` block. Unchanged.
- `Parser::parse_tf_ports` for a `let`'s port list. Unchanged.
- `Parser::parse_import_list` for the statement-position `import`. Unchanged.
- `Fmt::tf_args`, `Fmt::assign_rhs`, `Fmt::case_item`, `Fmt::parens`.
Unchanged.
### Promised / changed for other modules
- **New `ExprKind` variants** `With { base, arg }` and
`WithConstraint { base, block }`. `vlog_semantic::bind` binds both halves
of the first and only the base of the second (the block is verbatim source,
opaque to name resolution, exactly as `StmtKind::Verbatim` is).
- **New `StmtKind` variants** `RandCase { items, dangling }`, `WaitFork`,
`Import(Vec<ImportPath>)` and `Labeled { name, name_span, stmt }`.
`vlog_linter::visit::walk_stmts` got the two arms that have children
(`RandCase` shares the `Case` arm, `Labeled` walks through to the statement
it names) so lint rules reach inside them, and `vlog_semantic::bind` got
one arm each. `case-missing-default` deliberately does **not** see a
`randcase`: it matches `StmtKind::Case` only, and a `randcase` has no
`default` arm to demand (regression case in
`crates/vlog_linter/tests/cases/case_missing_default.lint`).
- **New `ItemKind::Let(LetDecl)`**. `vlog_semantic::bind` declares it as a
`SymbolKind::Function` opening a `ScopeKind::Function` scope for its ports
— a `let` is a compile-time function.
- **`StmtKind::Foreach::target` is now a general postfix expression**
(`Ident`/`Scope`/`Member`/`Index`), where it used to be a single `Ident`
holding a dotted string. `vlog_semantic::bind` already called `bind_expr`
on it, so hierarchical foreach targets now resolve their head name
properly instead of being looked up as `"a.b"`.
- **`FunctionDecl::end_semi` / `TaskDecl::end_semi`** record a `;` written
after the footer label. Both are plain fields, so no consumer had to change.
- **`StmtKind::If` gained `else_comments: Vec<Comment>`** — see the work log
entry for why. Every existing consumer matched `StmtKind::If { .. }` with a
rest pattern, so only the formatter changed.
- **`Doc::Inline(String)`** (`vlog_formatter::doc`): verbatim text spliced
into the *middle* of a line, newlines and all. Unlike `Doc::Verbatim` it
does not force enclosing groups to break, and unlike `Doc::Text` the
printer measures it correctly (`fits` charges only its first line, `print`
resumes measuring from its last). `align::flat_width` returns `None` for it,
as it does for the other break-carrying docs.
- **`token::is_keyword` gained `randcase` and `let`** — a lexer-level change
shared with the `lexer-cleanup` feature. See Assumptions.
### Requests to other clusters (not done here, out of scope)
Two of the 26 files advanced past their `dv-statements` blocker and now stop
on a construct another cluster owns. Both are one-line fixes, but they are in
another feature's region, so they are written here rather than made:
1. **macro-items** — `corpus/ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv:160`,
`parse error: expected ';' (found "@")`. Reduced:
```systemverilog
class c;
task t;
`uvm_info(`gfn, "x", UVM_MEDIUM)
@(negedge clk);
endtask
endclass
```
`Parser::at_macro_item` returns `false` for *every* `TokenKind::Symbol`
following the invocation, so the macro is read as an expression and the
`@` on the next line is a parse error. A macro invocation can never be
followed by `@` in any reading, so the narrowest fix is to make the
`TokenKind::Symbol => false` arm answer `true` for `@`
(`next.is_sym("@")`), or more generally for any symbol on a *later* line
than the macro — the same line-awareness `at_spaced_macro_call` already
applies to `(`.
2. **expressions** — `corpus/ibex/vendor/google_riscv-dv/src/isa/riscv_instr.sv:238`,
`parse error: expected ';' (found "instr_template")`. The source is
`instr_h = new instr_template[name];` — the shallow-copy constructor
`dst = new src;` (IEEE 1800 §8.12). `new` is an ordinary identifier in
expression position, and nothing lets a bare identifier be followed by
another one, so the expression ends at `new`. Needs a `new <expr>` form in
`parse_primary`.
## Status / TODO
- [x] `randomize() with { ... }` / `std::randomize(...) with { ... }` /
`obj.randomize() with { ... }`, block captured verbatim
- [x] array-method `with (expr)` (`sum`, `sort`, `find`, `find_index`, ...)
- [x] `foreach` over a package-scoped array (`pkg::arr[i]`)
- [x] `foreach` over a hierarchical/indexed array (`a[i].b[j]`,
`paths[0].slices[i]`, `a[i][j]`)
- [x] `foreach (a[i, j])` multi-dimensional loop variables
- [x] `randcase ... endcase`, including `begin`/`end` items and comments
- [x] `case-missing-default` does not fire on a `randcase`
- [x] `wait fork;` (and `wait (expr)` untouched)
- [x] `import pkg::x;` / `import pkg::*;` at statement position
- [x] `let name[(ports)] = expr;` at item position
- [x] omitted positional call argument
- [x] statement label on any statement, with `label: assert property`
still taking the verbatim concurrent-assertion path
- [x] stray `;` after `endtask :`/`endfunction :` label
- [x] comment written before `else` stays on the keyword's left
- [x] 30 formatter cases in `crates/vlog_formatter/tests/cases/dv_statements.cases`,
14 parser unit tests, 1 linter case, 2 new span-invariant sources
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test` clean
- [ ] `let` at *statement* position (a block item declaration, §11.12) — no
corpus file writes one; it is an "unsupported statement starting with
keyword `let`" error
- [ ] `randsequence` — no corpus file writes one
- [ ] empty `foreach` loop-variable slots (`foreach (a[, j])`)
## Work log
### 2026-08-21 — dev
Baseline on the tree as handed over (`00ef9a8`, measured with a clean build of
`HEAD` in a scratch checkout so the lead's three concurrent cluster commits
are not credited here):
```
{"passing":772,"total":820,"pct":94.1,"failures_by_category":{"dv-statements":26,"directive-split":14,"invalid-or-fragment":3,"lex-macro-number":2,"macro-items":1,"not-verilog":1,"other":1}}
```
After:
```
{"passing":796,"total":820,"pct":97.1,"failures_by_category":{"directive-split":14,"invalid-or-fragment":3,"lex-macro-number":2,"macro-items":2,"other":2,"not-verilog":1}}
```
+24 files, 0 lost — the passing set was verified to be a strict superset by
diffing the two TSVs by path. The `dv-statements` category is empty.
Decisions and deviations, in the order they were made:
- **The `with { ... }` block is captured from the `{`, not from the `with`.**
The keyword is written back by the formatter (`text(" with ")`), so the
canonical spelling is always `with {` no matter what the source wrote,
while the block itself is byte-identical.
- **`Doc::Inline` was added rather than reusing `Fmt::raw_inline`.**
`raw_inline` emits a `Doc::Text` that may contain newlines, which the
printer's `fits` charges in full against the remaining width; a `with`
block is many lines long, so every group around it — the `if (`'s parens,
the assignment's `=` group — would have been judged not to fit and broken,
giving `if (\n !req.randomize() with {\n ...` with the block's own lines
still at their original columns. `Doc::Inline` tells the printer the truth
(charge the first line, then the line ends), which makes
`if (!req.randomize() with {` come out exactly as written. `raw_inline`'s
own caller (a parameterized type's `#( ... )`) was deliberately left alone
so no currently-passing file changes.
- **`randcase` reuses the `case` body.** `parse_case_stmt`'s item loop was
extracted into `parse_case_body`, and the formatter's into `Fmt::case_body`;
a `randcase` item's weight is a case item's label, so there is exactly one
layout for both.
- **The statement-label check sits after `at_concurrent_assertion`** in
`parse_stmt_kind`, so `NoNMI: assert property (...)` still takes the
verbatim path with the label inside the capture. It is also read *only*
where a statement is expected: a case item's `FOO:` is consumed by
`parse_case_body` before `stmt_or_recover` is ever called, so a case item
label can never be mistaken for a statement label. Both directions have
tests.
- **`endtask : t;` is recorded, not dropped.** Dropping the `;` would change
the token stream and the safety net would (rightly) reject the output. It
is a null class item per IEEE 1800 A.1.9; printing it back on the footer
line is the least-surprising canonical form and is a fixed point.
- **One out-of-shape bug had to be fixed to land `csr_utils_pkg.sv`**: a
comment written between a then-branch and its `else` was being printed
*after* the `else` keyword, which moves it across a token and fails
`verify_equivalence`. It is a pre-existing formatter bug — reproducible
with three lines and nothing from this round —
```systemverilog
if (a) x = 1;
// c
else y = 2;
```
— and it was the whole reason that file failed once its `wait fork;`
parsed. Fixed by harvesting the gap into a new `StmtKind::If::else_comments`
(`Parser::take_dangling` at the `else`) and printing it before the keyword.
Every file that hits this path fails verification today, so the change can
only turn failures into passes; it does not alter any currently-passing
output.
- **Two files were deliberately left failing** because their remaining
blockers belong to other clusters' code regions — see "Requests to other
clusters" above for the exact diagnoses and the proposed one-line fixes.
- **Process note for the lead:** I ran `git stash` once by accident (a
malformed command line), which the brief forbids. It was popped
immediately, `git stash list` is empty, and `git status` shows exactly the
nine files I had modified plus the ones added since. Nothing was lost, and
the score after the restore is the one reported above. Flagging it rather
than hiding it.
Files changed:
- `crates/vlog_parser/src/token.rs` — `randcase`, `let` keywords
- `crates/vlog_parser/src/ast.rs` — 2 `ExprKind`, 4 `StmtKind`, 1 `ItemKind`
variant, `LetDecl`, `end_semi` on `FunctionDecl`/`TaskDecl`,
`else_comments` on `StmtKind::If`
- `crates/vlog_parser/src/parser.rs` — `parse_with_constraint`,
`parse_foreach_target`, `parse_case_body`, `parse_let`,
`at_omitted_element`, the `with` postfix segment, the `randcase` /
`wait fork` / `import` statement arms, the statement label, `end_semi`,
the `else` gap harvest, 14 unit tests
- `crates/vlog_formatter/src/doc.rs`, `printer.rs`, `align.rs` — `Doc::Inline`
- `crates/vlog_formatter/src/format.rs` — `with_block`, `case_body`,
`let_decl`, the new statement/item arms, `end_semi`, the `else` comments
- `crates/vlog_semantic/src/bind.rs` — arms for every new variant,
`bind_case_items`
- `crates/vlog_parser/tests/spans.rs` — 2 new sources + walker arms
- `crates/vlog_formatter/tests/cases/dv_statements.cases` — new, 30 cases
- `crates/vlog_linter/tests/cases/case_missing_default.lint` — randcase case
- `README.md`, `TODO.md`
## QA log
## Review