diff --git a/README.md b/README.md index 80f75fd..299f448 100644 --- a/README.md +++ b/README.md @@ -379,6 +379,19 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset: empty literal (`q = {};`), `new[expr]`, `$`-bound indexing (`q[$]`, `q[$-1]`) and queue method calls. See `docs/features/dynamic-types/README.md` +- DV statements (IEEE 1800 §7.12, §9.3.5, §11.12, §12.7.3, §13.4.2, §18.7, + §18.16): `randomize() with { ... }` / `std::randomize(x, y) with { ... }` + (the call is structural, the constraint block is **passed through + verbatim**, exactly as `constraint c { ... }` is), the array-method + iterator argument `q.sum() with (item.w)`, `foreach` over a + package-scoped or hierarchical array with selects on the way + (`foreach (pkg::isa[i])`, `foreach (h[id].sub[k])`, `foreach (a[i][j])`), + `randcase ... endcase`, `wait fork;`, `import pkg::x;` among a block's + declarations, `let name(ports) = expr;`, an omitted positional call + argument (`create("x", , `gfn)`), and a statement label on any statement + (`chk: assert (a) x++; else y++;`). A stray `;` after a task/function + footer label (`endtask : t;`) is reproduced where it was written. See + `docs/features/dv-statements/README.md` - DPI: `import "DPI-C" [context|pure] [c_name =] function|task ...;` — a function/task prototype with a linkage prefix, so the argument list breaks like any other; `export "DPI-C" [c_name =] function|task name;`; and package @@ -497,8 +510,8 @@ corpus baseline this ordering comes from: `virtual` interface types in every type position unblocked 28 corpus files and moved the parse rate from 86.8% to 90.2%; the other 3 advanced to blockers in the `expressions` and `other` buckets. Still open in this item: - specify blocks, `let`/`checker`, `program` and `interface class` — all rare - in the corpus RTL + specify blocks, `checker`, `program` and `interface class` — all rare + in the corpus RTL (`let` landed with item 10 below) 9. ~~Expressions: casts with a non-simple base, streaming concatenations, `->`/`<->` implication, drive strengths, attributes on port connections, the `'{N{0}}` assignment-pattern replication, `inside` a macro, and @@ -506,6 +519,14 @@ corpus baseline this ordering comes from: `docs/features/expressions-2/README.md`. Emptied the `expressions` bucket (21 files) plus one `other` file and moved the parse rate from 91.6% to 94.1% +10. ~~DV statements: `with` clauses, package-scoped/hierarchical `foreach`, + `randcase`, `wait fork`, block-level `import`, `let`, omitted call + arguments and statement labels~~ — **done**; see + `docs/features/dv-statements/README.md`. Emptied the `dv-statements` + bucket (26 files) and moved the parse rate from 94.1% to 97.1%; 24 of the + 26 files format, the other 2 advanced to a macro-items blocker and to the + `new obj` shallow-copy expression. `specify` blocks, `checker`, + `program`, `interface class` and `randsequence` remain unsupported Like ruff, `vfmt` refuses to output anything for a file it cannot fully parse, so it can never corrupt code. diff --git a/TODO.md b/TODO.md index 07c6a7a..e699220 100644 --- a/TODO.md +++ b/TODO.md @@ -355,6 +355,19 @@ Adapt each: (`compare_helper.sv`) advanced to a macro-items blocker (`` `MACRO expr`` in expression position). `dv-statements` (26 files) is still the top blocker. + → dv-statements (`docs/features/dv-statements/README.md`) then took it + from 772/820 (94.1%, the baseline on the same tree) to **796/820 + (97.1%)** — 24 of the 26 `dv-statements` files gained, 0 lost, passing + set verified as a strict superset. `randomize() with { ... }`, + array-method `with (expr)`, package-scoped and hierarchical `foreach`, + `randcase`, `wait fork`, block-level `import`, `let`, omitted call + arguments, statement labels and a stray `;` after a task/function + footer are done, along with a comment written before `else` (which had + been crossing the keyword and failing verification). The 2 files left + advanced to blockers other clusters own: `dv_base_vseq.sv` to + macro-items (a bare macro followed by `@` on the next line), + `riscv_instr.sv` to the `new obj` shallow-copy expression. + `directive-split` (14 files) is now the top blocker. - [ ] **[R] Fuzzing.** ruff fuzzes its parser. `cargo-fuzz` targets: (a) parser must never panic on arbitrary bytes, (b) for inputs that parse, format must satisfy equivalence + convergence. diff --git a/crates/vlog_formatter/src/align.rs b/crates/vlog_formatter/src/align.rs index 8f0e9d7..5367af1 100644 --- a/crates/vlog_formatter/src/align.rs +++ b/crates/vlog_formatter/src/align.rs @@ -164,7 +164,9 @@ pub fn flat_width(d: &Doc) -> Option { Doc::Concat(items) | Doc::Indent(items) | Doc::Group(items) => { items.iter().try_fold(0, |acc, d| Some(acc + flat_width(d)?)) } - Doc::HardLine | Doc::BlankLine | Doc::Verbatim(_) => None, + // `Inline` carries its own line breaks, so a row holding one has no + // flat width either. + Doc::HardLine | Doc::BlankLine | Doc::Verbatim(_) | Doc::Inline(_) => None, } } diff --git a/crates/vlog_formatter/src/doc.rs b/crates/vlog_formatter/src/doc.rs index 38c6301..5417b83 100644 --- a/crates/vlog_formatter/src/doc.rs +++ b/crates/vlog_formatter/src/doc.rs @@ -7,6 +7,14 @@ pub enum Doc { /// Verbatim text. Must not contain newlines (use `HardLine`). Text(String), + /// Verbatim text spliced into the *middle* of a line, newlines and all: + /// the `{ ... }` of a `randomize() with { ... }` constraint block. It + /// carries its own indentation, so the printer copies it through + /// untouched and resumes measuring from its last line. Unlike + /// [`Doc::Verbatim`] it does not force enclosing groups to break — the + /// text starts on the current line, and what follows it continues on the + /// line the text ends on. + Inline(String), /// A space when flat, a newline when the enclosing group breaks. Line, /// Nothing when flat, a newline when the enclosing group breaks. diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs index e69a0ce..e6c0323 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -241,6 +241,18 @@ impl<'a> Fmt<'a> { text(raw.text.clone()) } + /// The `{ ... }` of a `randomize() with { ... }`: verbatim source spliced + /// into the middle of a line. + /// + /// Like [`Fmt::raw_inline`] it is reproduced byte for byte — the block is + /// a constraint body vfmt does not model, so there is no layout to apply + /// and re-indenting it would only drift on every pass — but the printer + /// is told about the line breaks inside it, so the expression around it + /// is still measured against the line width correctly. + fn with_block(&self, raw: &RawText) -> Doc { + Doc::Inline(raw.text.clone()) + } + /// A macro invocation standing as an item or a statement. The invocation /// itself is verbatim source — we do not expand macros, so re-spacing the /// argument list would be guesswork — and the trailing `;` is reproduced @@ -1008,6 +1020,7 @@ impl<'a> Fmt<'a> { ItemKind::GenCase(g) => self.gen_case(g, depth), ItemKind::Function(f) => self.function(f), ItemKind::Task(t) => self.task(t), + ItemKind::Let(l) => self.let_decl(l), ItemKind::Class(c) => self.class(c, depth), ItemKind::Modport(decls) => self.modport(decls), ItemKind::Clocking(c) => self.clocking(c), @@ -2168,6 +2181,18 @@ impl<'a> Fmt<'a> { } } + /// `let max(a, b) = (a > b) ? a : b;` (IEEE 1800 §11.12) — a name, an + /// optional port list laid out like a function's, and one expression. + fn let_decl(&self, l: &LetDecl) -> Doc { + let mut docs = vec![text(format!("let {}", l.name))]; + if l.has_parens { + docs.push(self.tf_args(&l.ports)); + } + docs.push(text(" =")); + docs.push(self.assign_rhs(self.expr(&l.value))); + concat(vec![group(docs), text(";")]) + } + fn function(&self, f: &FunctionDecl) -> Doc { let mut header = Vec::new(); if let Some(d) = &f.dpi { @@ -2210,6 +2235,7 @@ impl<'a> Fmt<'a> { indent(body), Doc::HardLine, Self::closing("endfunction", &f.end_label), + text(if f.end_semi { ";" } else { "" }), ]) } @@ -2247,6 +2273,7 @@ impl<'a> Fmt<'a> { indent(body), Doc::HardLine, Self::closing("endtask", &t.end_label), + text(if t.end_semi { ";" } else { "" }), ]) } @@ -2400,7 +2427,9 @@ impl<'a> Fmt<'a> { docs.push(Self::closing(join_kw, end_label)); concat(docs) } - StmtKind::If { qualifier, cond, then, els } => self.if_stmt(qualifier, cond, then, els), + StmtKind::If { qualifier, cond, then, else_comments, els } => { + self.if_stmt(qualifier, cond, then, else_comments, els) + } StmtKind::Case { qualifier, kw, expr, inside, items, dangling } => { let mut head = String::new(); if let Some(q) = qualifier { @@ -2413,19 +2442,14 @@ impl<'a> Fmt<'a> { if *inside { docs.push(text(" inside")); } - let mut body = Vec::new(); - for item in items { - body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); - body.extend(self.leading(&item.meta)); - body.push(self.case_item(item)); - body.extend(self.trailing(&item.meta)); - } - body.extend(self.dangling(dangling)); - docs.push(indent(body)); - docs.push(Doc::HardLine); - docs.push(text("endcase")); + docs.push(self.case_body(items, dangling)); concat(docs) } + // `randcase` is a `case` body with weights for labels and no + // selector, so it shares the body layout. + StmtKind::RandCase { items, dangling } => { + concat(vec![text("randcase"), self.case_body(items, dangling)]) + } StmtKind::For { init, cond, step, body } => { let mut header = vec![text("for (")]; let init_parts: Vec = init @@ -2553,6 +2577,13 @@ impl<'a> Fmt<'a> { StmtKind::Break => text("break;"), StmtKind::Continue => text("continue;"), StmtKind::Disable(name) => text(format!("disable {name};")), + StmtKind::WaitFork => text("wait fork;"), + StmtKind::Import(paths) => text(format!("import {};", join_paths(paths))), + // A statement label prints tight against its `:`, the way a case + // label does: `check_decode: assert (...)`. + StmtKind::Labeled { name, stmt, .. } => { + concat(vec![text(format!("{name}: ")), self.stmt(stmt)]) + } StmtKind::Directive(d) => self.raw_text(d), // See `ItemKind::Error`: unreachable from `format_source`, present // so the match stays total. @@ -2589,6 +2620,7 @@ impl<'a> Fmt<'a> { qualifier: &Option, cond: &Expr, then: &Stmt, + else_comments: &[Comment], els: &Option>, ) -> Doc { let mut head = String::new(); @@ -2601,18 +2633,30 @@ impl<'a> Fmt<'a> { let then_is_block = matches!(then.kind, StmtKind::Block { .. }); let mut docs = vec![self.stmt_as_body(prefix, then)]; if let Some(els) = els { - if then_is_block { + // A comment written before `else` prints before it, each on its + // own line: it is where the source put it, and after the keyword + // it would have crossed a token. + if !else_comments.is_empty() { + docs.push(Doc::HardLine); + for c in else_comments { + docs.push(self.comment(c)); + docs.push(Doc::HardLine); + } + docs.push(text("else")); + } else if then_is_block { docs.push(text(" else")); } else { docs.push(Doc::HardLine); docs.push(text("else")); } // `else if` chains stay flat. - if let StmtKind::If { qualifier: eq, cond: ec, then: et, els: ee } = &els.kind { + if let StmtKind::If { qualifier: eq, cond: ec, then: et, else_comments: ecm, els: ee } = + &els.kind + { docs.push(text(" ")); let mut meta_docs = self.leading(&els.meta); docs.append(&mut meta_docs); - docs.push(self.if_stmt(eq, ec, et, ee)); + docs.push(self.if_stmt(eq, ec, et, ecm, ee)); docs.extend(self.trailing(&els.meta)); } else { docs.push(self.stmt_as_body(text(""), els)); @@ -2672,6 +2716,20 @@ impl<'a> Fmt<'a> { self.stmt_as_body(self.case_labels(&item.labels), &item.stmt) } + /// The indented items of a `case`/`randcase` body and the `endcase` that + /// closes it. + fn case_body(&self, items: &[CaseItem], dangling: &[Comment]) -> Doc { + let mut body = Vec::new(); + for item in items { + body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + body.extend(self.leading(&item.meta)); + body.push(self.case_item(item)); + body.extend(self.trailing(&item.meta)); + } + body.extend(self.dangling(dangling)); + concat(vec![indent(body), Doc::HardLine, text("endcase")]) + } + // ------------------------------------------------------------------ // Expressions // ------------------------------------------------------------------ @@ -2812,6 +2870,12 @@ impl<'a> Fmt<'a> { text("}"), ]), ExprKind::Postfix { expr, op } => concat(vec![self.expr(expr), text(op.clone())]), + ExprKind::With { base, arg } => { + concat(vec![self.expr(base), text(" with "), self.expr(arg)]) + } + ExprKind::WithConstraint { base, block } => { + concat(vec![self.expr(base), text(" with "), self.with_block(block)]) + } ExprKind::Inside { lhs, ranges } => { concat(vec![self.expr(lhs), text(" inside "), self.expr_list("{", ranges, "}")]) } diff --git a/crates/vlog_formatter/src/printer.rs b/crates/vlog_formatter/src/printer.rs index 1e54eae..570600f 100644 --- a/crates/vlog_formatter/src/printer.rs +++ b/crates/vlog_formatter/src/printer.rs @@ -30,6 +30,15 @@ impl Printer { out.push_str(s); col += s.chars().count(); } + Doc::Inline(s) => { + out.push_str(s); + // The text brought its own line breaks: keep measuring + // from the last one it wrote. + col = match s.rsplit_once('\n') { + Some((_, last)) => last.chars().count(), + None => col + s.chars().count(), + }; + } Doc::Concat(items) => { for item in items.iter().rev() { stack.push((ind, mode, item)); @@ -125,6 +134,12 @@ impl Printer { let Some((mode, d)) = stack.pop() else { return true }; match d { Doc::Text(s) => width -= s.chars().count() as isize, + Doc::Inline(s) => match s.split_once('\n') { + // Only the first line shares the current line; if it + // fits, the rest of the group starts after a break. + Some((head, _)) => return width - head.chars().count() as isize >= 0, + None => width -= s.chars().count() as isize, + }, Doc::Concat(items) | Doc::Indent(items) => { for it in items.iter().rev() { stack.push((mode, it)); diff --git a/crates/vlog_formatter/tests/cases/dv_statements.cases b/crates/vlog_formatter/tests/cases/dv_statements.cases new file mode 100644 index 0000000..3a3cde1 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/dv_statements.cases @@ -0,0 +1,578 @@ +#a randomize() with { ... } condition keeps its constraint block verbatim (ibex_mem_intf_response_seq_lib.sv:104) +class c; + task body(); + if (!req.randomize() with { + addr == item.addr; + read_write == item.read_write; + }) begin + `uvm_fatal(`gfn, "Cannot randomize response request") + end + endtask +endclass +---- +class c; + task body(); + if (!req.randomize() with { + addr == item.addr; + read_write == item.read_write; + }) begin + `uvm_fatal(`gfn, "Cannot randomize response request") + end + endtask +endclass +==== +#std::randomize(x) with { ... } as an assignment right-hand side (cb_filter_tb.sv:272) +module m; + task automatic rand_wait(input int unsigned min, max); + int unsigned rand_success, cycles; + rand_success = std::randomize(cycles) with { + cycles >= min; + cycles <= max; + }; + endtask +endmodule +---- +module m; + task automatic rand_wait(input int unsigned min, max); + int unsigned rand_success, cycles; + rand_success = std::randomize(cycles) with { + cycles >= min; + cycles <= max; + }; + endtask +endmodule +==== +#a dist { } inside the constraint block is part of the verbatim capture (ibex_mem_intf_response_driver.sv:94) +class c; + task body(); + if (!std::randomize(gnt_delay) with { + gnt_delay dist { + cfg.gnt_delay_min :/ 10, + [cfg.gnt_delay_min+1 : cfg.gnt_delay_max-1] :/ 5 + }; + }) begin + `uvm_fatal(`gfn, "Cannot randomize grant") + end + endtask +endclass +---- +class c; + task body(); + if (!std::randomize(gnt_delay) with { + gnt_delay dist { + cfg.gnt_delay_min :/ 10, + [cfg.gnt_delay_min+1 : cfg.gnt_delay_max-1] :/ 5 + }; + }) begin + `uvm_fatal(`gfn, "Cannot randomize grant") + end + endtask +endclass +==== +#a constraint if inside the block is verbatim too (riscv_load_store_instr_lib.sv:79) +class c; + function void f(); + if (!std::randomize(offset_, addr_) with { + if (locality == NARROW) { + soft offset_ inside {[-16:16]}; + } else { + soft offset_ inside {[-64:64]}; + } + addr_ == base + offset_; + }) begin + `uvm_fatal(`gfn, "Cannot randomize load/store offset") + end + endfunction +endclass +---- +class c; + function void f(); + if (!std::randomize(offset_, addr_) with { + if (locality == NARROW) { + soft offset_ inside {[-16:16]}; + } else { + soft offset_ inside {[-64:64]}; + } + addr_ == base + offset_; + }) begin + `uvm_fatal(`gfn, "Cannot randomize load/store offset") + end + endfunction +endclass +==== +#a string carrying a newline inside the constraint block survives byte for byte +class c; + function void f(); + void'(std::randomize(x) with { + msg == "line one +line two"; + x > 0; + }); + endfunction +endclass +---- +class c; + function void f(); + void'(std::randomize(x) with { + msg == "line one +line two"; + x > 0; + }); + endfunction +endclass +==== +#a comment inside the constraint block stays inside it, and one after the block stays outside +class c; + function void f(); + void'(std::randomize(x) with { + // pick something small + x < 4; + }); // done + endfunction +endclass +---- +class c; + function void f(); + void'(std::randomize(x) with { + // pick something small + x < 4; + }); // done + endfunction +endclass +==== +#a one-line constraint block stays on its line +class c; + function void f(); + if (!req.randomize() with { addr == 0; }) $fatal(1, "no"); + endfunction +endclass +---- +class c; + function void f(); + if (!req.randomize() with { addr == 0; }) $fatal(1, "no"); + endfunction +endclass +==== +#array-method with (expr): sum, sort and find (riscv_reg.sv:79, dv_base_reg_block.sv:256) +class c; + function void f(); + total_len = fld.sum() with (item.bit_width); + mapped_addr_ranges.sort(m) with (m.start_addr); + q = list.find() with (item > 3); + n = list.find_index with (item.x == 1); + endfunction +endclass +---- +class c; + function void f(); + total_len = fld.sum() with (item.bit_width); + mapped_addr_ranges.sort(m) with (m.start_addr); + q = list.find() with (item > 3); + n = list.find_index with (item.x == 1); + endfunction +endclass +==== +#foreach over a package-scoped array (riscv_instr.sv:156) +class c; + function void f(); + foreach(riscv_instr_pkg::supported_isa[i]) begin + basic_instr = {basic_instr, C_EBREAK}; + end + endfunction +endclass +---- +class c; + function void f(); + foreach (riscv_instr_pkg::supported_isa[i]) begin + basic_instr = {basic_instr, C_EBREAK}; + end + endfunction +endclass +==== +#foreach over a hierarchical array with a select on the way (riscv_callstack_gen.sv:183, riscv_page_table_list.sv:130) +class c; + function void f(); + foreach(program_h[id].sub_program_id[k]) begin + program_h[id].sub_program_id[k] = sub_program_id_pool[idx]; + end + foreach(page_table[i].pte[j]) idx++; + endfunction +endclass +---- +class c; + function void f(); + foreach (program_h[id].sub_program_id[k]) begin + program_h[id].sub_program_id[k] = sub_program_id_pool[idx]; + end + foreach (page_table[i].pte[j]) idx++; + endfunction +endclass +==== +#foreach over a literal index followed by a member select (csr_utils_pkg.sv:290) +class c; + function void f(); + foreach (paths[0].slices[i]) str = $sformatf("%0s", paths[0].slices[i].path); + endfunction +endclass +---- +class c; + function void f(); + foreach (paths[0].slices[i]) str = $sformatf("%0s", paths[0].slices[i].path); + endfunction +endclass +==== +#a nested foreach whose inner array repeats the outer loop variable (core_ibex_test_lib.sv:483) +class c; + function void f(); + foreach (data_valid[i]) begin + foreach (data_valid[i][j]) data_valid[i][j] = 1'b0; + end + endfunction +endclass +---- +class c; + function void f(); + foreach (data_valid[i]) begin + foreach (data_valid[i][j]) data_valid[i][j] = 1'b0; + end + endfunction +endclass +==== +#the multi-dimensional spelling puts every loop variable in one bracket group +class c; + function void f(); + foreach (arr[i,j]) arr[i][j] = 0; + endfunction +endclass +---- +class c; + function void f(); + foreach (arr[i, j]) arr[i][j] = 0; + endfunction +endclass +==== +#randcase items are case items without a selector (uart_rx_oversample_vseq.sv:67) +class c; + task t(); + randcase + 1: pattern = (1 << num_bits) - 1; // all 1s + 1: pattern = 0; + endcase + endtask +endclass +---- +class c; + task t(); + randcase + 1: pattern = (1 << num_bits) - 1; // all 1s + 1: pattern = 0; + endcase + endtask +endclass +==== +#a randcase item may be a begin/end block, and comments keep their place (uart_base_vseq.sv:236) +class c; + task t(); + randcase + // read one byte + 1: begin + csr_rd(.ptr(ral.fifo_status), .value(fifo_status)); + end + + 5: drive_line_loopback(); + // nothing left to read + endcase + endtask +endclass +---- +class c; + task t(); + randcase + // read one byte + 1: begin + csr_rd(.ptr(ral.fifo_status), .value(fifo_status)); + end + + 5: drive_line_loopback(); + // nothing left to read + endcase + endtask +endclass +==== +#case-missing-default does not fire on a randcase: it has no default arm +class c; + task t(); + randcase + 1: a = 0; + 1: a = 1; + endcase + endtask +endclass +---- +class c; + task t(); + randcase + 1: a = 0; + 1: a = 1; + endcase + endtask +endclass +==== +#wait fork; inside an isolation fork (dv_base_vseq.sv:96) +class c; + task t(); + fork + begin : isolation_fork + fork + apply_reset(); + join_none + wait fork; + end : isolation_fork + join + endtask +endclass +---- +class c; + task t(); + fork + begin : isolation_fork + fork + apply_reset(); + join_none + wait fork; + end : isolation_fork + join + endtask +endclass +==== +#wait fork as the body of an if, and an ordinary wait (expr) beside it (csr_utils_pkg.sv:462) +class c; + task t(); + if (blocking) wait fork; + wait (done == 1); + wait (ready) x = 1; + endtask +endclass +---- +class c; + task t(); + if (blocking) wait fork; + wait (done == 1); + wait (ready) x = 1; + endtask +endclass +==== +#a comment written before else stays on the else's left +class c; + task t(); + if (blocking) wait fork; + // Add #0 to ensure that this thread starts executing first + else #0; + endtask +endclass +---- +class c; + task t(); + if (blocking) wait fork; + // Add #0 to ensure that this thread starts executing first + else #0; + endtask +endclass +==== +#import as the first statement of a function body (dv_base_reg_field.sv:97) +class c; + function uvm_reg_data_t mubi_or_hi(uvm_reg_data_t a); + import prim_mubi_pkg::*; + uvm_reg_data_t out; + return out; + endfunction +endclass +---- +class c; + function uvm_reg_data_t mubi_or_hi(uvm_reg_data_t a); + import prim_mubi_pkg::*; + uvm_reg_data_t out; + return out; + endfunction +endclass +==== +#imports among a block's declarations (mem_bkdr_util.sv:154) +class c; + function void f(); + if (`HAS_ECC) begin + import prim_secded_pkg::prim_secded_e; + import prim_secded_pkg::get_ecc_data_width, prim_secded_pkg::get_ecc_parity_width; + prim_secded_e secded_eds; + end + endfunction +endclass +---- +class c; + function void f(); + if (`HAS_ECC) begin + import prim_secded_pkg::prim_secded_e; + import prim_secded_pkg::get_ecc_data_width, prim_secded_pkg::get_ecc_parity_width; + prim_secded_e secded_eds; + end + endfunction +endclass +==== +#a let declaration at module scope (clk_int_div_tb.sv:53) +module m; + let max(a,b) = (a > b) ? a : b; + let min(a,b) = (a < b) ? a : b; +endmodule +---- +module m; + let max(a, b) = (a > b) ? a : b; + let min(a, b) = (a < b) ? a : b; +endmodule +==== +#a let with typed ports, a default, and the port-less spelling +module m; + let f(int a, untyped b = 0) = a + b; + let ready = valid && !stall; +endmodule +---- +module m; + let f(int a, untyped b = 0) = a + b; + let ready = valid && !stall; +endmodule +==== +#an omitted positional argument keeps its place in the list (riscv_instr_base_test.sv:88) +class c; + function void f(); + asm_gen = riscv_asm_program_gen::type_id::create("asm_gen", , `gfn); + endfunction +endclass +---- +class c; + function void f(); + asm_gen = riscv_asm_program_gen::type_id::create("asm_gen", , `gfn); + endfunction +endclass +==== +#a labeled immediate assertion (addr_decode_tb.sv:98) +module m; + always @(addr) #0 begin : proc_check_decode + check_decode: assert (idx == addr_map[0].idx) passed_checks++; else begin + failed_checks++; + $warning("Decoder did not decode correctly."); + end + end +endmodule +---- +module m; + always @(addr) #0 begin : proc_check_decode + check_decode: assert (idx == addr_map[0].idx) passed_checks++; + else + begin + failed_checks++; + $warning("Decoder did not decode correctly."); + end + end +endmodule +==== +#a label on an ordinary statement, and one on a block +module m; + initial begin + step_one: x = 1; + step_two: begin + y = 2; + end + end +endmodule +---- +module m; + initial begin + step_one: x = 1; + step_two: begin + y = 2; + end + end +endmodule +==== +#a label in front of a concurrent assertion stays part of the verbatim capture +module m; + initial begin + NoNMI: assert property (@(posedge clk) a |-> b) else $error("nmi"); + end +endmodule +---- +module m; + initial begin + NoNMI: assert property (@(posedge clk) a |-> b) else $error("nmi"); + end +endmodule +==== +#a case item label is not a statement label +module m; + initial begin + case (x) + FOO: begin + y = 1; + end + default: y = 0; + endcase + end +endmodule +---- +module m; + initial begin + case (x) + FOO: begin + y = 1; + end + default: y = 0; + endcase + end +endmodule +==== +#a stray semicolon after an endtask label is printed where it was written (ibex_cosim_scoreboard.sv:307) +class c; + task run_cosim_imem_errors(); + x = 1; + endtask: run_cosim_imem_errors; + + function void f(); + endfunction : f; +endclass +---- +class c; + task run_cosim_imem_errors(); + x = 1; + endtask : run_cosim_imem_errors; + + function void f(); + endfunction : f; +endclass +==== +#the whole cluster inside a format-off fence comes out byte-exact +module m; +// verilog_format: off + let max(a,b) = (a>b)?a:b; + initial begin + foreach( pkg::arr[i] ) x=1; + randcase + 1: y=0; + endcase + if(!r.randomize() with { a==1; }) $fatal(1,"x"); + end +// verilog_format: on + initial x = 1; +endmodule +---- +module m; +// verilog_format: off + let max(a,b) = (a>b)?a:b; + initial begin + foreach( pkg::arr[i] ) x=1; + randcase + 1: y=0; + endcase + if(!r.randomize() with { a==1; }) $fatal(1,"x"); + end +// verilog_format: on + initial x = 1; +endmodule +==== diff --git a/crates/vlog_linter/src/visit.rs b/crates/vlog_linter/src/visit.rs index 48d9e73..a99e3d8 100644 --- a/crates/vlog_linter/src/visit.rs +++ b/crates/vlog_linter/src/visit.rs @@ -77,11 +77,14 @@ pub(crate) fn walk_stmts(stmt: &Stmt, f: &mut dyn FnMut(&Stmt)) { walk_stmts(els, f); } } - StmtKind::Case { items, .. } => { + StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => { for case_item in items { walk_stmts(&case_item.stmt, f); } } + // A label wraps the statement it names; the rules care about the + // statement, not the label. + StmtKind::Labeled { stmt: inner, .. } => walk_stmts(inner, f), StmtKind::For { body, .. } | StmtKind::While { body, .. } | StmtKind::DoWhile { body, .. } diff --git a/crates/vlog_linter/tests/cases/case_missing_default.lint b/crates/vlog_linter/tests/cases/case_missing_default.lint index 3b8d14a..1e06003 100644 --- a/crates/vlog_linter/tests/cases/case_missing_default.lint +++ b/crates/vlog_linter/tests/cases/case_missing_default.lint @@ -48,3 +48,14 @@ module m; //^ 13 unused-waiver end endmodule + +==== +# a randcase has no default arm to demand: the rule leaves it alone +class c; + task t(); + randcase + 1: x = 0; + 5: x = 1; + endcase + endtask +endclass diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index aa010a0..f654c82 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -230,6 +230,8 @@ pub enum ItemKind { GenCase(GenCase), Function(FunctionDecl), Task(TaskDecl), + /// `let name(ports) = expr;` (IEEE 1800 §11.12). + Let(LetDecl), /// A `class` / `virtual class` declaration and its body. Class(ClassDecl), /// `modport a (input x, output y), b (...);` (IEEE 1800 §25.5). One @@ -1018,6 +1020,10 @@ pub struct FunctionDecl { pub end_label: Option, /// Byte range of `end_label`. pub end_label_span: Option, + /// True when a `;` was written after the footer (`endfunction : f;`) — a + /// null class item (IEEE 1800 A.1.9), reproduced where it was written so + /// the token stream is unchanged. + pub end_semi: bool, } #[derive(Debug)] @@ -1044,6 +1050,26 @@ pub struct TaskDecl { pub end_label: Option, /// Byte range of `end_label`. pub end_label_span: Option, + /// True when a `;` was written after the footer; see + /// [`FunctionDecl::end_semi`]. + pub end_semi: bool, +} + +/// A `let` declaration: `let max(a, b) = (a > b) ? a : b;` (IEEE 1800 §11.12). +/// +/// A `let` port is the same `[type] name [= default]` a task/function port is +/// minus the direction keyword, so the ports reuse [`TfArg`] rather than +/// growing a near-identical node of their own. +#[derive(Debug)] +pub struct LetDecl { + pub name: String, + /// Byte range of `name`. + pub name_span: TextRange, + /// False for the port-less spelling `let x = expr;` — an empty `()` was + /// written when this is true and [`LetDecl::ports`] is empty. + pub has_parens: bool, + pub ports: Vec, + pub value: Expr, } #[derive(Debug)] @@ -1097,6 +1123,10 @@ pub enum StmtKind { qualifier: Option, cond: Expr, then: Box, + /// Comments written between the then-branch and the `else` keyword. + /// They are kept here, not on `els`, because printing them after the + /// keyword moves them across it and the safety net rejects that. + else_comments: Vec, els: Option>, }, Case { @@ -1130,11 +1160,43 @@ pub enum StmtKind { Forever { body: Box, }, + /// `foreach (arr[i, j]) stmt` (IEEE 1800 §12.7.3). + /// + /// `target` is the array being iterated, which may be a package-scoped or + /// hierarchical name with index and member selects along the way + /// (`riscv_instr_pkg::supported_isa`, `page_table[i].pte`); `vars` are the + /// names in the *last* bracket group, the only one that declares loop + /// variables. Foreach { target: Expr, vars: Vec, body: Box, }, + /// `randcase w1 : stmt; w2 : stmt; endcase` (IEEE 1800 §18.16) — a `case` + /// whose items are weights and which has no selector expression. + RandCase { + items: Vec, + dangling: Vec, + }, + /// `wait fork;` — block until every child process finishes + /// (IEEE 1800 §9.6.1). `fork` is a keyword, not an expression, which is + /// why this is not a [`StmtKind::Wait`]. + WaitFork, + /// `import pkg::item;` / `import pkg::*;` standing among a block's + /// declarations (IEEE 1800 §13.4.2) — the statement twin of + /// [`ItemKind::Import`]. + Import(Vec), + /// `name : stmt` — a statement label (IEEE 1800 §9.3.5). + /// + /// `begin`/`fork` keep their label inside their own node, because the + /// source writes it *after* the keyword; this is the general prefix form, + /// which any statement may carry. + Labeled { + name: String, + /// Byte range of `name`. + name_span: TextRange, + stmt: Box, + }, /// Blocking/nonblocking/compound assignment. Assign { lhs: Expr, @@ -1366,6 +1428,22 @@ pub enum ExprKind { /// The macro invocation token, exactly as written. set: String, }, + /// `expr with (expr)` — the iterator argument of an array method + /// (IEEE 1800 §7.12): `fld.sum() with (item.bit_width)`. The argument is + /// an ordinary parenthesized expression, so `base` and `arg` are both + /// laid out structurally. + With { + base: Box, + arg: Box, + }, + /// `expr with { ... }` — the inline constraint block of a `randomize` + /// call (IEEE 1800 §18.7). The block is a `constraint` body written in an + /// expression, so it is kept byte-for-byte exactly as + /// [`ItemKind::Verbatim`]'s `constraint c { ... }` is. + WithConstraint { + base: Box, + block: RawText, + }, /// A named call argument: the `.ptr(ral.ovrd)` of /// `csr_wr(.ptr(ral.ovrd), .value(x))`. `value` is [`ExprKind::Empty`] /// for `.name()`, exactly as an empty connection is. diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index 7b21357..bd62571 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -716,12 +716,25 @@ impl<'a> Parser<'a> { self.parse_named_arg()? } else if self.cur().is_sym("[") { self.parse_value_range()? + } else if self.at_omitted_element() { + // An omitted positional argument: `create("asm_gen", , `gfn)` + // (`riscv_instr_base_test.sv:88`) takes the parameter's default + // (IEEE 1800 §13.5.3). It is an element with no tokens at all, + // recognized here for the reason the two shapes above are. + self.expr_at(start, ExprKind::Empty(Vec::new())) } else { self.parse_expr()? }; Ok(ExprItem { meta, expr, span: self.span_from(start) }) } + /// True when the cursor stands where a list element belongs but the + /// source wrote none: the next token already closes the element. + fn at_omitted_element(&self) -> bool { + let t = self.cur(); + t.is_sym(",") || t.is_sym(")") + } + /// `.name(expr)` / `.name()` — a named call argument. The cursor is on /// the `.` and the next token is an identifier. fn parse_named_arg(&mut self) -> PResult { @@ -1195,6 +1208,7 @@ impl<'a> Parser<'a> { "function" => self.parse_function().map(ItemKind::Function), "task" => self.parse_task().map(ItemKind::Task), "class" => self.parse_class().map(ItemKind::Class), + "let" => self.parse_let().map(ItemKind::Let), "constraint" => self.parse_constraint().map(ItemKind::Verbatim), "covergroup" => self.parse_covergroup().map(ItemKind::Verbatim), "assert" | "assume" | "cover" if self.at_concurrent_assertion() => { @@ -1552,6 +1566,24 @@ impl<'a> Parser<'a> { Ok(self.verbatim_since(start, col)) } + /// The `{ ... }` of a `randomize() with { ... }` inline constraint + /// (IEEE 1800 §18.7), kept as verbatim source. + /// + /// It is a `constraint` body written inside an expression — the same + /// second grammar (`dist`, `soft`, constraint `if`, `->`) that + /// [`Parser::parse_constraint`] declines to model — so it gets exactly + /// the same treatment: skip to the matching brace and copy the bytes out. + /// The `with` keyword itself is left outside the capture; the formatter + /// writes it back. + fn parse_with_constraint(&mut self) -> PResult { + self.expect_kw("with")?; + let start = self.here(); + let col = self.cur().col; + self.expect_sym("{")?; + self.skip_balanced("{", "}")?; + Ok(self.verbatim_since(start, col)) + } + /// `covergroup name ... endgroup [: label]`, kept as verbatim source, for /// the same reason constraints are: coverpoints, bins and crosses are a /// separate grammar with nothing to gain from canonical layout. @@ -3084,6 +3116,10 @@ impl<'a> Parser<'a> { self.parse_tf_body("endfunction")? }; let (end_label, end_label_span) = split_label(end); + // `endfunction : f;` — the stray `;` is a null class item + // (IEEE 1800 A.1.9). It is recorded here so the footer can print it + // back where it was written instead of on a line of its own. + let end_semi = !is_prototype && self.eat_sym(";"); Ok(FunctionDecl { dpi, prefix, @@ -3099,6 +3135,7 @@ impl<'a> Parser<'a> { dangling, end_label, end_label_span, + end_semi, }) } @@ -3124,6 +3161,8 @@ impl<'a> Parser<'a> { self.parse_tf_body("endtask")? }; let (end_label, end_label_span) = split_label(end); + // See `parse_function_decl`: a stray `;` after the footer. + let end_semi = !is_prototype && self.eat_sym(";"); Ok(TaskDecl { dpi, prefix, @@ -3138,9 +3177,28 @@ impl<'a> Parser<'a> { dangling, end_label, end_label_span, + end_semi, }) } + /// `let name [( ports )] = expr;` (IEEE 1800 §11.12), corpus + /// `common_cells/test/clk_int_div_tb.sv:53`. + /// + /// A `let` port is a task/function port without a direction — an optional + /// type, a name, optional dimensions and an optional default — so the + /// port list is read by [`Parser::parse_tf_ports`]. A `let` with no ports + /// writes no parens at all, which is what `has_parens` records. + fn parse_let(&mut self) -> PResult { + self.expect_kw("let")?; + let Name { text: name, span: name_span } = self.expect_name()?; + let has_parens = self.cur().is_sym("("); + let ports = self.parse_tf_ports()?; + self.expect_sym("=")?; + let value = self.parse_expr()?; + self.expect_sym(";")?; + Ok(LetDecl { name, name_span, has_parens, ports, value }) + } + fn parse_tf_ports(&mut self) -> PResult> { let mut args = Vec::new(); if !self.cur().is_sym("(") { @@ -3236,6 +3294,18 @@ impl<'a> Parser<'a> { if self.at_concurrent_assertion() { return Ok(StmtKind::Verbatim(self.parse_concurrent_assertion()?)); } + // A statement label (IEEE 1800 §9.3.5): `check_decode: assert (...)`. + // It is read only here, where a statement is expected — a case item's + // `LABEL:` is read by `parse_case_body`, which never reaches this + // function with the label still in front of it. The concurrent + // assertion above claims `label : assert property` first, because + // that whole construct is captured verbatim, label included. + if self.cur().kind == TokenKind::Ident && self.nth(1).is_sym(":") { + let Name { text: name, span: name_span } = self.expect_name()?; + self.expect_sym(":")?; + let stmt = Box::new(self.parse_stmt()?); + return Ok(StmtKind::Labeled { name, name_span, stmt }); + } let t = self.cur(); if t.kind == TokenKind::Directive { return Ok(StmtKind::Directive(self.take_raw_text())); @@ -3409,28 +3479,16 @@ impl<'a> Parser<'a> { "foreach" => { self.bump(); self.expect_sym("(")?; - let target_start = self.here(); - let mut name = self.expect_ident()?; - while self.cur().is_sym(".") { - self.bump(); - name.push('.'); - name.push_str(&self.expect_ident()?); - } - // The target's span stops at the name, before the `[`. - let target = self.expr_at(target_start, ExprKind::Ident(name)); - self.expect_sym("[")?; - let mut vars = Vec::new(); - if !self.cur().is_sym("]") { - vars.push(self.expect_name()?); - while self.eat_sym(",") { - vars.push(self.expect_name()?); - } - } - self.expect_sym("]")?; + let (target, vars) = self.parse_foreach_target()?; self.expect_sym(")")?; let body = Box::new(self.parse_stmt()?); Ok(StmtKind::Foreach { target, vars, body }) } + "randcase" => { + self.bump(); + let (items, dangling) = self.parse_case_body()?; + Ok(StmtKind::RandCase { items, dangling }) + } "return" => { self.bump(); let e = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) }; @@ -3467,6 +3525,13 @@ impl<'a> Parser<'a> { } "wait" => { self.bump(); + // `wait fork;` waits for the enclosing `fork`'s children + // (IEEE 1800 §9.6.1); `fork` is a keyword, not a condition. + if self.cur().is_kw("fork") { + self.bump(); + self.expect_sym(";")?; + return Ok(StmtKind::WaitFork); + } self.expect_sym("(")?; let cond = self.parse_expr()?; self.expect_sym(")")?; @@ -3510,6 +3575,9 @@ impl<'a> Parser<'a> { self.expect_sym(";")?; Ok(StmtKind::ParamDecl(d)) } + // A package import standing among a block's declarations + // (IEEE 1800 §13.4.2): the same statement the item level takes. + "import" => Ok(StmtKind::Import(self.parse_import_list()?)), "input" | "output" | "inout" => { let d = self.parse_port_decl()?; Ok(StmtKind::PortDecl(d)) @@ -3549,13 +3617,18 @@ impl<'a> Parser<'a> { let cond = self.parse_expr()?; self.expect_sym(")")?; let then = Box::new(self.parse_stmt()?); + let mut else_comments = Vec::new(); let els = if self.cur().is_kw("else") { + // Whatever was written in the gap before `else` stays on the + // keyword's left; the then-branch has already taken its own + // trailing comment. + else_comments = self.take_dangling(); self.bump(); Some(Box::new(self.parse_stmt()?)) } else { None }; - Ok(StmtKind::If { qualifier, cond, then, els }) + Ok(StmtKind::If { qualifier, cond, then, else_comments, els }) } fn parse_case_stmt(&mut self, qualifier: Option) -> PResult { @@ -3566,6 +3639,15 @@ impl<'a> Parser<'a> { // `case (x) inside` — the same statement with one extra token, whose // labels may be `[lo:hi]` ranges (handled by `parse_expr_item`). let inside = self.eat_kw("inside"); + let (items, dangling) = self.parse_case_body()?; + Ok(StmtKind::Case { qualifier, kw, expr, inside, items, dangling }) + } + + /// The `label : statement` items of a `case`/`randcase` body, the + /// comments left dangling before `endcase`, and the `endcase` itself. + /// A `randcase` item's label is its weight expression, so the two bodies + /// are the same grammar. + fn parse_case_body(&mut self) -> PResult<(Vec, Vec)> { let mut items = Vec::new(); while !self.at_body_end("endcase") { let start = self.here(); @@ -3588,7 +3670,67 @@ impl<'a> Parser<'a> { } let dangling = self.take_dangling(); self.expect_closer("endcase")?; - Ok(StmtKind::Case { qualifier, kw, expr, inside, items, dangling }) + Ok((items, dangling)) + } + + /// The `arr [ i, j ]` of a `foreach` header, split into the array and the + /// loop variables (IEEE 1800 §12.7.3). + /// + /// The array is a package-scoped or hierarchical name that may carry + /// index and member selects along the way — `riscv_instr_pkg::supported_isa` + /// (`riscv_instr.sv:156`), `program_h[id].sub_program_id` + /// (`riscv_callstack_gen.sv:183`), `paths[0].slices` + /// (`csr_utils_pkg.sv:290`) — so it is parsed as a postfix chain. The + /// bracket group the `)` follows is the one that declares the loop + /// variables; every earlier one is an ordinary select. + fn parse_foreach_target(&mut self) -> PResult<(Expr, Vec)> { + let outer_links = self.links; + let out = self.parse_foreach_target_inner(); + self.links = outer_links; + out + } + + fn parse_foreach_target_inner(&mut self) -> PResult<(Expr, Vec)> { + let start = self.here(); + let name = self.expect_ident()?; + let mut expr = self.expr_at(start, ExprKind::Ident(name)); + loop { + self.link()?; + let t = self.cur(); + if t.is_sym(".") { + self.bump(); + let name = self.expect_ident()?; + expr = self.expr_at(start, ExprKind::Member { base: Box::new(expr), name }); + } else if t.is_sym("::") { + self.bump(); + let name = self.expect_ident()?; + expr = self.expr_at(start, ExprKind::Scope { base: Box::new(expr), name }); + } else if t.is_sym("[") { + let after = self.scan_matching(self.pos, "[", "]"); + if self.tokens.get(after).is_some_and(|t| t.is_sym(")")) { + break; + } + self.bump(); + let index = self.parse_expr()?; + self.expect_sym("]")?; + expr = self.expr_at( + start, + ExprKind::Index { base: Box::new(expr), index: Box::new(index) }, + ); + } else { + break; + } + } + self.expect_sym("[")?; + let mut vars = Vec::new(); + if !self.cur().is_sym("]") { + vars.push(self.expect_name()?); + while self.eat_sym(",") { + vars.push(self.expect_name()?); + } + } + self.expect_sym("]")?; + Ok((expr, vars)) } fn parse_for_step(&mut self) -> PResult { @@ -3958,6 +4100,12 @@ impl<'a> Parser<'a> { || (t.is_sym("'") && self.nth(1).is_sym("(")) || t.is_sym("++") || t.is_sym("--") + // `with ( ... )` (an array method's iterator argument) and + // `with { ... }` (a `randomize` constraint block) are the two + // postfix spellings of `with`; the delimiter tells them apart and + // demanding one keeps the `with [range]` of a stream expression, + // which vfmt does not model, out of this path. + || (t.is_kw("with") && (self.nth(1).is_sym("(") || self.nth(1).is_sym("{"))) } /// Postfix segments are parsed by a loop, but each one wraps the @@ -4027,6 +4175,8 @@ impl<'a> Parser<'a> { let first_expr = if self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident { self.parse_named_arg()? + } else if self.at_omitted_element() { + self.expr_at(arg_start, ExprKind::Empty(Vec::new())) } else { self.parse_expr_or_type()? }; @@ -4036,6 +4186,21 @@ impl<'a> Parser<'a> { } self.expect_sym(")")?; expr = self.expr_at(start, ExprKind::Call { callee: Box::new(expr), args }); + } else if t.is_kw("with") { + if self.nth(1).is_sym("{") { + let block = self.parse_with_constraint()?; + expr = self + .expr_at(start, ExprKind::WithConstraint { base: Box::new(expr), block }); + } else { + self.bump(); // with + // `( expression )` — an ordinary parenthesized primary, + // which is what IEEE 1800 §7.12 spells here. + let arg = self.parse_primary()?; + expr = self.expr_at( + start, + ExprKind::With { base: Box::new(expr), arg: Box::new(arg) }, + ); + } } else if t.is_sym("'") && self.nth(1).is_sym("(") { // Cast: `expr'(x)`. The casting type is a `constant_primary` // (IEEE 1800 §6.24.1): a name, a package-scoped or @@ -6147,4 +6312,186 @@ mod tests { assert_eq!(conns[0].name, "a"); assert!(conns[1].meta.attrs.is_empty()); } + + // ------------------------------------------------------------------ + // DV statements (`docs/features/dv-statements/README.md`) + // ------------------------------------------------------------------ + + /// The statements of the one `initial` block of a single-item module. + fn initial_stmts(f: &SourceFile) -> &Vec { + let ItemKind::Initial(stmt) = &module_of(f).items[0].kind else { + panic!("expected an initial block") + }; + let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") }; + stmts + } + + #[test] + fn a_randomize_with_block_is_captured_verbatim_and_the_call_is_not() { + let f = parse_ok( + "module m;\n initial begin\n x = std::randomize(y) with {\n y > 1;\n };\n end\nendmodule\n", + ); + let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else { + panic!("expected an assignment") + }; + let ExprKind::WithConstraint { base, block } = &rhs.kind else { + panic!("expected a with-constraint, got {:?}", rhs.kind) + }; + // The `with` keyword is outside the capture; the braces are inside. + assert_eq!(block.text, "{\n y > 1;\n }"); + assert!(matches!(base.kind, ExprKind::Call { .. }), "the call is still structural"); + } + + #[test] + fn an_array_method_with_argument_is_an_ordinary_expression() { + let f = parse_ok( + "module m;\n initial begin\n n = q.sum() with (item.w);\n end\nendmodule\n", + ); + let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else { + panic!("expected an assignment") + }; + let ExprKind::With { base, arg } = &rhs.kind else { + panic!("expected a with-expression, got {:?}", rhs.kind) + }; + assert!(matches!(base.kind, ExprKind::Call { .. })); + assert!(matches!(arg.kind, ExprKind::Paren { .. })); + } + + #[test] + fn a_with_that_opens_neither_a_paren_nor_a_brace_is_not_a_postfix_segment() { + // The stream expression's `with [range]` is still unsupported, and + // still fails where it always did rather than being mis-read. + assert!( + parse_err("module m;\n initial x = {<<{a with [0:1]}};\nendmodule\n").contains("with") + ); + } + + #[test] + fn a_foreach_splits_the_array_from_its_loop_variables() { + let f = parse_ok( + "module m;\n initial begin\n foreach (pkg::a[i].b[j]) x = 1;\n end\nendmodule\n", + ); + let StmtKind::Foreach { target, vars, .. } = &initial_stmts(&f)[0].kind else { + panic!("expected a foreach") + }; + // Everything before the last bracket group is the array. + assert!(matches!(target.kind, ExprKind::Member { .. })); + assert_eq!(vars.len(), 1); + assert_eq!(vars[0].text, "j"); + } + + #[test] + fn a_foreach_over_a_selected_array_keeps_the_select_on_the_array() { + let f = parse_ok( + "module m;\n initial begin\n foreach (a[i][j]) x = 1;\n end\nendmodule\n", + ); + let StmtKind::Foreach { target, vars, .. } = &initial_stmts(&f)[0].kind else { + panic!("expected a foreach") + }; + assert!(matches!(target.kind, ExprKind::Index { .. })); + assert_eq!(vars[0].text, "j"); + } + + #[test] + fn a_randcase_takes_case_items_without_a_selector() { + let f = parse_ok( + "module m;\n initial begin\n randcase\n 1: x = 0;\n 5: x = 1;\n endcase\n end\nendmodule\n", + ); + let StmtKind::RandCase { items, .. } = &initial_stmts(&f)[0].kind else { + panic!("expected a randcase") + }; + assert_eq!(items.len(), 2); + assert_eq!(items.iter().filter(|i| i.labels.is_empty()).count(), 0); + } + + #[test] + fn wait_fork_is_a_statement_of_its_own_and_wait_expr_still_is_not() { + let f = parse_ok( + "module m;\n initial begin\n wait fork;\n wait (done);\n end\nendmodule\n", + ); + let stmts = initial_stmts(&f); + assert!(matches!(stmts[0].kind, StmtKind::WaitFork)); + assert!(matches!(stmts[1].kind, StmtKind::Wait { .. })); + } + + #[test] + fn an_import_stands_among_a_blocks_declarations() { + let f = parse_ok( + "module m;\n initial begin\n import p::*;\n x = 1;\n end\nendmodule\n", + ); + let StmtKind::Import(paths) = &initial_stmts(&f)[0].kind else { + panic!("expected an import statement") + }; + assert_eq!(paths[0].pkg.text, "p"); + assert_eq!(paths[0].item.text, "*"); + } + + #[test] + fn a_let_declaration_keeps_its_ports_and_its_value() { + let f = parse_ok("module m;\n let max(a, b) = (a > b) ? a : b;\nendmodule\n"); + let ItemKind::Let(l) = &module_of(&f).items[0].kind else { panic!("expected a let") }; + assert_eq!(l.name, "max"); + assert!(l.has_parens); + assert_eq!(l.ports.len(), 2); + assert_eq!(l.ports[1].name, "b"); + assert!(matches!(l.value.kind, ExprKind::Ternary { .. })); + } + + #[test] + fn an_omitted_call_argument_is_an_empty_element_that_still_holds_its_place() { + let f = parse_ok("module m;\n initial x = f(a, , b);\nendmodule\n"); + let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else { + panic!("expected an initial block") + }; + let StmtKind::Assign { rhs, .. } = &stmt.kind else { panic!("expected an assignment") }; + let ExprKind::Call { args, .. } = &rhs.kind else { panic!("expected a call") }; + assert_eq!(args.len(), 3); + assert!(matches!(args[1].expr.kind, ExprKind::Empty(_))); + } + + #[test] + fn a_statement_label_wraps_the_statement_it_names() { + let f = parse_ok( + "module m;\n initial begin\n chk: assert (a) x++; else y++;\n end\nendmodule\n", + ); + let StmtKind::Labeled { name, stmt, .. } = &initial_stmts(&f)[0].kind else { + panic!("expected a labeled statement") + }; + assert_eq!(name, "chk"); + assert!(matches!(stmt.kind, StmtKind::Assert { .. })); + } + + #[test] + fn a_label_before_a_concurrent_assertion_still_takes_the_verbatim_path() { + // The concurrent-assertion check runs first and swallows the label. + let f = parse_ok( + "module m;\n initial begin\n NoNMI: assert property (@(posedge c) a);\n end\nendmodule\n", + ); + assert!(matches!(initial_stmts(&f)[0].kind, StmtKind::Verbatim(_))); + } + + #[test] + fn a_stray_semicolon_after_a_footer_label_is_recorded_not_dropped() { + let f = parse_ok("class c;\n task t();\n endtask : t;\n function void g();\n endfunction\nendclass\n"); + let ItemKind::Class(class) = &f.items[0].kind else { panic!("expected a class") }; + let ItemKind::Task(t) = &class.items[0].kind else { panic!("expected a task") }; + assert!(t.end_semi); + let ItemKind::Function(g) = &class.items[1].kind else { panic!("expected a function") }; + assert!(!g.end_semi); + } + + #[test] + fn a_comment_before_else_is_kept_on_the_keywords_left() { + let f = parse_ok( + "module m;\n initial\n if (a) x = 1;\n // why\n else x = 2;\nendmodule\n", + ); + let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else { + panic!("expected an initial block") + }; + let StmtKind::If { else_comments, els, .. } = &stmt.kind else { panic!("expected an if") }; + assert_eq!(else_comments.len(), 1); + assert_eq!(else_comments[0].text, "// why"); + // The else-branch itself did not also take the comment. + assert!(els.as_ref().expect("an else").meta.leading.is_empty()); + } } diff --git a/crates/vlog_parser/src/token.rs b/crates/vlog_parser/src/token.rs index efa709f..68bc262 100644 --- a/crates/vlog_parser/src/token.rs +++ b/crates/vlog_parser/src/token.rs @@ -169,6 +169,12 @@ pub fn is_keyword(s: &str) -> bool { | "case" | "casex" | "casez" + // `randcase` is reserved (IEEE 1800 Table B.1) and opens a + // statement of its own; `let` is reserved too and opens an item. + // Both are here rather than matched by text so a declaration can + // never accidentally be named after one. + | "randcase" + | "let" | "endcase" | "default" | "unique" diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index d3847ba..8265e27 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -75,6 +75,11 @@ const SOURCES: &[&str] = &[ // named call arguments, `case ... inside`, a bare event control. "class c;\n string q[$] = {};\n rand int offset[];\n logic hits[*];\n string lut[string];\n item_t #(A, B) rq[NumInp-1:0][$:8];\n function void f(string ops[$], output int outs[]);\n q[$].label = ops[$-1];\n offset = new[n];\n endfunction\nendclass\n", "module m;\n typedef bit [3:0] q_t[$];\n task t;\n csr_wr(.ptr(ral.ovrd), .value({a, b}), .flag());\n @hier.tick;\n case (x) inside\n [A:B], C: y = 1;\n default: y = 0;\n endcase\n endtask\nendmodule\n", + // DV statements: `with` clauses, scoped/hierarchical `foreach`, + // `randcase`, `wait fork`, a block-level `import`, a `let`, an omitted + // call argument and a statement label. + "module m;\n let max(a, b) = (a > b) ? a : b;\n initial begin\n import p::*;\n wait fork;\n foreach (pkg::isa[i]) x = 1;\n foreach (h[id].sub[k, j]) x = 2;\n chk: assert (a) x++; else y++;\n n = q.sum() with (item.w);\n y = f(a, , b);\n randcase\n 1: x = 0;\n 5: begin\n x = 1;\n end\n endcase\n end\nendmodule\n", + "class c;\n task t();\n if (!req.randomize() with {\n a == 1;\n b dist { 0 :/ 1 };\n }) $fatal(1, \"no\");\n endtask : t;\nendclass\n", // DPI imports and exports, plus package re-exports. "package p;\n import \"DPI-C\"\n function void env_final();\n import \"DPI-C\" context function chandle mk(int unsigned k, bit [7:0] v);\n import \"DPI-C\" function chandle get;\n import \"DPI-C\" pure c_name = task tick(input int n);\n export \"DPI-C\" function f;\n export \"DPI-C\" ex_name = task t;\n export q::*;\n export r::a, s::b;\n export *::*;\nendpackage\n", ]; @@ -616,6 +621,14 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { check_stmt(src, s, here); } } + ItemKind::Let(l) => { + check_name(src, "let name", &l.name, l.name_span, here); + for a in &l.ports { + assert_inside(src, "let port", a.span, here); + check_name(src, "let port name", &a.name, a.name_span, a.span); + } + check_expr(src, &l.value, here); + } ItemKind::Defparam(pairs) => { for (lhs, rhs) in pairs { check_expr(src, lhs, here); @@ -793,8 +806,23 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) { check_stmt(src, s, here); } } + StmtKind::RandCase { items, .. } => { + for item in items { + assert_inside(src, "case item", item.span, here); + for l in &item.labels { + check_expr(src, &l.expr, here); + } + check_stmt(src, &item.stmt, here); + } + } + StmtKind::Labeled { name, name_span, stmt: inner } => { + check_name(src, "statement label", name, *name_span, here); + check_stmt(src, inner, here); + } + StmtKind::Import(paths) => check_import_paths(src, paths, here), StmtKind::Break | StmtKind::Continue + | StmtKind::WaitFork | StmtKind::Disable(_) | StmtKind::Null | StmtKind::Error(_) => {} @@ -819,6 +847,14 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) { check_expr(src, expr, here); } ExprKind::InsideMacro { lhs, .. } => check_expr(src, lhs, here), + ExprKind::With { base, arg } => { + check_expr(src, base, here); + check_expr(src, arg, here); + } + ExprKind::WithConstraint { base, block } => { + check_expr(src, base, here); + assert_inside(src, "with constraint block", block.span, here); + } ExprKind::NamedArg { name, name_span, value, .. } => { check_name(src, "named argument", name, *name_span, here); check_expr(src, value, here); diff --git a/crates/vlog_semantic/src/bind.rs b/crates/vlog_semantic/src/bind.rs index 9de7005..aac5549 100644 --- a/crates/vlog_semantic/src/bind.rs +++ b/crates/vlog_semantic/src/bind.rs @@ -222,6 +222,20 @@ impl<'a> Binder<'a> { self.bind_import_path(path, scope); } } + // A `let` is a compile-time function: its ports are visible only + // inside its own body expression. + ItemKind::Let(l) => { + let inner = self.declare_with_scope( + scope, + &l.name, + SymbolKind::Function, + l.name_span, + item.span, + ScopeKind::Function, + ); + self.bind_tf_args(&l.ports, inner); + self.bind_expr(&l.value, inner); + } ItemKind::Typedef(t) => self.bind_typedef(t, item.span, scope), ItemKind::ParamDecl(p) => { self.bind_declarators(&p.declarators, SymbolKind::Param, &p.ty, item.span, scope) @@ -850,11 +864,18 @@ impl<'a> Binder<'a> { } StmtKind::Case { expr, items, .. } => { self.bind_expr(expr, scope); - for it in items { - for l in &it.labels { - self.bind_expr(&l.expr, scope); - } - self.bind_stmt(&it.stmt, scope); + self.bind_case_items(items, scope); + } + StmtKind::RandCase { items, .. } => self.bind_case_items(items, scope), + // A statement label names the statement the way a block name + // names its block (IEEE 1800 §9.3.5). + StmtKind::Labeled { name, name_span, stmt: inner } => { + self.declare(scope, name, SymbolKind::Block, *name_span, stmt.span); + self.bind_stmt(inner, scope); + } + StmtKind::Import(paths) => { + for path in paths { + self.bind_import_path(path, scope); } } StmtKind::For { init, cond, step, body } => { @@ -957,6 +978,7 @@ impl<'a> Binder<'a> { } StmtKind::Break | StmtKind::Continue + | StmtKind::WaitFork | StmtKind::Directive(_) | StmtKind::MacroStmt(_) | StmtKind::Null @@ -967,6 +989,16 @@ impl<'a> Binder<'a> { } } + /// The labels and bodies of a `case`/`randcase` body. + fn bind_case_items(&mut self, items: &'a [CaseItem], scope: ScopeId) { + for it in items { + for l in &it.labels { + self.bind_expr(&l.expr, scope); + } + self.bind_stmt(&it.stmt, scope); + } + } + fn bind_timing(&mut self, t: &'a TimingControl, scope: ScopeId) { match t { TimingControl::Delay(e) => self.bind_expr(e, scope), @@ -1079,6 +1111,13 @@ impl<'a> Binder<'a> { } // The set is a macro invocation this crate makes no claims about. ExprKind::InsideMacro { lhs, .. } => self.bind_expr(lhs, scope), + ExprKind::With { base, arg } => { + self.bind_expr(base, scope); + self.bind_expr(arg, scope); + } + // The constraint block is verbatim source: opaque to name + // resolution, exactly as `StmtKind::Verbatim` is. + ExprKind::WithConstraint { base, .. } => self.bind_expr(base, scope), ExprKind::Paren { inner, .. } => self.bind_expr(inner, scope), // Only the cast's operand is bound. The casting type names a // type — a keyword (`int'(x)`), a typedef or a parameter — and diff --git a/docs/features/dv-statements/README.md b/docs/features/dv-statements/README.md new file mode 100644 index 0000000..68018a1 --- /dev/null +++ b/docs/features/dv-statements/README.md @@ -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)` 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`** — 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 ` 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