Files
lucisv/docs/features/dv-statements/README.md
T
lucioandClaude Fable 5 0557933994 QA round 1: adversarial review logs and a with-block attack test
No blocking findings over the 8 round-1 clusters: whole-corpus idempotency
and comment-preservation sweep clean (796/820), 476-run mutation fuzz clean,
no swallowed errors in the diff. Adds
reindented_string_inside_a_with_block_is_rejected. Findings (non-blocking)
are in each feature README's QA log; the printer fits() / Doc::Inline gap
is fixed separately.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-21 01:37:33 -07:00

22 KiB

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:

    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

  • randomize() with { ... } / std::randomize(...) with { ... } / obj.randomize() with { ... }, block captured verbatim
  • array-method with (expr) (sum, sort, find, find_index, ...)
  • foreach over a package-scoped array (pkg::arr[i])
  • foreach over a hierarchical/indexed array (a[i].b[j], paths[0].slices[i], a[i][j])
  • foreach (a[i, j]) multi-dimensional loop variables
  • randcase ... endcase, including begin/end items and comments
  • case-missing-default does not fire on a randcase
  • wait fork; (and wait (expr) untouched)
  • import pkg::x; / import pkg::*; at statement position
  • let name[(ports)] = expr; at item position
  • omitted positional call argument
  • statement label on any statement, with label: assert property still taking the verbatim concurrent-assertion path
  • stray ; after endtask :/endfunction : label
  • comment written before else stays on the keyword's left
  • 30 formatter cases in crates/vlog_formatter/tests/cases/dv_statements.cases, 14 parser unit tests, 1 linter case, 2 new span-invariant sources
  • 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 —
    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

2026-08-21 — round-1 adversarial QA

Verified: cargo test --workspace/clippy/fmt clean; corpus score 796/820; whole-corpus idempotency + comment-preservation sweep clean; 476-case mutation fuzz clean. Added one regression test to crates/vlog_formatter/tests/verification.rs (reindented_string_inside_a_with_block_is_rejected) locking in that the safety net would still reject a re-indented multi-line string inside a with { ... } block even if a future change broke Fmt::with_block's "never touch it" contract; cargo test -p vlog_formatter --test verification is green (100 passed) with it in.

Doc::Inline printer width accounting — real bug found (NON-BLOCKING: formatting-quality, not corruption).

with_block (format.rs fn with_block, ~line 246) emits the constraint body as Doc::Inline(raw.text.clone()) — always byte-for-byte, never re-indented. That part is correct and I could not break it: braces inside strings/comments inside the block don't confuse skip_balanced (lexer already collapses those to single tokens), multi-line strings inside the block survive untouched at every indent level tried, and it's idempotent in every case.

But printer.rs's fits() (the group flat/break decision) and print() disagree about what happens after a multi-line Doc::Inline:

  • print() (printer.rs ~line 33) correctly continues measuring from the end of the Inline's last line — i.e. whatever comes next in the doc keeps writing onto the same output line the Inline's } ended on. This matches the doc comment on Doc::Inline in doc.rs ("what follows it continues on the line the text ends on").
  • fits() (printer.rs ~line 137) treats a multi-line Doc::Inline like HardLine/Verbatim and returns early — return width - head.chars().count() as isize >= 0 — based only on the Inline's first line, without checking whatever comes after it in the same group. This is inconsistent with print()'s actual behavior: since nothing after the Inline starts on a fresh line, the group's fits-check needs to keep measuring past the Inline to know whether the rest of the line fits, but it stops and reports "fits" prematurely.

Repro (/private/tmp/.../scratchpad/qa/with5.sv):

if (a.randomize() with {
      x == 1;
      y == 2;
    } && some_really_quite_long_flag_name_that_would_overflow_the_line_length_for_sure)
  begin
    z = 1;
  end

target/release/vfmt --stdout --line-length 40 with5.sv keeps the whole } && some_really_quite_long_flag_name_that_would_overflow_the_line_length_for_sure) begin tail on one line (99 characters, well past the 40-column limit requested), where the same if condition without the with-block correctly wraps the && operands onto their own lines under --line-length 40 (verified with a matching ifbase.sv control case). The output is still valid Verilog, idempotent (cmp clean across two --stdout passes), and no content is lost — this is a line-length-target miss, not corruption — but it is exactly the class of bug the printer-width-accounting change was flagged as highest-risk for, so I'm logging it as a concrete, reproducible finding rather than "found nothing." Any group containing a multi-line with { ... } block followed by more content that needs to wrap will silently fail to wrap that trailing content.

Other targeted attacks:

  • with { ... } verbatim vs braces/strings/comments inside it. Braces inside a string ("brace } in string") and inside a comment (/* a } b { c */) inside a with block do not confuse skip_balanced/verify.rs; both round-trip byte-identical.
  • Comment right after .randomize( / before with / etc. Found a real (non-corrupting) gap parallel to the bind one: x.randomize /*c1*/ ( /*c2*/ ) /*c3*/ with /*c4*/ { a == 1; } /*c7*/ ; is rejected by the safety net (verification failed: token stream diverges ... input has comment "/*c1*/" ..., output has symbol "(" ...), exit 2, zero bytes written — clean, not corrupting, but a coverage gap (comments touching the .randomize()/with boundary currently make the statement unformattable rather than preserved-and-formatted).
  • General statement labels vs case-item labels vs label: assert property. A case body containing both a case-item label (1: y=1;) and, inside one arm's begin/end, a labeled concurrent assertion (my_label: assert property (...)) round-trips correctly and is idempotent; a top-level label: assert (cond) else $error(...); also round-trips.
  • Stray ; after endtask: name. endtask: t; → endtask : t; (label spacing normalized, the stray ; kept as a token, nothing dropped), idempotent.
  • Empty call argument f(a, , b) when the list breaks. Under --line-length 40 the empty argument gets its own line (, alone) when the call wraps; round-trips and is idempotent.

No BLOCKING findings for this cluster. The Doc::Inline fits() bug above is the one concrete "this is a real bug" result of the whole round — it's a formatting-quality regression, not a hard-invariant break, but given how the dev flagged this exact change as highest-risk, I'm surfacing it prominently rather than filing it as routine cosmetic feedback.