diff --git a/TODO.md b/TODO.md index 7e457b5..9a26f2f 100644 --- a/TODO.md +++ b/TODO.md @@ -1356,6 +1356,23 @@ README.md, TODO.md §11 Lane B lines) Also delivered there: the `Parser::take_before_open` handshake Lane B filed (`docs/features/formatter-bug-fixes/README.md`), which unblocks the 12th bucket-2 file, `keymgr_scoreboard.sv`. -- [ ] Mop-up bundle (~26 files): enum member ranges, cast-base drive +- [x] Mop-up bundle (~26 files): enum member ranges, cast-base drive strengths, local typedef statement, gate delays, virtual+modport, rand-on-struct, foreach-skip-dim, hierarchical bind instance list. + Done: nine shapes, **47** files (the estimate was low, and two of + `syntax_coverage.md`'s bucket labels were mis-diagnoses — bucket 6 is + a *system function call* as the casting type, `$bits(x)'(y)`, not a + drive strength; bucket 12 has six files, not five). Real grammar + throughout, no verbatim capture, `verify.rs` untouched. One new + `StmtKind` variant (the block-scoped `typedef`, which is the item form + exactly) and four new fields; seven of the nine buckets needed no AST + surface at all. OpenTitan 88 → 43 failures: 45 files clean, 2 advance + to the `iff`-in-event-control gap, **zero** newly failing, and zero + output change on any of the 3,896 previously-passing files. Corpus + gate byte-identical at 813/820. Tolerant diagnostics over the failing + set 1 644 → 1 290, none worse anywhere. + `docs/features/testbench-mopup/README.md`. +- [ ] Skipped there, one file: a gate's drive strength + (`pullup (weak1) u (...)`, spi_host/dv/tb.sv:101) — a different + production from the cast bases bucket 6 named, costing two AST changes + for one file. See that README's Status for the exact shape. diff --git a/crates/lucisv_server/src/type_def.rs b/crates/lucisv_server/src/type_def.rs index cd3a9ee..cb073b3 100644 --- a/crates/lucisv_server/src/type_def.rs +++ b/crates/lucisv_server/src/type_def.rs @@ -282,6 +282,11 @@ fn stmt_site(stmt: &Stmt, offset: u32) -> Option> { return None; } match &stmt.kind { + // A block-scoped typedef answers exactly as the item form does: the + // cursor on the alias name jumps one hop to the aliased type. Added + // when `StmtKind::Typedef` landed (testbench-mopup, 2026-08-29) — + // QA's blast-radius audit caught this arm missing. + StmtKind::Typedef(t) => alias_site(t, stmt.span), StmtKind::VarDecl(d) => declarator_site(&d.ty, stmt.span, &d.declarators), StmtKind::ParamDecl(p) => declarator_site(&p.ty, stmt.span, &p.declarators), StmtKind::PortDecl(p) => declarator_site(&p.ty, stmt.span, &p.declarators), @@ -364,6 +369,27 @@ mod tests { // in-file types // ------------------------------------------------------------------ + #[test] + fn a_block_scoped_typedefs_alias_jumps_one_hop_to_its_type() { + // QA (testbench-mopup, 2026-08-29): the item-level alias hop worked, + // the new statement-level typedef silently answered nothing. Both + // forms now answer through the same alias_site. + let text = "\ +module m; + typedef logic [7:0] byte_t; + initial begin + typedef byte_t word_t; + word_t w; + end +endmodule +"; + let (ws, uri) = document(text); + assert!( + !jumps(&ws, &uri, at(text, "word_t;") + 3).is_empty(), + "the block-scoped alias hops to byte_t instead of answering nothing" + ); + } + #[test] fn a_variable_jumps_to_the_typedef_of_its_type() { let text = "\ diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs index fee3b83..a615d5d 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -1605,6 +1605,9 @@ impl<'a> Fmt<'a> { .iter() .map(|m| { let mut d = vec![text(m.name.clone())]; + // Tight against the name: `OtbnDmem[16]` is one enum name + // range, not a name with a dimension beside it. + d.extend(m.range.iter().map(|r| self.dim(r))); if let Some(v) = &m.value { d.push(text(" = ")); d.push(self.expr(v)); @@ -1640,6 +1643,9 @@ impl<'a> Fmt<'a> { inner.push(Doc::HardLine); inner.extend(self.leading(&m.meta)); let mut d = Vec::new(); + for q in &m.qualifiers { + d.push(text(format!("{q} "))); + } if let Some(ty) = self.data_type(&m.ty) { d.push(ty); d.push(text(" ")); @@ -1944,9 +1950,20 @@ impl<'a> Fmt<'a> { fn gate_instantiation(&self, g: &GateInstantiation) -> Doc { let mut docs = vec![text(g.gate.clone())]; - if let Some(delay) = &g.delay { + if let [delay] = g.delay.as_slice() { + // One value prints itself, brackets and all (`#5`, `#(5)`). docs.push(text(" #")); docs.push(self.expr(delay)); + } else if !g.delay.is_empty() { + // `#(rise, fall[, turn-off])` — the parens are the list's own. + docs.push(text(" #(")); + for (i, d) in g.delay.iter().enumerate() { + if i > 0 { + docs.push(text(", ")); + } + docs.push(self.expr(d)); + } + docs.push(text(")")); } for (i, inst) in g.instances.iter().enumerate() { docs.push(if i > 0 { text(", ") } else { text(" ") }); @@ -2682,6 +2699,8 @@ impl<'a> Fmt<'a> { StmtKind::ExprStmt(e) => concat(vec![self.expr(e), text(";")]), StmtKind::EventTrigger(e) => concat(vec![text("-> "), self.expr(e), text(";")]), StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), text(";")]), + // The item form prints its own `;`. + StmtKind::Typedef(t) => self.typedef(t), StmtKind::ParamDecl(d) => concat(vec![self.param_decl(d, None), text(";")]), StmtKind::PortDecl(d) => concat(vec![self.port_decl(d), text(";")]), StmtKind::Return(e) => match e { @@ -2976,7 +2995,12 @@ impl<'a> Fmt<'a> { let after: Vec<&Comment> = after.iter().collect(); self.paren_comments(inner, &before, &after) } - ExprKind::Cast { ty, expr } => { + // `ty'{...}` prints no brackets of its own: the assignment + // pattern already carries the `'{` and the `}`. + ExprKind::Cast { ty, expr, pattern: true } => { + concat(vec![self.expr(ty), self.expr(expr)]) + } + ExprKind::Cast { ty, expr, .. } => { concat(vec![self.expr(ty), text("'("), self.expr(expr), text(")")]) } ExprKind::AssignPattern(items) => { diff --git a/crates/vlog_formatter/tests/cases/mopup_round.cases b/crates/vlog_formatter/tests/cases/mopup_round.cases new file mode 100644 index 0000000..6650a81 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/mopup_round.cases @@ -0,0 +1,230 @@ +# The mop-up round: the small parser buckets of syntax_coverage.md, bundled. +# See docs/features/testbench-mopup/README.md. Every case here is a shape the +# OpenTitan sweep contains; none of them needed a layout decision, because in +# every one the new surface is data the source already laid out (a bracket, a +# qualifier word, a modport suffix) rather than a construct to break. + +# --- bucket 4: a block-scoped `typedef` statement (IEEE 1800 §6.18) --- +# The statement form is the item form, indented to the block. Same node, same +# printer, so `typedef enum` still fits on one line if it fits. +class c; + task access_data_fifo(ref bit [7:0] data_q[$]); + typedef enum bit {WRITE = 1'b1, READ = 1'b0} rdwr_e; + rdwr_e rw = WRITE; + endtask +endclass +---- +class c; + task access_data_fifo(ref bit [7:0] data_q [$]); + typedef enum bit {WRITE = 1'b1, READ = 1'b0} rdwr_e; + rdwr_e rw = WRITE; + endtask +endclass +==== +# every typedef spelling reaches statement position, comments included +module m; + initial begin + // a block-scoped alias, a dynamic-array alias and a struct + typedef logic [2*$bits(mubi4_t) - 1:0] extclk_ctrl_t; + typedef bit data_result[]; + typedef struct { + trans_e unit; + uvm_reg_field hint_bit; + } hint_t; + typedef class fwd; + data_result data_array; + end +endmodule +---- +module m; + initial begin + // a block-scoped alias, a dynamic-array alias and a struct + typedef logic [2*$bits(mubi4_t)-1:0] extclk_ctrl_t; + typedef bit data_result []; + typedef struct { + trans_e unit; + uvm_reg_field hint_bit; + } hint_t; + typedef class fwd; + data_result data_array; + end +endmodule +==== +# --- bucket 6: a system function call as the casting type --- +# `$bits(x)'(y)` / `$clog2(N)'(y)` — a `constant_primary` per IEEE 1800 +# §6.24.1, and the only call shape admitted left of a cast's `'`. +module m; + assign periph_data_mux = $bits(periph_data_mux)'({periph_to_mio_i, 1'b0}); + assign a = $clog2(RomSize)'(RomSize); + assign b = data_q[$clog2(dm::DataCount)'(autoexecdata_idx)]; +endmodule +---- +module m; + assign periph_data_mux = $bits(periph_data_mux)'({periph_to_mio_i, 1'b0}); + assign a = $clog2(RomSize)'(RomSize); + assign b = data_q[$clog2(dm::DataCount)'(autoexecdata_idx)]; +endmodule +==== +# --- bucket 8: enum member ranges (IEEE 1800 §6.19) --- +# The bracket prints tight against the name: it is part of the name, not a +# dimension standing beside it, and there is no layout decision in it. +package p; + typedef enum logic [ResetWidths-1:0] { + ReqPeriResetIdx[0:1], + ReqMainPwrResetIdx, + ReqEscResetIdx + } reset_idx_e; + + typedef enum { + OtbnDmem[16], + OtbnImem, + RamMain[16] = 5, + Otp + } mem_e; +endpackage +---- +package p; + typedef enum logic [ResetWidths-1:0] { + ReqPeriResetIdx[0:1], + ReqMainPwrResetIdx, + ReqEscResetIdx + } reset_idx_e; + + typedef enum {OtbnDmem[16], OtbnImem, RamMain[16] = 5, Otp} mem_e; +endpackage +==== +# --- bucket 10: a cast applied to an assignment pattern, `ty'{...}` --- +# The pattern brings its own `'{` and `}`, so the cast prints no brackets of +# its own. The last line is the reason the two spellings stay distinguishable +# in the tree: `ty'('{...})` is a different token stream and must survive as +# itself. +class c; + function void f(); + exp_alert_q[alert_name].push_back(expected_alert_t'{1, is_fatal, max_delay}); + q.push_back(mem_item_t'{addr: a, data: d}); + x = pkg::cfg_t'{default: 0}; + endfunction +endclass + +module m; + assign tag = {ibex_pkg::IC_NUM_WAYS{prim_ram_1p_pkg::ram_1p_cfg_req_t'{req: spram_rm.cfg}}}; + assign y = bar_t'('{a: 1}); +endmodule +---- +class c; + function void f(); + exp_alert_q[alert_name].push_back(expected_alert_t'{1, is_fatal, max_delay}); + q.push_back(mem_item_t'{addr: a, data: d}); + x = pkg::cfg_t'{default: 0}; + endfunction +endclass + +module m; + assign tag = {ibex_pkg::IC_NUM_WAYS{prim_ram_1p_pkg::ram_1p_cfg_req_t'{req: spram_rm.cfg}}}; + assign y = bar_t'('{a: 1}); +endmodule +==== +# --- bucket 11: a gate's `#(rise, fall[, turn-off])` delay list (§28.14) --- +# The one-value spellings keep the node they always had, so `#(5)` and `#5` +# still print exactly as written; only a real comma list prints its own parens. +module m; + buf #(ast_bhv_pkg::AON_EN_RDLY, 0) b0 (en_osc_re_buf, (vcore_pok_h_i && aon_en_i)); + and #(1, 2, 3) g1 (o, a, b); + not #(1:2:3, 4:5:6) n0 (o, a); + buf #(5) b1 (o, a); + buf #5 b2 (o, a); + buf b3 (o, a); +endmodule +---- +module m; + buf #(ast_bhv_pkg::AON_EN_RDLY, 0) b0 (en_osc_re_buf, (vcore_pok_h_i && aon_en_i)); + and #(1, 2, 3) g1 (o, a, b); + not #(1:2:3, 4:5:6) n0 (o, a); + buf #(5) b1 (o, a); + buf #5 b2 (o, a); + buf b3 (o, a); +endmodule +==== +# --- bucket 12: `virtual iface.modport name;` (IEEE 1800 §25.9) --- +# The modport is glued onto the interface name, exactly as an interface +# *port*'s already is, so the type prints as the one string it is. +module tb; + virtual spi_if.tb tb_sif = sif.tb; + virtual spi_if.dut dut_sif; + virtual interface bus_if plain_vif; + + task automatic spi_transaction(virtual spi_if.tb sif, ref spi_fifo_t d_in[$]); + endtask +endmodule +---- +module tb; + virtual spi_if.tb tb_sif = sif.tb; + virtual spi_if.dut dut_sif; + virtual interface bus_if plain_vif; + + task automatic spi_transaction(virtual spi_if.tb sif, ref spi_fifo_t d_in [$]); + endtask +endmodule +==== +# --- bucket 14: `rand`/`randc` on a plain struct member --- +# Not LRM-legal, but vendor-accepted and real. Carried and printed; lucisv +# models no randomization semantics either way. +package p; + typedef struct { + rand bit cpol; + randc bit [3:0] csnlead; + rand mubi4_t en; // enable this region + bit plain; + } cfg_t; +endpackage +---- +package p; + typedef struct { + rand bit cpol; + randc bit [3:0] csnlead; + rand mubi4_t en; // enable this region + bit plain; + } cfg_t; +endpackage +==== +# --- bucket 15: a `foreach` with a skipped dimension (IEEE 1800 §12.7.3) --- +# A skipped slot is an empty name written where the source wrote nothing: it +# declares no loop variable, and it prints as nothing. +module m; + initial begin + foreach (cfg.mem_bkdr_util_h[, bank]) x = 1; + foreach (h[i, , k]) y = 2; + foreach (q[i, j]) w = 4; + end +endmodule +---- +module m; + initial begin + foreach (cfg.mem_bkdr_util_h[, bank]) x = 1; + foreach (h[i, , k]) y = 2; + foreach (q[i, j]) w = 4; + end +endmodule +==== +# --- bucket 16: a hierarchical path in a `bind`'s instance list --- +# The dots are glued into the one name the list already carries, the way +# `bind`'s own target path is. +module tb; + bind prim_packer_fifo : dut.u_entropy_src_core.u_prim_packer_fifo_precon + entropy_subsys_fifo_exception_if #( + .IsPackerFifo(1) + ) u_fifo_exc_if ( + .clk_i, + .rst_ni + ); + + bind foo : a.b, plain_inst bar u (.x); +endmodule +---- +module tb; + bind prim_packer_fifo : dut.u_entropy_src_core.u_prim_packer_fifo_precon entropy_subsys_fifo_exception_if #( + .IsPackerFifo(1) + ) u_fifo_exc_if (.clk_i, .rst_ni); + + bind foo : a.b, plain_inst bar u (.x); +endmodule diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index 2f5c533..bb0d751 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -532,6 +532,12 @@ pub struct EnumMember { pub name: String, /// Byte range of `name`. pub name_span: TextRange, + /// The enum name range of IEEE 1800 §6.19 — `Name[N]` or `Name[hi:lo]`, + /// which declares a run of sequentially-valued members. One dimension is + /// all the LRM allows; it is kept as an ordinary [`Dim`] so the existing + /// dimension parser and printer serve it, and it is printed back tight + /// against the name because it is part of the name, not a layout choice. + pub range: Vec, pub value: Option, /// True when a `,` followed this element in the source; see /// [`NonAnsiPort::comma`]. @@ -553,6 +559,12 @@ pub struct StructType { #[derive(Debug, Clone)] pub struct StructMember { pub meta: Meta, + /// `rand` / `randc` written before the member's type. The LRM allows the + /// randomization qualifiers only on a class property, but vendor tools + /// accept them on a plain struct member and real code uses them + /// (`spi_host/dv/env/spi_host_env_pkg.sv:64`); lucisv models no + /// randomization semantics, so the words are simply carried and printed. + pub qualifiers: Vec, pub ty: DataType, pub declarators: Vec, /// Code extent of the member, its `;` included. @@ -789,7 +801,11 @@ pub struct BindDirective { pub struct GateInstantiation { /// `and`, `or`, `not`, ... pub gate: String, - pub delay: Option, + /// The delay written after `#`: empty when there is none, one element for + /// every spelling a net or a continuous assignment also accepts, and two + /// or three for the `(rise, fall[, turn-off])` list that only a gate + /// takes (IEEE 1800 §28.14, `top_earlgrey/ip/ast/rtl/aon_osc.sv:41`). + pub delay: Vec, pub instances: Vec, } @@ -1193,6 +1209,11 @@ pub enum StmtKind { /// declarations (IEEE 1800 §13.4.2) — the statement twin of /// [`ItemKind::Import`]. Import(Vec), + /// `typedef enum bit {WRITE, READ} rdwr_e;` written inside a + /// function/task body or a `begin` block, scoping the type to that block + /// (IEEE 1800 §6.18) — the statement twin of [`ItemKind::Typedef`], with + /// the same payload and the same layout. + Typedef(Typedef), /// `name : stmt` — a statement label (IEEE 1800 §9.3.5). /// /// `begin`/`fork` keep their label inside their own node, because the @@ -1414,11 +1435,18 @@ pub enum ExprKind { }, /// `ty'(expr)` cast. The casting type is an expression because it may be /// a name (`int`, `my_t`), a package-scoped name - /// (`lc_ctrl_pkg::TxWidth'(x)`), a size (`4'(x)`) or a parenthesized - /// constant expression (`(DepthW + 3)'(1'b1)`) — IEEE 1800 §6.24.1. + /// (`lc_ctrl_pkg::TxWidth'(x)`), a size (`4'(x)`), a parenthesized + /// constant expression (`(DepthW + 3)'(1'b1)`) or a system function call + /// (`$bits(x)'(y)`) — IEEE 1800 §6.24.1. Cast { ty: Box, expr: Box, + /// True for the `ty'{...}` spelling (IEEE 1800 §10.9.1), where the + /// argument is an assignment pattern. The pattern brings its own + /// `'{` and `}`, so such a cast prints no brackets of its own — + /// which is also why the two spellings must stay distinguishable: + /// `ty'('{a: 1})` is a different token stream from `ty'{a: 1}`. + pattern: bool, }, /// `'{...}` assignment pattern. AssignPattern(Vec), diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index 6c982c5..d748579 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -2941,6 +2941,14 @@ impl<'a> Parser<'a> { self.bump(); ty.virt = Some(if self.eat_kw("interface") { VirtualKw::Interface } else { VirtualKw::Bare }); + // `virtual spi_if.tb sif` — a modport-qualified virtual interface + // type (IEEE 1800 §25.9, `spi_device/pre_dv/tb/spid_common.sv:563`). + // Glued onto the interface name exactly as an interface *port*'s + // modport is, so every consumer still sees one type-name string. + if self.at_modport_port() { + ty.name = self.parse_modport_port_type()?.name; + return Ok(ty); + } } let t = self.cur(); // An anonymous aggregate stands where a type name does (IEEE 1800 @@ -3094,7 +3102,16 @@ impl<'a> Parser<'a> { } else { None }; - let ty = self.parse_opt_data_type()?; + // A declaration reaches here with its `virtual` already in + // `qualifiers`, so `parse_opt_data_type`'s own modport branch cannot + // fire: `virtual spi_if.tb tb_sif = sif.tb;` + // (`spi_device/pre_dv/tb/spid_jedec_tb.sv:32`) is recognized here + // instead, the way `parse_ansi_port` recognizes an interface port's. + let ty = if qualifiers.iter().any(|q| q == "virtual") && self.at_modport_port() { + self.parse_modport_port_type()? + } else { + self.parse_opt_data_type()? + }; let declarators = self.parse_declarators()?; self.expect_sym(";")?; Ok(DataDecl { net, delay, qualifiers, ty, declarators }) @@ -3168,13 +3185,15 @@ impl<'a> Parser<'a> { let start = self.here(); let mut meta = self.take_meta(); let Name { text: name, span: name_span } = self.expect_name()?; - // Enum member ranges (`VAL[4]`) are rare; unsupported. + // `ReqPeriResetIdx[0:1]`, `OtbnDmem[16]` — the enum name range of + // IEEE 1800 §6.19 (`rstmgr_pkg.sv:72`, `chip_env_pkg.sv:88`). + let range = self.parse_dims()?; let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; let span = self.span_from(start); self.take_before_sep(&mut meta, ","); let comma = self.eat_sym(","); meta.trailing = self.take_trailing(); - members.push(EnumMember { meta, name, name_span, value, comma, span }); + members.push(EnumMember { meta, name, name_span, range, value, comma, span }); let dirs = self.take_list_directives(&mut directives, members.len()); if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym("}")) { break; @@ -3202,12 +3221,16 @@ impl<'a> Parser<'a> { while !self.cur().is_sym("}") && !self.at_eof() { let start = self.here(); let mut meta = self.take_meta(); + let mut qualifiers = Vec::new(); + while self.cur().is_kw("rand") || self.cur().is_kw("randc") { + qualifiers.push(self.bump().text); + } let ty = self.parse_opt_data_type()?; let declarators = self.parse_declarators()?; self.expect_sym(";")?; let span = self.span_from(start); meta.trailing = self.take_trailing(); - members.push(StructMember { meta, ty, declarators, span }); + members.push(StructMember { meta, qualifiers, ty, declarators, span }); } let dangling = self.take_dangling(); self.expect_sym("}")?; @@ -3303,13 +3326,25 @@ impl<'a> Parser<'a> { Ok(Some(DriveStrength { first, second })) } - fn parse_delay_value(&mut self) -> PResult { - if self.cur().is_sym("(") { - let start = self.here(); - self.bump(); + /// The value after a `#`: a bare primary, or a parenthesized delay — + /// one value, `min:typ:max`, or the `(rise, fall[, turn-off])` list of + /// IEEE 1800 §28.14. + /// + /// A single value keeps the [`ExprKind::Paren`] node the one-value + /// spelling has always produced, so `#(5)` and `#(1:2:3)` still print + /// exactly as written; only a real comma list yields more than one + /// element. + fn parse_delay_values(&mut self) -> PResult> { + if !self.cur().is_sym("(") { + return Ok(vec![self.parse_primary()?]); + } + let start = self.here(); + self.bump(); // ( + let mut out = Vec::new(); + loop { let inner_start = self.here(); let first = self.parse_expr()?; - let expr = if self.eat_sym(":") { + out.push(if self.eat_sym(":") { let typ = self.parse_expr()?; self.expect_sym(":")?; let max = self.parse_expr()?; @@ -3323,15 +3358,31 @@ impl<'a> Parser<'a> { ) } else { first - }; - self.expect_sym(")")?; - Ok(self.expr_at( - start, - ExprKind::Paren { inner: Box::new(expr), before: Vec::new(), after: Vec::new() }, - )) - } else { - self.parse_primary() + }); + if !self.eat_sym(",") { + break; + } } + self.expect_sym(")")?; + if out.len() == 1 { + let inner = out.remove(0); + return Ok(vec![self.expr_at( + start, + ExprKind::Paren { inner: Box::new(inner), before: Vec::new(), after: Vec::new() }, + )]); + } + Ok(out) + } + + /// The single delay value a net declaration or a continuous assignment + /// takes. The multi-value list is a gate-instantiation spelling only — + /// see [`Parser::parse_delay_values`]. + fn parse_delay_value(&mut self) -> PResult { + let mut values = self.parse_delay_values()?; + if values.len() > 1 { + return self.error("a multi-value delay list is only allowed on a gate instantiation"); + } + Ok(values.remove(0)) } /// True when the cursor opens a `bind` directive (IEEE 1800 §23.11). @@ -3380,7 +3431,7 @@ impl<'a> Parser<'a> { let mut instances = Vec::new(); if self.eat_sym(":") { loop { - instances.push(self.expect_name()?); + instances.push(self.parse_bind_instance()?); if !self.eat_sym(",") { break; } @@ -3391,6 +3442,23 @@ impl<'a> Parser<'a> { Ok(BindDirective { target, target_comments, target_span, instances, module_comments, inst }) } + /// One entry of a `bind`'s `: instance_list`. The LRM spells these as bare + /// instance names, but vendor tools accept — and OpenTitan writes — a + /// hierarchical path: `bind prim_packer_fifo : + /// dut.u_entropy_src_core.u_prim_packer_fifo_precon ...` + /// (`entropy_src/dv/tb/tb.sv:94`). The dots are glued into the one name + /// the list already carries, exactly as `bind`'s own target path is. + fn parse_bind_instance(&mut self) -> PResult { + let start = self.here(); + let mut text = self.expect_ident()?; + while self.cur().is_sym(".") { + self.bump(); + text.push('.'); + text.push_str(&self.expect_ident()?); + } + Ok(Name { text, span: self.span_from(start) }) + } + fn parse_instantiation(&mut self) -> PResult { let module_start = self.here(); let mut module = self.expect_ident()?; @@ -3665,9 +3733,9 @@ impl<'a> Parser<'a> { let gate = self.bump().text; let delay = if self.cur().is_sym("#") { self.bump(); - Some(self.parse_delay_value()?) + self.parse_delay_values()? } else { - None + Vec::new() }; let mut instances = Vec::new(); loop { @@ -4363,6 +4431,10 @@ impl<'a> Parser<'a> { // 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()?)), + // A block-scoped type (IEEE 1800 §6.18), e.g. + // `spi_host/dv/env/seq_lib/spi_host_base_vseq.sv:577`. Same + // grammar and same layout as the item-level `typedef`. + "typedef" => Ok(StmtKind::Typedef(self.parse_typedef()?)), "input" | "output" | "inout" => { let d = self.parse_port_decl()?; Ok(StmtKind::PortDecl(d)) @@ -4509,15 +4581,29 @@ impl<'a> Parser<'a> { self.expect_sym("[")?; let mut vars = Vec::new(); if !self.cur().is_sym("]") { - vars.push(self.expect_name()?); + vars.push(self.parse_foreach_var()?); while self.eat_sym(",") { - vars.push(self.expect_name()?); + vars.push(self.parse_foreach_var()?); } } self.expect_sym("]")?; Ok((expr, vars)) } + /// One loop-variable slot of a `foreach`'s bracket list. A dimension may + /// be **skipped** (IEEE 1800 §12.7.3) by writing nothing in its slot — + /// `foreach (cfg.mem_bkdr_util_h[, bank])` + /// (`ip_templates/flash_ctrl/dv/env/flash_ctrl_env.sv:43`) iterates only + /// the second dimension. A skipped slot is an empty name at the point it + /// was written: it declares nothing, and it prints as nothing. + fn parse_foreach_var(&mut self) -> PResult { + if self.cur().is_sym(",") || self.cur().is_sym("]") { + let here = self.here(); + return Ok(Name { text: String::new(), span: self.span_from(here) }); + } + self.expect_name() + } + fn parse_for_step(&mut self) -> PResult { let lhs = self.parse_unary()?; let op = self.cur().text.clone(); @@ -4883,6 +4969,10 @@ impl<'a> Parser<'a> { || t.is_sym("[") || t.is_sym("(") || (t.is_sym("'") && self.nth(1).is_sym("(")) + // `ty'{...}` — a cast over an assignment pattern. Only a base + // that may stand left of a cast opens one, so a bare `'{...}` + // literal still reaches `parse_primary` as the whole expression. + || (t.is_sym("'{") && self.is_cast_base(base)) || t.is_sym("++") || t.is_sym("--") // `with ( ... )` (an array method's iterator argument) and @@ -5015,28 +5105,39 @@ impl<'a> Parser<'a> { }, ); } - } 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 - // hierarchical name, a size, or a parenthesized constant - // expression — `(NumLevels)'(unsigned'(j))` (corpus - // `common_cells/src/lzc.sv:67`). - if !matches!( - expr.kind, - ExprKind::Ident(_) - | ExprKind::Number(_) - | ExprKind::Scope { .. } - | ExprKind::Member { .. } - | ExprKind::Paren { .. } - ) { + } else if (t.is_sym("'") && self.nth(1).is_sym("(")) || t.is_sym("'{") { + // Cast: `expr'(x)`, or `expr'{...}` over an assignment + // pattern (IEEE 1800 §10.9.1). The casting type is a + // `constant_primary` (IEEE 1800 §6.24.1): a name, a + // package-scoped or hierarchical name, a size, a + // parenthesized constant expression — + // `(NumLevels)'(unsigned'(j))` (corpus + // `common_cells/src/lzc.sv:67`) — or a system function call, + // `$bits(x)'(y)` / `$clog2(N)'(y)`. + if !self.is_cast_base(&expr) { return self.error("unsupported cast base expression"); } - self.bump(); // ' - self.bump(); // ( - let inner = self.parse_expr()?; - self.expect_sym(")")?; - expr = self - .expr_at(start, ExprKind::Cast { ty: Box::new(expr), expr: Box::new(inner) }); + if t.is_sym("'{") { + let pattern_start = self.here(); + let inner = self.parse_assign_pattern(pattern_start)?; + expr = self.expr_at( + start, + ExprKind::Cast { ty: Box::new(expr), expr: Box::new(inner), pattern: true }, + ); + } else { + self.bump(); // ' + self.bump(); // ( + let inner = self.parse_expr()?; + self.expect_sym(")")?; + expr = self.expr_at( + start, + ExprKind::Cast { + ty: Box::new(expr), + expr: Box::new(inner), + pattern: false, + }, + ); + } } else { // `++` / `--`, the only remaining segment kind. let op = self.bump().text; @@ -5066,6 +5167,31 @@ impl<'a> Parser<'a> { Ok(self.expr_at(start, ExprKind::Stream { dir, slice, inner })) } + /// True when `e` may stand left of a cast's `'` — the `constant_primary` + /// of IEEE 1800 §6.24.1's `casting_type`. + /// + /// A **system function call** is one of those primaries, and the only + /// call shape accepted here: `$bits(periph_data_mux)'({...})` + /// (`top_earlgrey/ip_autogen/pinmux/rtl/pinmux.sv:490`) and + /// `$clog2(RomSize)'(RomSize)` (`vendor/pulp_riscv_dbg/debug_rom/ + /// debug_rom.sv:67`). An ordinary call is left out: a constant function + /// call is legal SV there, but nothing in either corpus writes one, and + /// admitting `f(x)'(y)` would also admit a mis-parse of a method call + /// followed by an unrelated sized literal. + fn is_cast_base(&self, e: &Expr) -> bool { + match &e.kind { + ExprKind::Ident(_) + | ExprKind::Number(_) + | ExprKind::Scope { .. } + | ExprKind::Member { .. } + | ExprKind::Paren { .. } => true, + ExprKind::Call { callee, .. } => { + matches!(&callee.kind, ExprKind::Ident(n) if n.starts_with('$')) + } + _ => false, + } + } + /// True when the `'{` just consumed opens the replication form /// `'{N{0}}` (IEEE 1800 §10.9.1) rather than a keyed or positional /// pattern. @@ -5101,6 +5227,51 @@ impl<'a> Parser<'a> { false } + /// An assignment pattern, the cursor on its `'{` (IEEE 1800 §10.9.1): + /// `'{a, b}`, `'{key: v}`, `'{default: 0}` and the replication form + /// `'{N{0}}`. `start` is the `'{`'s own position — a cast over a pattern + /// (`ty'{...}`) keeps the type outside the pattern's span, in the `Cast` + /// node that wraps it. + fn parse_assign_pattern(&mut self, start: u32) -> PResult { + self.bump(); // '{ + if self.at_assign_pattern_repl() { + return self.parse_assign_pattern_repl(start); + } + let mut items = Vec::new(); + if !self.cur().is_sym("}") { + loop { + let item_start = self.here(); + let mut meta = self.take_meta(); + let key_or_val = if self.cur().is_kw("default") { + self.bump(); + self.expr_at(item_start, ExprKind::Ident("default".to_string())) + } else { + self.parse_expr_or_type()? + }; + let (key, value) = if self.eat_sym(":") { + (Some(key_or_val), self.parse_expr()?) + } else { + (None, key_or_val) + }; + let item_span = self.span_from(item_start); + self.take_before_sep(&mut meta, ","); + let more = self.eat_sym(","); + if more { + meta.trailing = self.take_trailing(); + } + items.push(PatternItem { meta, key, value, span: item_span }); + if !more { + break; + } + } + if let Some(last) = items.last_mut() { + self.take_before_sep(&mut last.meta, "}"); + } + } + self.expect_sym("}")?; + Ok(self.expr_at(start, ExprKind::AssignPattern(items))) + } + /// `'{N{a, b}}`, the `'{` already consumed. fn parse_assign_pattern_repl(&mut self, start: u32) -> PResult { let count = self.parse_expr()?; @@ -5186,7 +5357,7 @@ impl<'a> Parser<'a> { self.expect_sym(")")?; return Ok(self.expr_at( start, - ExprKind::Cast { ty: Box::new(ty), expr: Box::new(inner) }, + ExprKind::Cast { ty: Box::new(ty), expr: Box::new(inner), pattern: false }, )); } // Type keyword used as an argument (e.g. `$bits(int)`). @@ -5267,45 +5438,7 @@ impl<'a> Parser<'a> { self.expect_sym("}")?; Ok(self.expr_at(start, ExprKind::Concat(items))) } - "'{" => { - self.bump(); - if self.at_assign_pattern_repl() { - return self.parse_assign_pattern_repl(start); - } - let mut items = Vec::new(); - if !self.cur().is_sym("}") { - loop { - let item_start = self.here(); - let mut meta = self.take_meta(); - let key_or_val = if self.cur().is_kw("default") { - self.bump(); - self.expr_at(item_start, ExprKind::Ident("default".to_string())) - } else { - self.parse_expr_or_type()? - }; - let (key, value) = if self.eat_sym(":") { - (Some(key_or_val), self.parse_expr()?) - } else { - (None, key_or_val) - }; - let item_span = self.span_from(item_start); - self.take_before_sep(&mut meta, ","); - let more = self.eat_sym(","); - if more { - meta.trailing = self.take_trailing(); - } - items.push(PatternItem { meta, key, value, span: item_span }); - if !more { - break; - } - } - if let Some(last) = items.last_mut() { - self.take_before_sep(&mut last.meta, "}"); - } - } - self.expect_sym("}")?; - Ok(self.expr_at(start, ExprKind::AssignPattern(items))) - } + "'{" => self.parse_assign_pattern(start), _ => self.error("expected expression"), } } @@ -6414,13 +6547,17 @@ mod tests { #[test] fn the_two_shapes_left_open_by_ansi_first_port_still_refuse() { - // Pinned so a future round that changes either does it on purpose + // Pinned so a future round that changes it does it on purpose // (docs/features/ansi-first-port/README.md, Status): the generic - // `interface` port is a different production wanting a "any - // interface" DataType, and a modport-qualified *declaration* type - // would change how a `.` after an identifier reads everywhere. + // `interface` port is a different production wanting an "any + // interface" DataType. assert!(parse_err("module m (interface bus);\nendmodule\n").contains("expected")); - assert!(parse_err("module m;\n virtual bus_if.mp v;\nendmodule\n").contains("expected")); + // The second shape that round left open, `virtual bus_if.mp v;`, is + // closed by docs/features/testbench-mopup/README.md — but only + // after `virtual`, so a `.` after a bare identifier still reads as a + // member access everywhere else, which is what that round was + // protecting. + assert!(parse_err("module m;\n bus_if.mp v;\nendmodule\n").contains("expected")); } #[test] @@ -8459,4 +8596,234 @@ mod tests { "a directive starting a statement list is pass-through, not a split" ); } + + // ------------------------------------------------------------------ + // The mop-up round: docs/features/testbench-mopup/README.md + // ------------------------------------------------------------------ + + /// The statements of the first module item, which every mop-up statement + /// test wants. + fn block_stmts(f: &SourceFile) -> &[Stmt] { + let m = module_of(f); + let stmt = match &m.items[0].kind { + ItemKind::Initial(s) | ItemKind::Always { stmt: s, .. } => s, + other => panic!("expected an initial/always, got {other:?}"), + }; + let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") }; + stmts + } + + #[test] + fn a_typedef_is_a_statement_inside_a_block() { + // hw/ip/spi_host/dv/env/seq_lib/spi_host_base_vseq.sv:577 and the + // three other spellings the sweep contains, all in one block. + let f = parse_ok( + "module m;\n initial begin\n typedef enum bit {WRITE = 1'b1} rdwr_e;\n \ + typedef bit data_result[];\n typedef struct {int a;} s_t;\n \ + typedef class fwd;\n end\nendmodule\n", + ); + let stmts = block_stmts(&f); + let names: Vec<&str> = stmts + .iter() + .map(|s| match &s.kind { + StmtKind::Typedef(t) => t.name.as_str(), + other => panic!("expected a typedef statement, got {other:?}"), + }) + .collect(); + assert_eq!(names, ["rdwr_e", "data_result", "s_t", "fwd"]); + } + + #[test] + fn a_typedef_statement_carries_the_same_payload_as_the_item() { + // Same node type, so nothing downstream needs a second shape. + let f = parse_ok( + "module m;\n initial begin\n typedef enum bit {A, B} e_t;\n end\nendmodule\n", + ); + let StmtKind::Typedef(t) = &block_stmts(&f)[0].kind else { panic!("expected a typedef") }; + let TypedefKind::Enum(e) = &t.kind else { panic!("expected an enum") }; + assert_eq!(e.members.iter().map(|m| m.name.as_str()).collect::>(), ["A", "B"]); + } + + #[test] + fn a_system_function_call_may_be_a_casting_type() { + // hw/top_earlgrey/ip_autogen/pinmux/rtl/pinmux.sv:490 and + // hw/vendor/pulp_riscv_dbg/debug_rom/debug_rom.sv:67. + for src in [ + "module m;\n assign y = $bits(x)'({a, b});\nendmodule\n", + "module m;\n assign y = $clog2(RomSize)'(RomSize);\nendmodule\n", + ] { + let f = parse_ok(src); + let m = module_of(&f); + let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") }; + let ExprKind::Cast { ty, pattern, .. } = &a.assigns[0].rhs.kind else { + panic!("expected a cast in {src:?}") + }; + assert!(!pattern, "the `'(...)` spelling"); + assert!(matches!(&ty.kind, ExprKind::Call { .. }), "the casting type is the call"); + } + // An *ordinary* call is still not a casting type: the net stays as + // narrow as the corpus needs it. + assert!(parse_err("module m;\n assign y = f(x)'(z);\nendmodule\n") + .contains("unsupported cast base expression")); + } + + #[test] + fn an_enum_member_may_carry_a_name_range() { + // hw/top_earlgrey/ip_autogen/rstmgr/rtl/rstmgr_pkg.sv:101 (`[hi:lo]`) + // and hw/top_earlgrey/dv/env/chip_env_pkg.sv:88 (`[N]`). + let f = parse_ok("typedef enum {A[0:1], B, C[16] = 5} e_t;\n"); + let ItemKind::Typedef(t) = &f.items[0].kind else { panic!("expected a typedef") }; + let TypedefKind::Enum(e) = &t.kind else { panic!("expected an enum") }; + assert!(matches!( + e.members[0].range.as_slice(), + [Dim { kind: DimKind::Range { b: Some(_), .. }, .. }] + )); + assert!(e.members[1].range.is_empty(), "a plain member has no range"); + assert!(matches!( + e.members[2].range.as_slice(), + [Dim { kind: DimKind::Range { b: None, .. }, .. }] + )); + assert!(e.members[2].value.is_some(), "the range does not swallow the `= 5`"); + } + + #[test] + fn a_cast_may_be_applied_to_an_assignment_pattern() { + // hw/dv/sv/cip_lib/cip_base_scoreboard.sv:442. + let f = parse_ok("module m;\n assign y = expected_alert_t'{1, is_fatal};\nendmodule\n"); + let m = module_of(&f); + let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") }; + let ExprKind::Cast { ty, expr, pattern } = &a.assigns[0].rhs.kind else { + panic!("expected a cast") + }; + assert!(*pattern, "the `'{{...}}` spelling"); + assert!(matches!(&ty.kind, ExprKind::Ident(n) if n == "expected_alert_t")); + assert!(matches!(&expr.kind, ExprKind::AssignPattern(items) if items.len() == 2)); + } + + #[test] + fn the_two_cast_spellings_over_a_pattern_stay_distinct() { + // `ty'('{...})` and `ty'{...}` are different token streams; only the + // `pattern` flag keeps the printer from collapsing one into the other. + let f = parse_ok("module m;\n assign y = bar_t'('{a: 1});\nendmodule\n"); + let m = module_of(&f); + let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") }; + let ExprKind::Cast { expr, pattern, .. } = &a.assigns[0].rhs.kind else { + panic!("expected a cast") + }; + assert!(!pattern, "the parens are the cast's, not the pattern's"); + assert!(matches!(&expr.kind, ExprKind::AssignPattern(_))); + // And a bare pattern is still a whole expression, not a cast. + let f = parse_ok("module m;\n assign y = '{a: 1};\nendmodule\n"); + let m = module_of(&f); + let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") }; + assert!(matches!(&a.assigns[0].rhs.kind, ExprKind::AssignPattern(_))); + } + + #[test] + fn a_gate_takes_a_multi_value_delay_list() { + // hw/top_earlgrey/ip/ast/rtl/aon_osc.sv:41. + let f = parse_ok( + "module m;\n buf #(RDLY, 0) b0 (o, a);\n and #(1, 2, 3) g (o, a, b);\n \ + buf #(5) b1 (o, a);\n buf #5 b2 (o, a);\n buf b3 (o, a);\nendmodule\n", + ); + let m = module_of(&f); + let lens: Vec = m + .items + .iter() + .map(|i| match &i.kind { + ItemKind::GateInstantiation(g) => g.delay.len(), + other => panic!("expected a gate, got {other:?}"), + }) + .collect(); + assert_eq!(lens, [2, 3, 1, 1, 0]); + // The one-value parenthesized spelling keeps its `Paren` node, which + // is what makes `#(5)` print back as `#(5)` and not as `#5`. + let ItemKind::GateInstantiation(g) = &m.items[2].kind else { panic!("expected a gate") }; + assert!(matches!(g.delay[0].kind, ExprKind::Paren { .. })); + } + + #[test] + fn a_multi_value_delay_is_refused_where_only_a_gate_may_write_one() { + // A net declaration and a continuous assignment take one delay; the + // message says which construct the list belongs to. + assert!(parse_err("module m;\n wire #(1, 2) w;\nendmodule\n") + .contains("only allowed on a gate instantiation")); + assert!(parse_err("module m;\n assign #(1, 2) y = x;\nendmodule\n") + .contains("only allowed on a gate instantiation")); + } + + #[test] + fn a_virtual_interface_type_may_name_a_modport() { + // hw/ip/spi_device/pre_dv/tb/spid_jedec_tb.sv:32 (a declaration) and + // .../spid_common.sv:563 (a task argument). + let f = parse_ok("module m;\n virtual spi_if.tb tb_sif = sif.tb;\nendmodule\n"); + let m = module_of(&f); + let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") }; + assert_eq!(d.qualifiers, ["virtual"]); + assert_eq!(d.ty.name, "spi_if.tb"); + assert_eq!(d.declarators[0].name, "tb_sif"); + + let f = parse_ok("module m;\n task t(virtual spi_if.tb sif);\n endtask\nendmodule\n"); + let m = module_of(&f); + let ItemKind::Task(t) = &m.items[0].kind else { panic!("expected a task") }; + assert_eq!(t.args[0].ty.name, "spi_if.tb"); + assert!(t.args[0].ty.virt.is_some(), "still a virtual interface type"); + } + + #[test] + fn a_dot_after_a_plain_type_name_is_still_not_a_modport() { + // The widening is scoped to `virtual`, which is what keeps a `.` + // after an identifier reading as a member access everywhere else + // (docs/features/ansi-first-port/README.md, Status). + assert!(parse_err("module m;\n bus_if.mp v;\nendmodule\n").contains("expected")); + } + + #[test] + fn a_struct_member_may_be_declared_rand() { + // hw/ip/spi_host/dv/env/spi_host_env_pkg.sv:64 — not LRM-legal, but + // real, vendor-accepted code. + let f = parse_ok("typedef struct {\n rand bit cpol;\n randc int n;\n bit p;\n} c_t;\n"); + let ItemKind::Typedef(t) = &f.items[0].kind else { panic!("expected a typedef") }; + let TypedefKind::Struct(s) = &t.kind else { panic!("expected a struct") }; + assert_eq!(s.members[0].qualifiers, ["rand"]); + assert_eq!(s.members[1].qualifiers, ["randc"]); + assert!(s.members[2].qualifiers.is_empty()); + assert_eq!(s.members[0].declarators[0].name, "cpol"); + } + + #[test] + fn a_foreach_may_skip_a_dimension() { + // hw/ip_templates/flash_ctrl/dv/env/flash_ctrl_env.sv:43. A skipped + // slot is an empty name at the point the source wrote nothing. + let f = parse_ok( + "module m;\n initial begin\n foreach (h[, bank]) x = 1;\n \ + foreach (h[i, , k]) y = 2;\n end\nendmodule\n", + ); + let stmts = block_stmts(&f); + let StmtKind::Foreach { vars, .. } = &stmts[0].kind else { panic!("expected a foreach") }; + assert_eq!(vars.iter().map(|v| v.text.as_str()).collect::>(), ["", "bank"]); + assert!(vars[0].span.is_empty(), "a skipped slot occupies no source"); + let StmtKind::Foreach { vars, .. } = &stmts[1].kind else { panic!("expected a foreach") }; + assert_eq!(vars.iter().map(|v| v.text.as_str()).collect::>(), ["i", "", "k"]); + } + + #[test] + fn a_bind_instance_may_be_a_hierarchical_path() { + // hw/ip/entropy_src/dv/tb/tb.sv:94. + let f = + parse_ok("bind prim_packer_fifo : dut.u_core.u_fifo fifo_if #(.P(1)) u (.clk_i);\n"); + let ItemKind::Bind(b) = &f.items[0].kind else { panic!("expected a bind") }; + assert_eq!(b.target, "prim_packer_fifo"); + assert_eq!( + b.instances.iter().map(|i| i.text.as_str()).collect::>(), + ["dut.u_core.u_fifo"] + ); + // A bare name and a path may share one list. + let f = parse_ok("bind foo : a.b, plain bar u (.x);\n"); + let ItemKind::Bind(b) = &f.items[0].kind else { panic!("expected a bind") }; + assert_eq!( + b.instances.iter().map(|i| i.text.as_str()).collect::>(), + ["a.b", "plain"] + ); + } } diff --git a/crates/vlog_parser/tests/error_recovery.rs b/crates/vlog_parser/tests/error_recovery.rs index 7fc5c86..602879f 100644 --- a/crates/vlog_parser/tests/error_recovery.rs +++ b/crates/vlog_parser/tests/error_recovery.rs @@ -287,6 +287,44 @@ endfunction : my_seq assert!(parse_source(src).is_ok(), "strict parse must agree with tolerant"); } +/// The mop-up round's nine shapes, all in one buffer: the strict parser +/// accepts them, so the tolerant parser must report nothing at all. A gap +/// that still failed here would be worse than a plain refusal — an editor +/// would show the diagnostic on every keystroke. +/// +/// See `docs/features/testbench-mopup/README.md`. +#[test] +fn the_mopup_shapes_report_nothing_in_tolerant_mode() { + let src = "\ +package p; + typedef enum logic [1:0] {ReqPeriResetIdx[0:1], ReqMainPwrResetIdx} reset_idx_e; + typedef struct { + rand bit cpol; + randc bit [3:0] csnlead; + } cfg_t; +endpackage + +module tb; + virtual spi_if.tb tb_sif = sif.tb; + buf #(ast_bhv_pkg::AON_EN_RDLY, 0) b0 (en_osc_re_buf, (vcore_pok_h_i && aon_en_i)); + assign periph_data_mux = $bits(periph_data_mux)'({periph_to_mio_i, 1'b0}); + + bind prim_packer_fifo : dut.u_core.u_fifo fifo_if #(.P(1)) u_fifo_exc_if (.clk_i); + + initial begin + typedef enum bit {WRITE = 1'b1, READ = 1'b0} rdwr_e; + typedef bit data_result[]; + foreach (cfg.mem_bkdr_util_h[, bank]) begin + q.push_back(mem_item_t'{addr, mask}); + end + end +endmodule +"; + let (_, diags) = parse_source_tolerant(src); + assert!(diags.is_empty(), "a mop-up shape still reports: {diags:?}"); + assert!(parse_source(src).is_ok(), "strict parse must agree with tolerant"); +} + // ---------------------------------------------------------------------- // Guarantee 2: diagnostics and error nodes stay inside the file // ---------------------------------------------------------------------- diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index 80774d5..c4c24fb 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -74,6 +74,13 @@ const SOURCES: &[&str] = &[ // Out-of-block constraints: the verbatim leaf reached from item position, // at file scope and inside a package, with a scope chain and a stray `;`. "class c;\n extern constraint x;\nendclass\nconstraint c::x {\n a == 0; // why\n}; // after\npackage p;\n constraint q::inner::deep_c { b < 4; }\nendpackage\n", + // The mop-up round: a block-scoped typedef, enum name ranges, a cast over + // an assignment pattern and one over a system function call, a gate delay + // list, a modport-qualified virtual interface, a `rand` struct member, a + // skipped `foreach` dimension, and a hierarchical `bind` instance path. + "package p;\n typedef enum logic [1:0] {A[0:1], B, C[4] = 5} e_t;\n typedef struct {\n rand bit cpol;\n randc int n;\n } cfg_t;\nendpackage\n", + "module m;\n virtual spi_if.tb tb_sif = sif.tb;\n buf #(RDLY, 0) b0 (o, a);\n and #(1, 2, 3) g (o, a, b);\n assign y = $bits(x)'({a, b});\n assign z = item_t'{addr: a, data: d};\n initial begin\n typedef enum bit {W = 1'b1} rdwr_e;\n typedef bit dyn_t[];\n foreach (h[, bank]) x = 1;\n foreach (h[i, , k]) y = 2;\n end\nendmodule\n", + "bind prim_packer_fifo : dut.u_core.u_fifo fifo_if #(.P(1)) u (.clk_i);\nbind foo : a.b, plain bar u (.x);\n", // Dynamic types: queues, dynamic and associative arrays, `$` indexes, // 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", @@ -466,30 +473,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { ItemKind::Directive(raw) | ItemKind::MacroItem(MacroCall { raw, .. }) => { assert_inside(src, "raw text", raw.span, here); } - ItemKind::Typedef(t) => { - check_name(src, "typedef name", &t.name, t.name_span, here); - if let TypedefKind::Enum(e) = &t.kind { - for d in &e.directives { - assert_inside(src, "list directive", d.raw.span, here); - } - for member in &e.members { - assert_inside(src, "enum member", member.span, here); - check_name( - src, - "enum member name", - &member.name, - member.name_span, - member.span, - ); - } - } - if let TypedefKind::Struct(s) = &t.kind { - for member in &s.members { - assert_inside(src, "struct member", member.span, here); - check_declarators(src, &member.declarators, member.span); - } - } - } + ItemKind::Typedef(t) => check_typedef(src, t, here), ItemKind::ParamDecl(p) => check_declarators(src, &p.declarators, here), ItemKind::DataDecl(d) => check_declarators(src, &d.declarators, here), ItemKind::PortDecl(p) => check_declarators(src, &p.declarators, here), @@ -515,10 +499,22 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { despace(&b.target), "the bind target span does not slice back to its name" ); - check_names(src, "bind instance name", &b.instances, here); + // An instance may itself be a hierarchical path, glued the same + // way, so it gets the same modulo-whitespace comparison. + for i in &b.instances { + assert_inside(src, "bind instance name", i.span, here); + assert_eq!( + despace(slice(src, i.span)), + despace(&i.text), + "the bind instance span does not slice back to its name" + ); + } check_instantiation(src, &b.inst, here); } ItemKind::GateInstantiation(g) => { + for d in &g.delay { + check_expr(src, d, here); + } for i in &g.instances { assert_inside(src, "gate instance", i.span, here); check_opt_name(src, "gate instance name", i.name.as_ref(), i.name_span, i.span); @@ -715,6 +711,30 @@ fn check_gen_block(src: &str, b: &GenBlock, parent: TextRange) { } } +/// Shared by the item form and the block-scoped statement form, which carry +/// the same [`Typedef`] payload. +fn check_typedef(src: &str, t: &Typedef, here: TextRange) { + check_name(src, "typedef name", &t.name, t.name_span, here); + if let TypedefKind::Enum(e) = &t.kind { + for d in &e.directives { + assert_inside(src, "list directive", d.raw.span, here); + } + for member in &e.members { + assert_inside(src, "enum member", member.span, here); + check_name(src, "enum member name", &member.name, member.name_span, member.span); + for dim in &member.range { + assert_inside(src, "enum member range", dim.span, member.span); + } + } + } + if let TypedefKind::Struct(s) = &t.kind { + for member in &s.members { + assert_inside(src, "struct member", member.span, here); + check_declarators(src, &member.declarators, member.span); + } + } +} + fn check_declarators(src: &str, declarators: &[Declarator], parent: TextRange) { for d in declarators { assert_inside(src, "declarator", d.span, parent); @@ -795,6 +815,7 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) { } StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => check_expr(src, e, here), StmtKind::VarDecl(d) => check_declarators(src, &d.declarators, here), + StmtKind::Typedef(t) => check_typedef(src, t, here), StmtKind::ParamDecl(p) => check_declarators(src, &p.declarators, here), StmtKind::PortDecl(p) => check_declarators(src, &p.declarators, here), StmtKind::Return(e) => check_opt_expr(src, e.as_ref(), here), @@ -845,7 +866,7 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) { ExprKind::Unary { expr, .. } | ExprKind::Postfix { expr, .. } | ExprKind::Paren { inner: expr, .. } => check_expr(src, expr, here), - ExprKind::Cast { ty, expr } => { + ExprKind::Cast { ty, expr, .. } => { check_expr(src, ty, here); check_expr(src, expr, here); } diff --git a/crates/vlog_semantic/src/bind.rs b/crates/vlog_semantic/src/bind.rs index 10df9a8..b6b50ff 100644 --- a/crates/vlog_semantic/src/bind.rs +++ b/crates/vlog_semantic/src/bind.rs @@ -308,7 +308,9 @@ impl<'a> Binder<'a> { // Handshakes. ItemKind::Bind(b) => self.bind_instantiation_module(&b.inst, scope), ItemKind::GateInstantiation(g) => { - self.bind_opt_expr(g.delay.as_ref(), scope); + for d in &g.delay { + self.bind_expr(d, scope); + } for inst in &g.instances { if let (Some(name), Some(ns)) = (&inst.name, inst.name_span) { self.declare(scope, name, SymbolKind::Instance, ns, inst.span); @@ -997,6 +999,8 @@ impl<'a> Binder<'a> { StmtKind::Foreach { target, vars, body } => { let inner = self.new_scope(ScopeKind::Block, scope, stmt.span); self.bind_expr(target, scope); + // A skipped dimension (`arr[, j]`) arrives as an empty name; + // `declare` already ignores those, so it declares nothing. for v in vars { self.declare(inner, &v.text, SymbolKind::Var, v.span, v.span); } @@ -1027,6 +1031,10 @@ impl<'a> Binder<'a> { } StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => self.bind_expr(e, scope), StmtKind::VarDecl(d) => self.bind_data_decl(d, stmt.span, scope), + // A block-scoped type binds exactly as an item-level one does; the + // scope it lands in is the enclosing block's, which is what + // IEEE 1800 §6.18 asks for. + StmtKind::Typedef(t) => self.bind_typedef(t, stmt.span, scope), StmtKind::ParamDecl(p) => { self.bind_declarators(&p.declarators, SymbolKind::Param, &p.ty, stmt.span, scope) } diff --git a/docs/features/testbench-mopup/README.md b/docs/features/testbench-mopup/README.md new file mode 100644 index 0000000..7eed79c --- /dev/null +++ b/docs/features/testbench-mopup/README.md @@ -0,0 +1,633 @@ +# testbench-mopup + +## Goal + +Close the small, well-scoped grammar gaps `syntax_coverage.md` left after the +testbench-syntax wave's three big rounds — its own ranked recommendation #3, +"sweep the small, well-scoped grammar gaps as one mop-up round". Nine shapes, +**47 OpenTitan files** blocked between them, no two of which share a parser +path: a block-scoped `typedef` statement, a system function call used as a +casting type, enum member ranges, a cast applied to an assignment pattern, a +gate's multi-value delay list, a modport-qualified virtual interface type, +`rand` on a plain struct member, a `foreach` with a skipped dimension, and a +hierarchical path in a `bind`'s instance list. + +None of these is a new *kind* of thing lucisv must model. In every one the new +surface is data the source already laid out — a bracket, a qualifier word, a +modport suffix, one more delay value — so there is no layout decision in any of +them, and the printer work is "put the bytes back where they were". That is why +they were worth bundling: nine independent one-function changes with one +build/sweep/corpus/README overhead, exactly as `mop-up-2` did for an earlier +grab-bag. + +Result: the OpenTitan sweep goes **88 → 43** failures, 45 files clean, 2 +advanced to a different documented bucket, **zero** newly failing. + +## Assumptions + +### The corpus is the specification, and it disagreed with the analysis twice + +Every bucket was re-read at its real `file:line` before anything was written, +and two of the brief's bucket labels did not survive that reading: + +- **Bucket 6 is not drive strengths.** `syntax_coverage.md` §6 called the nine + `unsupported cast base expression` files "`weak0'(...)`/`pull1'(...)` as a + cast base". A `grep` for that spelling across all 3,943 files finds **zero** + occurrences. The eight files that actually raise that message are all a + **system function call** used as the casting type — + `$bits(periph_data_mux)'({...})` (`pinmux.sv:490`, three tops) and + `$clog2(RomSize)'(RomSize)` (`pulp_riscv_dbg`, five files) — which is a + `constant_primary` and therefore legal `casting_type` per IEEE 1800 §6.24.1. + That is the gap this round fixed. The ninth file + (`spi_host/dv/tb.sv`, `unexpected keyword \`weak1\``) is a genuinely + different construct and is **skipped** — see Status. +- **Bucket 12 is six files, not five.** The five `spid_*_tb.sv` declarations + are joined by `spid_common.sv:563`, where the same type stands in a task's + argument list and so raises a different message. + +Both corrections are recorded here rather than in `syntax_coverage.md`, which +is not this worktree's file. + +### No verbatim capture, so invariant 4 does not engage + +Every shape here is **real grammar**: parsed into ordinary nodes and printed by +the ordinary printer. Nothing in this round captures source bytes and replays +them, so there is no new `RawText`, `verify.rs` is untouched, and the standing +"masked-corruption attack tests for a widened normalization" requirement has +nothing to attach to. What replaces it is the ordinary safety net: all 45 +newly-formatting files went through `format_source`'s own token-equivalence +and convergence checks, and the whole-tree output diff below shows the change +is a strict superset of the old behaviour. + +### Costing the AST changes against topo §2.2 + +The brief's instruction was to avoid new AST variants where a span-preserving +existing shape serves. Seven of the nine buckets needed **no** new AST surface +at all; the two that did were costed: + +| bucket | AST change | exhaustive arms it cost | +|---|---|---| +| 4 local `typedef` stmt | **new variant** `StmtKind::Typedef(Typedef)` | 3 — `format.rs`, `bind.rs`, `spans.rs`. `visit.rs`, `type_def.rs`, `linked.rs`, `selection.rs` all have wildcards and needed nothing. | +| 6 system-fn cast base | none | none | +| 8 enum member range | new field `EnumMember::range: Vec` | 2 — `parse_enum_type`, the enum printer (`spans.rs` gained a check, not an arm) | +| 10 cast-to-pattern | new field `ExprKind::Cast::pattern: bool` | 2 — the `format.rs` arm and the `spans.rs` arm; the four other `Cast` sites already used `..` | +| 11 gate delay list | `GateInstantiation::delay: Option` → `Vec` | 3 — `format.rs`, `bind.rs`, `spans.rs` | +| 12 virtual+modport | none (the modport is glued into `DataType::name`) | none | +| 14 rand on struct | new field `StructMember::qualifiers: Vec` | 1 — the struct printer | +| 15 foreach skip dim | none (an empty `Name`) | none | +| 16 bind hier path | none (dots glued into the instance `Name`) | none | + +`StmtKind::Typedef` is the one place a new variant was the right call rather +than a dodge: the statement form *is* the item form — same payload, same +layout, same binding — so reusing `Typedef` and adding one dispatch arm is both +smaller and more honest than any encoding that avoided the variant. + +### Why `Cast` needed a flag and could not just look at its argument + +The obvious zero-cost encoding of `ty'{...}` is `Cast { ty, expr: +AssignPattern(..) }` with the printer noticing that the argument is a pattern +and printing no brackets. It is wrong, because `ty'('{a: 1})` produces exactly +the same tree and would then print as `ty'{a: 1}` — a different token stream, +which the safety net would (correctly) refuse, turning a file that formats +today into one that does not. Neither corpus contains that spelling today, but +"nothing writes it yet" is not a reason to build a shape that cannot represent +it. One `bool` on the variant costs two edits and makes the two spellings +distinguishable by construction; `the_two_cast_spellings_over_a_pattern_stay_distinct` +pins it. + +### The deliberate over- and under-acceptances + +- **`is_cast_base` admits only *system* function calls.** A constant function + call is a legal casting type too, but no file in either corpus writes one, + and admitting `f(x)'(y)` would also admit a mis-read of a method call + followed by an unrelated sized literal. Pinned by the negative half of + `a_system_function_call_may_be_a_casting_type`. +- **A multi-value delay list is refused off gates.** IEEE 1800 allows + `assign #(1,2) y = x;` and `wire #(1,2) w;` too, but neither corpus writes + one and widening `ContAssign`/`DataDecl` to `Vec` would cost arms for + nothing. `parse_delay_value` now says which construct may write a list + instead of failing at the comma; pinned by + `a_multi_value_delay_is_refused_where_only_a_gate_may_write_one`. +- **`EnumMember::range` is a `Vec`, so `A[1][2]` is accepted** even + though the LRM allows one dimension. The field is echoed, never + interpreted, so the extra permissiveness costs nothing and reusing + `parse_dims`/`self.dim` is smaller than a bespoke one-dimension parser. +- **`rand` on a struct member is not LRM-legal at all** (randomization + qualifiers belong to class properties). It is in the corpus, vendor tools + take it, and lucisv models no randomization semantics either way, so the + words are carried and printed and nothing else happens. +- **The modport widening is scoped to `virtual`.** `bus_if.mp v;` without + `virtual` still refuses, which is the exact thing + `docs/features/ansi-first-port/README.md` was protecting when it left this + open — a `.` after a bare identifier still reads as a member access + everywhere. Pinned by `a_dot_after_a_plain_type_name_is_still_not_a_modport`. + +## Handshakes + +**Consumed, unchanged:** + +- `types-decls` — `parse_typedef`, `parse_dims`, `parse_opt_data_type`, + `parse_modport_port_type`. All four are called from one new place each; none + changed behaviour for its existing callers. +- `ansi-first-port` — `at_modport_port`, the `Ident . Ident Ident` lookahead + written for interface ports, reused verbatim as the modport-suffix test in + the two `virtual` positions. +- `expressions-2` — the `'{...}` assignment-pattern parse, lifted out of + `parse_primary`'s symbol match into `parse_assign_pattern` **with no change + to its body**, so that a cast can reach it. `parse_primary` now calls it + instead of inlining it. +- `bind` — `BindDirective::instances: Vec`, unchanged in type. That + feature's own README already flagged the shape ("`instances: Vec` + doesn't carry per-instance structure beyond a bare name list; the fix is the + same shape — accept a dotted path per instance name"); this round does + exactly that, and the promise `bind` made — the instance list is printed + verbatim from its names — still holds. +- `error-recovery` — untouched. Nine constructs that now parse produce no error + nodes, so there is nothing to recover from; the tolerant improvement below is + a pure consequence. +- `verify.rs` — untouched, and no capture added. Invariant 4 does not engage. + +**Promised to others:** + +- **`StmtKind::Typedef` binds in the enclosing block scope**, via the same + `Binder::bind_typedef` the item form uses. A `typedef` written inside a + `begin`/task/function therefore contributes a type symbol scoped to that + block, which is what IEEE 1800 §6.18 asks for and what a language server + wants. +- **A skipped `foreach` dimension declares nothing.** It arrives as a `Name` + with empty text and a zero-width span at the point the source wrote nothing; + `Binder::declare` already ignores empty names, so this falls out rather than + needing a guard. Anything that iterates `Foreach::vars` and assumes each is a + real variable must skip empty ones — `bind.rs` is the only such consumer + today and it does. +- **A `bind` instance name may now contain `.`.** Any consumer treating + `BindDirective::instances[i].text` as a single identifier must accept a + dotted path. `spans.rs`'s name check was widened to the same + modulo-whitespace comparison the `bind` target already used; no other + consumer reads the field. +- **A `virtual` type's `name` may now contain `.`** (`spi_if.tb`), exactly as + an interface port's already could. Same contract, one more position. + +**Requests to the lead (not acted on):** + +1. `docs/features/ansi-first-port/README.md`'s Status lists + `virtual bus_if.mp v;` as a deliberate non-goal. That is now stale — this + round closes it, narrowly. The pinning test in `parser.rs` was updated in + place (it still pins the half that remains open, the generic `interface` + port, plus the bare-identifier case the old reasoning was really about), + but the other feature's README is not this round's file. +2. `syntax_coverage.md` bucket 6's description is a mis-diagnosis (see + Assumptions). It is untracked and outside this worktree; the correction is + recorded here. + +## Status / TODO + +- [x] Bucket 4 — block-scoped `typedef` statement (10 files). +- [x] Bucket 6 — a system function call as the casting type (8 files). +- [x] Bucket 8 — enum member ranges `Name[N]` / `Name[hi:lo]` (6 files). +- [x] Bucket 10 — a cast over an assignment pattern, `ty'{...}` (6 files). +- [x] Bucket 11 — a gate's `#(rise, fall[, turn-off])` delay list (5 files). +- [x] Bucket 12 — `virtual iface.modport name` (6 files). +- [x] Bucket 14 — `rand`/`randc` on a plain struct member (3 files). +- [x] Bucket 15 — `foreach` with a skipped dimension (2 files). +- [x] Bucket 16 — a hierarchical path in a `bind`'s instance list (1 file). +- [x] OpenTitan sweep 88 → 43, set difference: **0 newly failing**. +- [x] Corpus gate 813/820 — the exact baseline, and byte-identical output on + all 817 corpus files. +- [x] Whole-tree output diff: zero output change on any of the 3,896 + previously-passing OpenTitan files. +- [x] Tolerant mode measured before and after; no file got worse. +- [x] 14 parser unit tests, 1 tolerant regression test, 3 new `spans.rs` + `SOURCES` entries, 9 formatter cases in a new `mopup_round.cases`. +- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`. +- [ ] **Skipped, deliberately: a gate's drive strength** + (`pullup (weak1) pd_in_i (...)`, `spi_host/dv/tb.sv:101`, **1 file**). + This is the ninth file `syntax_coverage.md` §6 lumped in with the cast + bases, and it is a different production: `n_output_gatetype + [drive_strength] [delay2]`, plus the single-strength `pullup_strength` + spelling `(weak1)` that `parse_opt_drive_strength` — which requires a + comma-separated pair — cannot express. Closing it needs **two** AST + changes for one file: `DriveStrength::second` widened to `Option` + (with an arm wherever a strength is printed) and a new `strength` field + on `GateInstantiation`. Judged disproportionate against a bundle whose + other eight buckets each cost at most one field; it is a clean, bounded + follow-up whenever a second file wants it. +- [ ] **Not done, out of scope:** the next blocker behind two of this round's + files — `iff` in an event control + (`spid_common.sv:1042`, `spid_upload_tb.sv:304`), which is a distinct + unbucketed shape, not a regression. + +## Work log + +### 2026-08-29 — dev (mop-up round) + +**Method.** Every bucket was read at its real `file:line` in +`/Users/guoliangchen/repo/opentitan` (read-only throughout) before a line was +written, using a script that resolves each sweep failure's reported position +back to its source. That is what caught the two mis-diagnoses recorded in +Assumptions — bucket 6 is not the construct the analysis named, and bucket 12 +has a sixth file. + +**Baseline.** 88 failures over 3,943 files on trunk `7f65a24`, not the 151 of +`syntax_coverage.md` (which predates the wave's three merged rounds) nor the +"~99" of the brief. Recorded per-file with its message so every later claim is +a set operation, not a count comparison. + +**The nine changes, each in one function.** + +1. **Local `typedef` statement.** One dispatch arm in the statement-keyword + match calling the existing `parse_typedef`, plus `StmtKind::Typedef`. The + formatter arm is `self.typedef(t)` with no `;` appended, because the item + printer already writes one. All four typedef spellings (enum, struct, + alias, `typedef class`) reach statement position for free, since it is the + same function. +2. **System function call as a casting type.** The cast-base whitelist moved + out of an inline `matches!` into `is_cast_base`, which adds one arm: + `Call` whose callee is an `Ident` starting with `$`. (`$bits` lexes as + `TokenKind::SystemIdent` and parses to `ExprKind::Ident("$bits")`, so the + test is a string prefix, not a new token concept.) +3. **Enum member ranges.** `EnumMember::range: Vec` filled by the + existing `parse_dims`, printed by the existing `self.dim` — tight against + the name, with no leading space, because the bracket is part of the name + rather than a dimension standing beside it. The range is parsed *before* + the `= value`, so `C[16] = 5` keeps both. +4. **Cast over an assignment pattern.** Two edits: `at_postfix_segment` now + treats `'{` as a postfix segment when the base may stand left of a cast + (so a bare `'{...}` literal still reaches `parse_primary` as a whole + expression), and the cast branch builds `Cast { pattern: true }` over the + pattern. The pattern parse itself was **lifted verbatim** out of + `parse_primary` into `parse_assign_pattern` so both callers share it; the + `start` it is handed is the `'{`'s own position, so the pattern's span + excludes the casting type and span nesting stays strict. +5. **Gate delay list.** `parse_delay_value` split into `parse_delay_values` + (the general form) and a one-value wrapper for nets and continuous + assignments. The one-value parenthesized spelling still produces the same + `ExprKind::Paren` node it always did, which is what keeps `#(5)` printing + as `#(5)` and `#(1:2:3)` as itself — only a real comma list yields more + than one element, and only then does the printer write its own parens. + `GateInstantiation::delay` became `Vec`. +6. **Modport-qualified virtual interface.** Two positions, because a + declaration and a type position take different routes: `parse_data_decl` + (where `virtual` has already gone into `qualifiers`) tests + `at_modport_port` before calling `parse_opt_data_type`, exactly as + `parse_ansi_port` does; `parse_opt_data_type` itself tests it right after + consuming its own `virtual`. Both glue the modport into `DataType::name`, + so nothing downstream needs a second field. +7. **`rand` on a struct member.** A `while` over `rand`/`randc` before the + member's type, into a new `qualifiers: Vec` mirroring `DataDecl`'s, + printed the same way. +8. **`foreach` with a skipped dimension.** `expect_name` replaced by + `parse_foreach_var`, which returns an empty `Name` at the current position + when the slot is empty. `join_names` then prints nothing for it, which is + exactly `[, bank]`. +9. **Hierarchical `bind` instance.** `parse_bind_instance` glues a dotted path + into one `Name`, the same three lines `parse_bind` already used for its + target. + +**One pinned test had to change.** `the_two_shapes_left_open_by_ansi_first_port_still_refuse` +asserted that `virtual bus_if.mp v;` refuses. That was a deliberate +non-goal recorded by `ansi-first-port`, whose stated reason was that "a +modport-qualified *declaration* type would change how a `.` after an +identifier reads everywhere". This round's version does not do that — it +reads the modport only after `virtual` — so the test now pins the half that +is still true (`bus_if.mp v;` without `virtual` still refuses), with a comment +naming this feature. Flagged in Handshakes as a request, not edited into the +other feature's README. + +**Measured on the real OpenTitan checkout** (3,943 `.sv`/`.svh`, +`--no-cache --check`, read-only; `git status --porcelain` in the corpus +unchanged before and after, still showing only the pre-existing +`hw/ip/aes/dv/tb/tb.sv` modification from an earlier session). + +| | before | after | +|---|---|---| +| files failing (whole sweep) | 88 | **43** | +| files this round's nine buckets blocked | 47 | 0 | +| of those, now fully clean | — | **45** | +| of those, advanced to a *different* bucket | — | 2 | +| **files that newly fail (set difference)** | — | **0** | + +The two advances are `spid_common.sv` and `spid_upload_tb.sv`, both of which +now get past the modport type and stop on `iff` in an event control — a +distinct shape no bucket in this round covers. Every other still-failing +file's message is byte-identical to its message before. + +**Strict-superset check, done as an output diff rather than a count.** Both +binaries (trunk and this worktree) were run over every file in both corpora +and their stdout compared byte for byte: + +| | files | outputs that differ | +|---|---|---| +| pinned corpus | 817 | **0** | +| whole OpenTitan tree | 3,943 | 47 — and all 47 are files that were *failing* before (45 now format, 2 changed error) | + +So no previously-passing file's formatting moved by a single byte. This is the +check that matters for a grammar widening: a count could hide a file that +started formatting differently while another started failing. + +**Idempotency** on the 45 newly-clean files: formatted through stdin twice +and diffed, **45 idempotent, 0 not**. (`format_source` runs its own +convergence check on every call, so a non-idempotent output would already have +been refused; this is the independent confirmation.) + +**Corpus gate.** `scripts/corpus_gate.sh`: +`{"passing":813,"total":820,"pct":99.1,...}` — the recorded baseline exactly, +0 verification errors, 0 crashes, no score movement in either direction. + +**Tolerant mode**, probed with a standalone crate path-depending on this +worktree's `vlog_parser` and calling `parse_source_tolerant` directly (the +method `syntax_coverage.md` documents; `lucisv check`'s exit code deliberately +discards `ParseDiagnostic`s). Run over the 88 before-failing files plus a +25-file control sample of always-clean files, with the fix stashed out and +back in: + +| | before | after | +|---|---|---| +| total diagnostics, 88 failing + 25 control | 1 644 | **1 290** | +| over the 45 files this round fixed | 147 | **0** | +| control sample (25 clean files) | 0 | 0 | +| files whose count got **worse** | — | **0** | +| `spid_common.sv` (worst cascade here) | 207 | 2 | +| `flash_ctrl_env.sv` (×2) | 28 | 0 | +| `spi_host_env_pkg.sv`, `ast.sv`, `flash_ctrl_env_pkg.sv` (×2) | 6 | 0 | + +`spid_common.sv` is the round's one real cascade collapse: a modport-qualified +type in a task's argument list wrecked the recovery for the rest of a +1,000-line file. It still reports 2 (the `iff` gap), but the buffer went from +unusable to two honest points. + +**Tests added.** + +- `crates/vlog_parser/src/parser.rs`, test module, new section — 14 tests: + `a_typedef_is_a_statement_inside_a_block`, + `a_typedef_statement_carries_the_same_payload_as_the_item`, + `a_system_function_call_may_be_a_casting_type` (with the negative half: an + ordinary call still refuses), `an_enum_member_may_carry_a_name_range`, + `a_cast_may_be_applied_to_an_assignment_pattern`, + `the_two_cast_spellings_over_a_pattern_stay_distinct`, + `a_gate_takes_a_multi_value_delay_list`, + `a_multi_value_delay_is_refused_where_only_a_gate_may_write_one`, + `a_virtual_interface_type_may_name_a_modport`, + `a_dot_after_a_plain_type_name_is_still_not_a_modport`, + `a_struct_member_may_be_declared_rand`, `a_foreach_may_skip_a_dimension`, + `a_bind_instance_may_be_a_hierarchical_path`, and the amended + `the_two_shapes_left_open_by_ansi_first_port_still_refuse`. +- `crates/vlog_parser/tests/error_recovery.rs`: + `the_mopup_shapes_report_nothing_in_tolerant_mode` — all nine shapes in one + buffer, asserting **zero** tolerant diagnostics and strict/tolerant + agreement. +- `crates/vlog_parser/tests/spans.rs`: three new `SOURCES` entries covering + all nine shapes, picked up for free by that file's existing exhaustive + walkers (byte coverage, span nesting, name-span slicing, token + reconstruction); plus a range check on `EnumMember::range`, a delay walk on + `GateInstantiation`, the `StmtKind::Typedef` arm, and the widened + `bind`-instance name comparison. The item-level typedef span check was + extracted into `check_typedef` so the statement form reuses it rather than + copying it. +- `crates/vlog_formatter/tests/cases/mopup_round.cases` (new file): 9 cases, + one per bucket, including the `ty'('{...})` round-trip that pins the two + cast spellings apart and the `#(5)`/`#5`/no-delay gate spellings that pin + the delay printer's one-value path. The harness asserts expected output + *and* idempotency per case. + +**Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets` +clean (0 warnings, no `#[allow]`); `cargo test --workspace` green; corpus gate +813/820. No `git commit`, no `git push`. + +**Deviations from the brief.** One skip, declared in Status: the gate +drive-strength file (`pullup (weak1) ...`), which the brief inherited from +`syntax_coverage.md`'s bucket-6 label. It is a different production from the +cast bases that label named, and it costs two AST changes for one file. The +eight files that label actually described are fixed. + +## QA log + +### 2026-08-29 — QA (mop-up round) + +**Verdict: SHIP**, with one real-but-narrow finding filed below (LOW +severity — LSP-only, no corruption/safety-net risk) and no other defects +found after an adversarial pass over all nine buckets. Every headline +number in the Work log was independently reproduced from scratch (not +re-derived from the dev's own scripts/output) using two freshly-built +release binaries (trunk `7f65a24` in a separate worktree, this round's +tree) and read-only sweeps. + +**Incident, disclosed up front.** My first attempt at the whole-tree +"strict superset" check ran `lucisv --no-cache ` (no `--check`) +directly over all 3,943 real OpenTitan files, not realizing that spelling +rewrites the file **in place** (`crates/lucisv/src/main.rs:280`, +`std::fs::write`). This reformatted ~3,759 files in +`/Users/guoliangchen/repo/opentitan` before I caught it via `git status`. +Recovery: `git stash push -u` (preserving the damage for forensic +inspection if ever needed, `stash@{0}`, message "QA accidental mutation +recovery snapshot"), then the working tree came back byte-identical to +committed HEAD `0098135` via the stash. Net effect: the corpus is now +**cleaner** than before my mistake — the README's noted +"one pre-existing uncommitted modification to `hw/ip/aes/dv/tb/tb.sv` from +an earlier session" is gone too, since it was never committed and I could +not disentangle it from my own accidental reformat after the fact. It was +already flagged as unrelated to any analysis, so nothing this round relied +on is affected, but the lead and the user should know the corpus is no +longer bit-for-bit what earlier sessions left it as. All further +reproduction below used **read-only** stdin/stdout mode (`lucisv - < file`) +or `--check`, verified after every sweep with `git status --porcelain` +returning empty. + +**1. Reproduced the OpenTitan sweep from scratch (88 → 43).** Built trunk +`7f65a24` in `git worktree add --detach .../scratchpad/trunk-base` and this +round's tree, ran `--no-cache --check` over all 3,943 `.sv`/`.svh` files +with both binaries (writing each file's exit code + message to its own +file, not a shared stream — my first pass shared one output file across 8 +parallel workers and silently interleaved partial lines; per-file output +fixed it). Results: **trunk 88 failing, new 43 failing, 0 newly failing, +45 newly fixed** — exact match. Confirmed the two "advanced to a different +bucket" files by diffing their messages directly: +`spid_common.sv` moved from `563:19: expected `)` (found ".")` to +`1042:19: expected `)` (found "iff")`, `spid_upload_tb.sv` from +`30:17: expected `;` (found ".")` to `304:21: expected `)` (found "iff")` +— both exactly the line numbers and shape the Work log names. + +**2. Reproduced the strict-superset / zero-output-movement claim, at full +tree scale (stronger than the dev's own methodology).** Using stdin/stdout +mode (never touches disk), diffed both binaries' formatted stdout across +all 3,943 files: of the 3,855 files trunk formats successfully, **0** +differ in the new binary — byte-for-byte and exit-code-for-exit-code +identical. Exactly 45 files flip from error to success; nothing else +moves. This is a full-tree check, not sampled — a stronger version of the +dev's own 817-file corpus check, which I also ran independently (see 4). + +**3. Reproduced idempotency (45/45).** Round-tripped each of the 45 +newly-clean files' formatted output back through the new binary a second +time via stdin/stdout (no disk writes): 0 not idempotent. + +**4. Reproduced the corpus gate.** `scripts/corpus_gate.sh ~/.cache/lucisv-corpus` +→ `{"passing":813,"total":820,"pct":99.1,...}`, 0 verification errors, 0 +crashes — the exact recorded baseline. Separately diffed stdin/stdout +output for all 860 `.sv`/`.v`/`.svh`/`.vh` files under +`~/.cache/lucisv-corpus` between trunk and new: **0 differ**. + +**5. Reproduced the tolerant-mode table, and extended it to the whole +tree.** Built two tiny standalone binaries path-depending on each +worktree's `vlog_parser` (trunk and new) calling `parse_source_tolerant` +directly, matching the dev's own methodology. Over the 45 newly-fixed +files: **147 → 0**, 0 files worse — exact match. Then ran the same probe +over **all 3,943** OpenTitan files (not just the dev's 88-failing + 25 +control sample): total diagnostics **1,644 → 1,290** (matches the dev's +reported total exactly, confirming their 88+25 sample already accounted +for every file with any diagnostics at all), **0 files worse anywhere in +the whole tree**, 47 improved (the 45 plus the two advanced files, whose +`spid_common.sv` cascade reproduced at exactly **207 → 2** and +`spid_upload_tb.sv` at **9 → 7**). + +**6. Reproduced the skip.** `spi_host/dv/tb.sv` still fails, message +unchanged (`unexpected keyword` `weak1``-shaped), confirmed identical +between trunk and new in the byte-for-byte message diff in step 1/2 — not +a half-parse, exactly as claimed. + +**7. Blast-radius audit.** For each new variant/field, grepped every match +on the enclosing type across all crates (not just the four files the dev's +README names) and read every wildcard's body, not just its existence: + +| Type/field | Consumer | Verdict | +|---|---|---| +| `StmtKind::Typedef` | `vlog_formatter::format.rs`, `vlog_semantic::bind.rs`, `vlog_parser::tests/spans.rs` | Correct — dedicated arms, reuse `check_typedef`/`bind_typedef`/item printer. | +| `StmtKind::Typedef` | `vlog_linter::visit.rs` (AST walker) | Correct — `f(stmt)` fires unconditionally before the descend-match; the new variant has no nested statements so the wildcard `_ => {}` is exactly right. | +| `StmtKind::Typedef` | `lucisv_server::linked.rs`, `selection.rs` | Correct — neither construct has a closing label or nested statement to widen selection into; wildcard is right. | +| `StmtKind::Typedef` | `lucisv_server::type_def.rs` (`stmt_site`) | **BUG — see Finding 1.** No arm; falls to `_ => None`. Not "needed nothing" as the dev's README states. | +| `StmtKind::Typedef` (block scoping) | `vlog_semantic::bind.rs` scope tree | Correct — verified live with a standalone probe: a typedef inside `initial begin...end` resolves inside the block and does **not** leak to a sibling declaration outside it (`definition_of` returns `None` for the outer use). | +| Block-scoped typedef in outline | `vlog_semantic::document_symbols` | Correct — verified live: the unnamed `initial` block bubbles its typedef/enum-variant/var children up to the module level, exactly as the "unnamed scope contributes to the enclosing level" doc comment promises. No AST-walker special-casing needed; this falls out of the generic Scope/Symbol model. | +| `EnumMember::range` | `format.rs`, `spans.rs` | Correct — printed tight against the name, span-checked. | +| `EnumMember::range` | `lucisv_server` (hover/completion/inlay/tokens) | Correct — none read the AST field directly; all go through the `Symbol`/`Reference` model, which is unaffected. | +| `StructMember::qualifiers` | `format.rs` | Correct — printed before the type. | +| `StructMember::qualifiers` | Every `lucisv_server`/`vlog_semantic` consumer of `StructMember` | Correct — all key off `SymbolKind::StructMember` (semantic model) or `.declarators`, never `.ty`'s qualifiers. | +| `GateInstantiation::delay: Vec` | `format.rs`, `bind.rs`, `spans.rs` | Correct — dedicated loops replace the old `Option` arm. | +| `GateInstantiation::delay` | `vlog_semantic::instantiations.rs`, `vlog_linter::signals.rs` | Correct — neither reads `.delay` at all (gates are explicitly excluded from the hierarchy census; signals only reads `.instances`). | +| `ExprKind::Cast::pattern` | `format.rs`, `spans.rs` | Correct — dedicated arm for `pattern: true`; `spans.rs` walks both `ty` and `expr` regardless of the flag. | +| `ExprKind::Cast::pattern` | `bind.rs`, `vlog_linter/signals.rs` | Correct — both already used `..` and only ever touch `expr`, never `ty`; unaffected by the flag. | +| `ExprKind::Cast::ty` when it is now a `Call` (`$bits(x)'(y)`) | `bind.rs` | **Not a regression** — `bind.rs`'s `Cast` arm has *never* bound `ty` for any shape (documented: "resolving \[type names\] is the work this crate does not do anywhere else either"), so `$bits(periph_data_mux)` inside a cast base gets no more and no less binding than `(NumLevels)'(x)` did before this round. Parity holds; flagged only for the record. | + +**Finding 1 — LOW severity, LSP-only, no corruption risk.** +`crates/lucisv_server/src/type_def.rs`'s `stmt_site` (used by +`textDocument/typeDefinition`) has explicit arms for `VarDecl`, +`ParamDecl`, `PortDecl`, `Block`, `If`, `Case`, `Labeled`, `For`/`While`/ +`DoWhile`/`Repeat`/`Forever`/`Foreach`, `Timing`/`Wait`, `Assert` — and a +wildcard `_ => None` for everything else, which now silently includes +`StmtKind::Typedef`. The item-level twin (`alias_site`, called from +`item_site`'s `ItemKind::Typedef` arm) already does the right thing one +level up; `stmt_site` was never given the matching arm. + +*Reproduction* (built as a temporary test, verified, then reverted so the +tree matches what ships): +```rust +let text = "\ +module m; + typedef enum logic { A, B } state_t; + task run(); + typedef state_t alias_t; + alias_t x; + endtask +endmodule +"; +jumps(&ws, &uri, at(text, "alias_t;")) // cursor on the block-scoped alias's own name +``` +Expected (by analogy with the item-level test +`an_alias_chain_is_walked_one_hop_at_a_time`, which pins exactly this +one-hop jump at item scope): `[(1, 30)]` (state_t's declaration). Actual: +`[]` — empty, no jump. Confirmed by direct build/run against this round's +`lucisv_server`, not just static reading. + +*Why LOW, not blocking*: fails safe (empty result, not a panic or a wrong +jump), affects only the "go to type definition" hop from a block-scoped +typedef's own alias name to what it aliases — a narrow, rare gesture +even among LSP users. Does not touch any hard invariant (no corruption, +no crash, `cargo test` stays green because no test exercised this exact +path). Does not block this round; recommend a one-line follow-up +(`StmtKind::Typedef(t) => alias_site(t, stmt.span),` mirroring the item +arm) whenever `lucisv_server` is next touched. Not fixed directly here +since `type_def.rs`/`lucisv_server` is outside this round's file +ownership (`vlog_parser`/`vlog_formatter`/`vlog_semantic`/`TODO.md`/the +new `docs/features/testbench-mopup/` + `mopup_round.cases`), so it is +recorded here rather than silently patched. + +**8. Production-widening attacks (all held).** +- `is_cast_base`: zero-arg system call (`$clog2()'(x)`) — accepted, + consistent with "echoed, not interpreted." An escaped identifier + spelled `\$foo` does **not** false-positive the `$`-prefix check: the + lexer's escaped-identifier token text retains the leading backslash + (`crates/vlog_parser/src/lexer.rs:301-313`), so `n.starts_with('$')` is + false for it — confirmed by reading the lexer, not just the parser. +- Multi-value delay: refused on `wire #(1,2) w;` and + `assign #(1,2) y = x;` (already pinned); also confirmed every other + delay call site (`# delay` timing control, blocking-assignment timing, + `event control`) routes through the single-value `parse_delay_value`, + not the new `parse_delay_values` — grepped all 6 call sites. +- `virtual pkg::iface_t.mp v;` (a scope, not a plain ident, before the + dot): `at_modport_port` requires `Ident "." Ident Ident`; `::` is a + distinct token from `.`, so this cleanly falls through to the ordinary + type path and refuses at the stray `.mp` rather than misreading it — + under-accepts, never corrupts. +- `EnumMember::range` accepts more than the documented over-acceptance: + besides nested dims (`A[1][2]`, documented), a dynamic-array dim + (`A[]`) and a wildcard dim (`A[*]`) also parse, since `range` reuses + the general-purpose `parse_dims`. Undocumented, but harmless by the + same "echoed, never interpreted" argument the dev already made for the + documented case — not filing as a separate finding. +- `rand`/`randc` on a struct member with a preceding attribute + (`(* attr *) rand bit cpol;`) refuses with a parse error. Verified this + is **pre-existing**, not a regression: the identical shape without + `rand` (`(* attr *) bit cpol;`) already refuses on trunk. Attributes on + struct members were never supported; this round didn't change that. + +**9. Comment/round-trip hostile variants.** A comment wedged directly +between a new production's leading token and the next real token (e.g. +`rand /* c */ bit cpol;`, `buf /* c */ #(1,2) b(o,a);`, +`typedef /* c */ enum bit {A} e_t;`, a comment inside a `foreach` skipped +slot) each trip `verify.rs`'s token-equivalence check and refuse cleanly +(exit 2, empty stdout, no corruption) rather than corrupt — invariant 1 +holds. Confirmed this is **not new to this round**: the identical +"comment between a qualifier and the next token" shape already fails the +same way on trunk for pre-existing constructs +(`rand /* c */ int x;` in a class, `input /* c */ logic a;` in a port +list, `wire /* c */ #(1) w;`). This is a known, systemic, pre-existing +formatter limitation (comments are only guaranteed preserved at +recognized attachment points — leading/before-separator/trailing — not +at arbitrary mid-construct positions), extended consistently rather than +newly introduced. Not filing as a mop-up-specific finding. +CRLF line endings round-trip correctly and idempotently through the new +gate-delay and typedef-statement productions together. + +**Gates**, re-run independently in this worktree: `cargo fmt --all -- +--check` clean; `cargo clippy --all-targets` clean (0 warnings); `cargo +test --workspace` → **2,604 passed**, 0 failed, 36 ignored (summed across +every crate's test binaries) — matches the claimed count exactly. + +**Tests added**: none needed as permanent additions — every hostile +variant I tried either matched existing pinned behavior (comment +mid-construct: pre-existing, already implicitly covered by the general +verify.rs safety net) or is the one real finding above, which is an LSP +gap outside this round's file ownership and is recorded rather than +patched. No masked-corruption attack tests were needed per invariant 4, +because this round adds no new normalization to `verify.rs` (confirmed: +`git diff` touches no file under that path). + +## Review + +**2026-08-29 — lead.** Reviewed after QA's SHIP; gates re-run on the +worktree. Nine buckets, seven of them zero-new-AST-surface, one +disciplined skip with the cost argument written down, and two +corrections to the wave's own analysis document — reading the real +file:line before believing the bucket label is exactly the discipline +the brief asked for. QA's blast-radius audit earned its place: the +missing `stmt_site` arm for `StmtKind::Typedef` was a real product gap +behind a compiling wildcard, precisely the failure mode the charter +named, and the lead applied the one-arm fix with its regression test +in this merge. QA's incident — an in-place format of the owner's +opentitan checkout via a missing `--check` — was disclosed immediately, +recovered via stash with the owner's one uncommitted file restored +token-faithfully by the lead, and produces a standing rule: QA +charters against real checkouts run `--check`/`--stdout` ONLY, and +`git status` the checkout after every sweep. The whole-tree +strict-superset check (0 of 3,855 previously-passing files' output +moved) is stronger than the round claimed for itself and is the right +bar for parser waves. Accepted; merged by the lead. OpenTitan sweep: +151 at the wave's start, 43 after this round.