diff --git a/README.md b/README.md index d75387f..05f1f7d 100644 --- a/README.md +++ b/README.md @@ -326,6 +326,10 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset: `return` - Module/gate instantiation: named and ordered connections, `.*`, parameter overrides, instance arrays +- `bind` directives (IEEE 1800 §23.11): `bind [: ]` + followed by an ordinary instantiation, at module scope, at top level and + inside `generate`. The target may be a module, interface or instance name + or a hierarchical path. See `docs/features/bind/README.md` - `generate` regions and module-level `if`/`for`/`case` - Functions and tasks (ANSI and old-style port declarations) - `typedef` (aliases, `enum`, packed `struct`/`union`, `typedef class` @@ -404,7 +408,8 @@ corpus baseline this ordering comes from: the parse rate from 58.0% to 70.5%. 72 of the 142 `extends` files now format; the other 70 advanced to a second blocker, 34 of them to item 4 below, which is now the top blocker -3. `bind` directives +3. ~~`bind` directives~~ — **done**; see `docs/features/bind/README.md`. + Unblocked 28 corpus files and moved the parse rate from 81.8% to 85.2% 4. ~~Dynamic arrays and queues — now the top blocker at 41 files (`bit x[$]`, `int q[]`)~~ — **done**; see `docs/features/dynamic-types/README.md`. Queues (`x[$]`, `q[$]`/`q[$-1]` indexing, `[$:N]`), dynamic arrays diff --git a/TODO.md b/TODO.md index d2cb15c..c10643d 100644 --- a/TODO.md +++ b/TODO.md @@ -332,6 +332,10 @@ Adapt each: `` `error``/`` `warning`` directives and elaboration system tasks (`$error`/`$fatal`/`$warning`/`$info`) at item position. `interface` (31 files) and `bind` (28) are now the top two blockers. + → bind (`docs/features/bind/README.md`) then took it from 671/820 + (81.8%, the baseline after round 21) to **699/820 (85.2%)** — all 28 + `bind` files gained, 0 lost, passing set verified as a strict superset. + `interface` (31 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/format.rs b/crates/vlog_formatter/src/format.rs index a0ac608..2f7232a 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -991,6 +991,7 @@ impl<'a> Fmt<'a> { ItemKind::Initial(s) => self.stmt_as_body(text("initial"), s), ItemKind::Final(s) => self.stmt_as_body(text("final"), s), ItemKind::Instantiation(inst) => self.instantiation(inst, depth), + ItemKind::Bind(b) => self.bind(b, depth), ItemKind::GateInstantiation(g) => self.gate_instantiation(g), ItemKind::Genvar(names) => text(format!("genvar {};", join_names(names))), ItemKind::GenerateRegion { items, dangling } => { @@ -1574,6 +1575,18 @@ impl<'a> Fmt<'a> { concat(docs) } + /// `bind [: u_a, u_b] `: the head is one flat run + /// of names, and everything after it is laid out exactly as the same + /// instantiation written on its own would be. + fn bind(&self, b: &BindDirective, depth: usize) -> Doc { + let head = if b.instances.is_empty() { + format!("bind {} ", b.target) + } else { + format!("bind {} : {} ", b.target, join_names(&b.instances)) + }; + concat(vec![text(head), self.instantiation(&b.inst, depth)]) + } + fn instantiation(&self, inst: &Instantiation, depth: usize) -> Doc { let mut docs = vec![text(inst.module.clone())]; let mut on_fresh_line = self.bracket_comments(&inst.param_comments, &mut docs, false); diff --git a/crates/vlog_formatter/tests/cases/bind.cases b/crates/vlog_formatter/tests/cases/bind.cases new file mode 100644 index 0000000..19b8750 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/bind.cases @@ -0,0 +1,295 @@ +# a bind directive is a module instantiation with a target scope in front +module m; +bind target_mod checker u_chk(.a(x),.b(y)); +endmodule +---- +module m; + bind target_mod checker u_chk (.a(x), .b(y)); +endmodule +==== +# implicit named connections, target on its own line +# corpus/ibex/vendor/lowrisc_ip/ip/prim/fpv/tb/prim_secded_22_16_bind_fpv.sv:9 +module prim_secded_22_16_bind_fpv; + bind prim_secded_22_16_tb + prim_secded_22_16_assert_fpv prim_secded_22_16_assert_fpv ( + .clk_i, + .rst_ni, + .data_i, + .data_o, + .encoded_o, + .syndrome_o, + .err_o, + .error_inject_i + ); +endmodule : prim_secded_22_16_bind_fpv +---- +module prim_secded_22_16_bind_fpv; + bind prim_secded_22_16_tb prim_secded_22_16_assert_fpv prim_secded_22_16_assert_fpv ( + .clk_i, + .rst_ni, + .data_i, + .data_o, + .encoded_o, + .syndrome_o, + .err_o, + .error_inject_i + ); +endmodule : prim_secded_22_16_bind_fpv +==== +# parameter overrides: the head does not fit, so the `#(` group breaks first +# -- the same choice the identically wide standalone instantiation makes +# corpus/ibex/vendor/lowrisc_ip/ip/prim/fpv/tb/prim_esc_rxtx_bind_fpv.sv:8 +module m; + bind prim_esc_rxtx_tb + prim_esc_rxtx_assert_fpv #(.TimeoutCntDw(6)) + prim_esc_rxtx_assert_fpv ( + .clk_i , + .rst_ni , + .esc_req_o + ); +endmodule +---- +module m; + bind prim_esc_rxtx_tb prim_esc_rxtx_assert_fpv #( + .TimeoutCntDw(6) + ) prim_esc_rxtx_assert_fpv (.clk_i, .rst_ni, .esc_req_o); +endmodule +==== +# the target may be an instance name rather than a module name +# corpus/ibex/vendor/lowrisc_ip/ip/prim/fpv/tb/prim_fifo_sync_bind_fpv.sv:17 +module m; + bind i_nopass1 prim_fifo_sync_assert_fpv #( + .Width(Width), + .Pass(1'b0) + ) i_nopass1_assert_fpv ( + .clk_i, + .rst_ni + ); +endmodule +---- +module m; + bind i_nopass1 prim_fifo_sync_assert_fpv #( + .Width(Width), + .Pass(1'b0) + ) i_nopass1_assert_fpv (.clk_i, .rst_ni); +endmodule +==== +# a `.*` connection list +# corpus/ibex/dv/uvm/core_ibex/fcov/core_ibex_fcov_bind.sv:6 +module core_ibex_fcov_bind; + bind ibex_core core_ibex_fcov_if u_fcov_bind ( + .* + ); +endmodule +---- +module core_ibex_fcov_bind; + bind ibex_core core_ibex_fcov_if u_fcov_bind (.*); +endmodule +==== +# `#(` glued to the module name gets its space back +# corpus/ibex/dv/uvm/icache/dv/fcov/ibex_icache_fcov_bind.sv:8 +module ibex_icache_fcov_bind; + bind ibex_icache ibex_icache_fcov_if#( + .NUM_FB(NUM_FB) + ) u_ibex_icache_fcov_if (.*); +endmodule +---- +module ibex_icache_fcov_bind; + bind ibex_icache ibex_icache_fcov_if #(.NUM_FB(NUM_FB)) u_ibex_icache_fcov_if (.*); +endmodule +==== +# implicit named *parameter* overrides, and an aligned connection list +# corpus/ibex/dv/verilator/simple_system_cosim/ibex_simple_system_cosim_checker_bind.sv:6 +module ibex_simple_system_cosim_checker_bind; + bind ibex_simple_system ibex_simple_system_cosim_checker#( + .SecureIbex, + .ICache, + .PMPEnable, + .PMPGranularity, + .PMPNumRegions, + .MHPMCounterNum + ) u_ibex_simple_system_cosim_checker_bind ( + .clk_i (IO_CLK), + .rst_ni (IO_RST_N), + .host_dmem_req (host_req[CoreD]), + .host_dmem_err (host_err[CoreD]) + ); +endmodule +---- +module ibex_simple_system_cosim_checker_bind; + bind ibex_simple_system ibex_simple_system_cosim_checker #( + .SecureIbex, + .ICache, + .PMPEnable, + .PMPGranularity, + .PMPNumRegions, + .MHPMCounterNum + ) u_ibex_simple_system_cosim_checker_bind ( + .clk_i (IO_CLK), + .rst_ni (IO_RST_N), + .host_dmem_req (host_req[CoreD]), + .host_dmem_err (host_err[CoreD]) + ); +endmodule +==== +# two bind directives at module scope, blank line between them kept +# corpus/opentitan/hw/ip/uart/dv/sva/uart_bind.sv:7 +module uart_bind; + bind uart tlul_assert #( + .EndpointType("Device") + ) tlul_assert_device ( + .clk_i, + .rst_ni, + .h2d (tl_i), + .d2h (tl_o) + ); + + bind uart uart_csr_assert_fpv uart_csr_assert ( + .clk_i, + .rst_ni, + .h2d (tl_i), + .d2h (tl_o) +); +endmodule +---- +module uart_bind; + bind uart tlul_assert #( + .EndpointType("Device") + ) tlul_assert_device (.clk_i, .rst_ni, .h2d(tl_i), .d2h(tl_o)); + + bind uart uart_csr_assert_fpv uart_csr_assert (.clk_i, .rst_ni, .h2d(tl_i), .d2h(tl_o)); +endmodule +==== +# the `target : instance_list` form (IEEE 1800 §23.11) +module m; +bind fifo_v3 : i_fifo_a , i_fifo_b fifo_props u_props (.clk_i, .rst_ni); +endmodule +---- +module m; + bind fifo_v3 : i_fifo_a, i_fifo_b fifo_props u_props (.clk_i, .rst_ni); +endmodule +==== +# a hierarchical target path +module m; +bind top.u_dut.u_core checker u_chk(.*); +endmodule +---- +module m; + bind top.u_dut.u_core checker u_chk (.*); +endmodule +==== +# a bind directive at top level, outside any module +bind cpu cpu_assert u_cpu_assert (.clk_i, .rst_ni); +---- +bind cpu cpu_assert u_cpu_assert (.clk_i, .rst_ni); +==== +# inside a generate region +module m; +generate +if (Enable) begin : g_chk +bind sub checker u_chk(.*); +end +endgenerate +endmodule +---- +module m; + generate + if (Enable) begin : g_chk + bind sub checker u_chk (.*); + end + endgenerate +endmodule +==== +# comments attached to a bind directive are kept +module m; + // bind the checker in + bind dut checker u_chk ( + // clock and reset come in implicitly + .clk_i, + .rst_ni // active low + ); // and that is that +endmodule +---- +module m; + // bind the checker in + bind dut checker u_chk ( + // clock and reset come in implicitly + .clk_i, + .rst_ni // active low + ); // and that is that +endmodule +==== +# an `ifdef inside the connection list of a bind +module m; + bind dut checker u_chk ( + .clk_i, +`ifdef FPV + .fpv_only_i, +`endif + .rst_ni + ); +endmodule +---- +module m; + bind dut checker u_chk ( + .clk_i, + `ifdef FPV + .fpv_only_i, + `endif + .rst_ni + ); +endmodule +==== +# a bind directive inside a `verilog_format: off` fence is untouched +module m; +// verilog_format: off + bind dut checker u_chk ( .clk_i ,.rst_ni ); +// verilog_format: on + bind dut2 checker u_chk2 ( .clk_i ,.rst_ni ); +endmodule +---- +module m; +// verilog_format: off + bind dut checker u_chk ( .clk_i ,.rst_ni ); +// verilog_format: on + bind dut2 checker u_chk2 (.clk_i, .rst_ni); +endmodule +==== +# at the line-length boundary: exactly 100 columns stays on one line +module m; + bind target_module_name checker_module_name u_checker_instance_name25 (.clk_i, .rst_ni, .a, .bcd); +endmodule +---- +module m; + bind target_module_name checker_module_name u_checker_instance_name25 (.clk_i, .rst_ni, .a, .bcd); +endmodule +==== +# one column over the limit breaks the connection list +module m; + bind target_module_name checker_module_name u_checker_instance_name260 (.clk_i, .rst_ni, .a, .bcd); +endmodule +---- +module m; + bind target_module_name checker_module_name u_checker_instance_name260 ( + .clk_i, + .rst_ni, + .a, + .bcd + ); +endmodule +==== +# `bind` is not a reserved word here: `obj.bind()` keeps parsing +module m; + initial begin + obj.bind(); + x = obj.bind; + end +endmodule +---- +module m; + initial begin + obj.bind(); + x = obj.bind; + end +endmodule +==== diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index 6d5b6a4..1781b01 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -218,6 +218,8 @@ pub enum ItemKind { Final(Stmt), Instantiation(Instantiation), GateInstantiation(GateInstantiation), + /// `bind [: ] ` (IEEE 1800 §23.11). + Bind(BindDirective), Genvar(Vec), GenerateRegion { items: Vec, @@ -647,6 +649,26 @@ pub struct Connection { pub span: TextRange, } +/// A `bind` directive: everything after the target scope is an ordinary +/// module instantiation, so it is parsed and printed as one. +#[derive(Debug)] +pub struct BindDirective { + /// The bind target: a module or interface name (`prim_secded_22_16_tb`), + /// an instance name (`i_nopass1`) or a hierarchical path + /// (`top.u_dut.u_core`), stored with its `.` separators glued. + pub target: String, + /// Byte range of `target`. A hierarchical target is stored with its `.` + /// glued, so there the slice matches `target` only modulo the whitespace + /// the source may have written around the dots — the same caveat + /// [`Instantiation::module_span`] carries for `::`. + pub target_span: TextRange, + /// The `: u_a, u_b` instance list that narrows a module target to + /// particular instances. Empty when the source wrote no `:`. + pub instances: Vec, + /// The instantiation being bound, identical in shape to a standalone one. + pub inst: Instantiation, +} + #[derive(Debug)] pub struct GateInstantiation { /// `and`, `or`, `not`, ... diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index 92d6c83..03a3e92 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -1054,6 +1054,7 @@ impl<'a> Parser<'a> { match t.kind { TokenKind::Directive => Ok(ItemKind::Directive(self.take_raw_text())), TokenKind::Keyword => self.parse_keyword_item(), + TokenKind::Ident if self.at_bind_directive() => self.parse_bind().map(ItemKind::Bind), TokenKind::Ident => self.parse_ident_item(), TokenKind::SystemIdent if ELAB_TASKS.contains(&t.text.as_str()) => { let call = self.parse_expr()?; @@ -2135,6 +2136,58 @@ impl<'a> Parser<'a> { } } + /// True when the cursor opens a `bind` directive (IEEE 1800 §23.11). + /// + /// `bind` is deliberately *not* in the lexer's keyword table — the same + /// call vfmt makes for `new`/`this`/`super` — so that `obj.bind()` keeps + /// parsing as the ordinary method call it is in existing testbenches. + /// A directive is recognized from its shape instead: the word `bind`, + /// then a target scope (a name, possibly a `.`-separated hierarchical + /// path), then either the `:` of an instance list or the module name of + /// the instantiation. A declaration of a variable called `bind` reaches + /// `;`, `,`, `=` or a dimension there, so it never matches. + fn at_bind_directive(&self) -> bool { + let t = self.cur(); + if t.kind != TokenKind::Ident || t.text != "bind" { + return false; + } + let mut p = self.pos + 1; + if !self.tokens.get(p).is_some_and(|t| t.kind == TokenKind::Ident) { + return false; + } + p += 1; + while self.tokens.get(p).is_some_and(|t| t.is_sym(".")) + && self.tokens.get(p + 1).is_some_and(|t| t.kind == TokenKind::Ident) + { + p += 2; + } + self.tokens.get(p).is_some_and(|t| t.is_sym(":") || t.kind == TokenKind::Ident) + } + + /// `bind [: , ...] [#(...)] (...);` + fn parse_bind(&mut self) -> PResult { + self.bump(); // `bind` + let start = self.here(); + let mut target = self.expect_ident()?; + while self.cur().is_sym(".") { + self.bump(); + target.push('.'); + target.push_str(&self.expect_ident()?); + } + let target_span = self.span_from(start); + let mut instances = Vec::new(); + if self.eat_sym(":") { + loop { + instances.push(self.expect_name()?); + if !self.eat_sym(",") { + break; + } + } + } + let inst = self.parse_instantiation()?; + Ok(BindDirective { target, target_span, instances, inst }) + } + fn parse_instantiation(&mut self) -> PResult { let module_start = self.here(); let mut module = self.expect_ident()?; @@ -3884,6 +3937,51 @@ mod tests { ); } + #[test] + fn bind_directive_forms() { + parse_ok( + "module top; + bind target_mod checker u_chk (.a(x), .b(y)); + bind i_inst checker #(.W(8)) u_chk2 (.*); + bind top.u_dut.u_core checker u_chk3 (.clk_i, .rst_ni); + bind fifo_v3 : i_a, i_b fifo_props u_props (.*); + endmodule", + ); + // Also at top level and inside a generate block. + parse_ok("bind cpu cpu_assert u_a (.*);\n"); + parse_ok( + "module m; + generate if (E) begin : g + bind sub checker u (.*); + end endgenerate + endmodule", + ); + } + + #[test] + fn a_bind_directive_wraps_an_ordinary_instantiation() { + let file = + parse_ok("module m;\n bind top.u_dut : u_a, u_b chk #(.W(8)) u (.a(x));\nendmodule\n"); + let m = module_of(&file); + let ItemKind::Bind(b) = &m.items[0].kind else { panic!("expected a bind directive") }; + assert_eq!(b.target, "top.u_dut"); + assert_eq!(b.instances.iter().map(|n| n.text.as_str()).collect::>(), ["u_a", "u_b"]); + assert_eq!(b.inst.module, "chk"); + assert_eq!(b.inst.params.as_ref().map(Vec::len), Some(1)); + assert_eq!(b.inst.instances[0].name, "u"); + } + + #[test] + fn bind_is_still_a_usable_identifier() { + // `bind` is not in the lexer's keyword table, so a method called + // `bind` — and a variable declared with a type of that name — keep + // parsing exactly as they did before the directive was supported. + parse_ok( + "module m;\n initial begin\n obj.bind();\n x = obj.bind;\n end\nendmodule\n", + ); + parse_ok("module m;\n bind x;\n bind y = 1;\nendmodule\n"); + } + #[test] fn expressions() { parse_ok( diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index 3afe976..95e8eca 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -496,45 +496,19 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => { check_stmt(src, stmt, here); } - ItemKind::Instantiation(inst) => { - // A scope-qualified module name (`pkg::mod`) is stored with its - // `::` glued, so the slice matches it modulo that whitespace. - assert_inside(src, "module name", inst.module_span, here); + ItemKind::Instantiation(inst) => check_instantiation(src, inst, here), + ItemKind::Bind(b) => { + // Like an instantiation's `module_span`: a hierarchical target + // is stored with its `.` glued, so the slice matches it modulo + // whitespace the source may have written around the dots. + assert_inside(src, "bind target", b.target_span, here); assert_eq!( - despace(slice(src, inst.module_span)), - despace(&inst.module), - "the instantiated module span does not slice back to its name" + despace(slice(src, b.target_span)), + despace(&b.target), + "the bind target span does not slice back to its name" ); - for d in &inst.param_directives { - assert_inside(src, "list directive", d.raw.span, here); - } - for c in inst.params.iter().flatten() { - assert_inside(src, "parameter override", c.span, here); - check_name(src, "parameter override name", &c.name, c.name_span, c.span); - check_opt_expr(src, c.expr.as_ref(), c.span); - } - for i in &inst.instances { - assert_inside(src, "instance", i.span, here); - check_name(src, "instance name", &i.name, i.name_span, i.span); - for d in &i.conn_directives { - assert_inside(src, "list directive", d.raw.span, i.span); - } - match &i.conns { - Connections::Named(cs) => { - for c in cs { - assert_inside(src, "connection", c.span, i.span); - check_name(src, "connection name", &c.name, c.name_span, c.span); - check_opt_expr(src, c.expr.as_ref(), c.span); - } - } - Connections::Ordered(cs) => { - for c in cs { - assert_inside(src, "connection", c.span, i.span); - check_opt_expr(src, c.expr.as_ref(), c.span); - } - } - } - } + check_names(src, "bind instance name", &b.instances, here); + check_instantiation(src, &b.inst, here); } ItemKind::GateInstantiation(g) => { for i in &g.instances { @@ -642,6 +616,47 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { } } +fn check_instantiation(src: &str, inst: &Instantiation, here: TextRange) { + // A scope-qualified module name (`pkg::mod`) is stored with its `::` + // glued, so the slice matches it modulo that whitespace. + assert_inside(src, "module name", inst.module_span, here); + assert_eq!( + despace(slice(src, inst.module_span)), + despace(&inst.module), + "the instantiated module span does not slice back to its name" + ); + for d in &inst.param_directives { + assert_inside(src, "list directive", d.raw.span, here); + } + for c in inst.params.iter().flatten() { + assert_inside(src, "parameter override", c.span, here); + check_name(src, "parameter override name", &c.name, c.name_span, c.span); + check_opt_expr(src, c.expr.as_ref(), c.span); + } + for i in &inst.instances { + assert_inside(src, "instance", i.span, here); + check_name(src, "instance name", &i.name, i.name_span, i.span); + for d in &i.conn_directives { + assert_inside(src, "list directive", d.raw.span, i.span); + } + match &i.conns { + Connections::Named(cs) => { + for c in cs { + assert_inside(src, "connection", c.span, i.span); + check_name(src, "connection name", &c.name, c.name_span, c.span); + check_opt_expr(src, c.expr.as_ref(), c.span); + } + } + Connections::Ordered(cs) => { + for c in cs { + assert_inside(src, "connection", c.span, i.span); + check_opt_expr(src, c.expr.as_ref(), c.span); + } + } + } + } +} + fn check_gen_if(src: &str, gi: &GenIf, parent: TextRange) { assert_inside(src, "generate if", gi.span, parent); check_expr(src, &gi.cond, gi.span); diff --git a/crates/vlog_semantic/src/bind.rs b/crates/vlog_semantic/src/bind.rs index edd8487..24361d3 100644 --- a/crates/vlog_semantic/src/bind.rs +++ b/crates/vlog_semantic/src/bind.rs @@ -241,6 +241,14 @@ impl<'a> Binder<'a> { ItemKind::Always { stmt, .. } => self.bind_stmt(stmt, scope), ItemKind::Initial(s) | ItemKind::Final(s) => self.bind_stmt(s, scope), ItemKind::Instantiation(i) => self.bind_instantiation(i, scope), + // A `bind` directive instantiates into *another* scope, so its + // instance name and connections do not belong to this one. Only + // the instantiation's module name is indexed, which is what makes + // the bound module show up as a dependency of this file. Whether + // the target scope and the connections should resolve too is a + // vlog_semantic decision — see `docs/features/bind/README.md` + // Handshakes. + ItemKind::Bind(b) => self.bind_instantiation_module(&b.inst, scope), ItemKind::GateInstantiation(g) => { self.bind_opt_expr(g.delay.as_ref(), scope); for inst in &g.instances { @@ -473,6 +481,14 @@ impl<'a> Binder<'a> { } } + /// The module-name half of [`Self::bind_instantiation`], for a `bind` + /// directive: the instance and its connections live in the target scope, + /// not in `scope`, so only the instantiated module is recorded. + fn bind_instantiation_module(&mut self, i: &Instantiation, scope: ScopeId) { + let ns = self.exact_or_empty(i.module_span, &i.module); + self.use_name(scope, &i.module, ns, Target::Module); + } + fn bind_connection(&mut self, c: &Connection, module: &str, scope: ScopeId) { if c.name != "*" { self.use_name(scope, &c.name, c.name_span, Target::Port(module.to_string())); diff --git a/docs/features/bind/README.md b/docs/features/bind/README.md new file mode 100644 index 0000000..555e314 --- /dev/null +++ b/docs/features/bind/README.md @@ -0,0 +1,201 @@ +# bind + +## Goal + +Parse and format the SystemVerilog `bind` directive (IEEE 1800-2017 §23.11) — +the second-largest parse blocker in the corpus after `interface`, at 28 files. +A directive is + +``` +bind [ : ] [ #( ) ] ( ); +``` + +where `` is a module identifier, an interface identifier or an +instance name, and **everything after it is exactly an ordinary module +instantiation**. That is the whole design point: `bind` reuses the existing +`Instantiation` node and the existing `Instantiation` layout code unchanged, so +a bound instantiation is laid out byte-for-byte the way the same instantiation +written on its own would be — same `#( )` override group, same instance name, +same connection-list group, same alignment inference for named connections. + +## What is structural, and what is verbatim + +All structural — a real `ItemKind::Bind(BindDirective)` node with a canonical +layout. Nothing is captured verbatim, no new normalization was needed, and +`crates/vlog_formatter/src/verify.rs` is untouched. + +| shape | corpus evidence | +|---|---| +| target on one line, module + instance on the next, implicit named connections (`.clk_i,`) | `corpus/ibex/vendor/lowrisc_ip/ip/prim/fpv/tb/prim_secded_22_16_bind_fpv.sv:9` (+19 sibling `prim_secded_*_bind_fpv.sv` / `prim_alert_rxtx*_bind_fpv.sv` files) | +| with `#( ... )` parameter overrides on the wrapped line | `corpus/ibex/vendor/lowrisc_ip/ip/prim/fpv/tb/prim_esc_rxtx_bind_fpv.sv:8` | +| target is an **instance** name, directive inside a module | `corpus/ibex/vendor/lowrisc_ip/ip/prim/fpv/tb/prim_fifo_sync_bind_fpv.sv:17` (12 directives in that one file) | +| `.*` connection list | `corpus/ibex/dv/uvm/core_ibex/fcov/core_ibex_fcov_bind.sv:6` | +| `#(` glued to the module name (`iface#(`) | `corpus/ibex/dv/uvm/icache/dv/fcov/ibex_icache_fcov_bind.sv:8` | +| **implicit named parameter overrides** (`.SecureIbex,` with no parens) + a hand-aligned connection table | `corpus/ibex/dv/verilator/simple_system_cosim/ibex_simple_system_cosim_checker_bind.sv:6` | +| two directives at module scope, blank line kept between them | `corpus/opentitan/hw/ip/uart/dv/sva/uart_bind.sv:7,16` | +| directive at **top level**, outside any module | `corpus/common_cells/formal/counter_properties.sv:96`, `fifo_v3_properties.sv:134`, `fall_through_register_properties.sv:84` (these three still fail on a *later* blocker, `assume` — category `assertions`, not mine) | + +**Verified already parsing, no work needed:** implicit named parameter +overrides `#(.SecureIbex, .ICache)`, `#(` with no preceding space, and `.*` all +went through the existing `parse_connection` / `parse_instantiation` path +unchanged — checked against the pre-change release binary before writing any +code, so the brief's "check whether the existing `#( )` override parser accepts +`.Name` with no parens" is answered *yes*. A case pins it for a plain +instantiation too (`bind.cases`, "implicit named *parameter* overrides"). + +## Assumptions + +- **`bind` is deliberately NOT added to the lexer keyword table.** It is a + reserved word in IEEE 1800 Table B.1, but promoting it would break + `obj.bind()` and `x = obj.bind`, because member access after `.` requires a + `TokenKind::Ident` (`parser.rs`, `self.nth(1).kind == TokenKind::Ident`). + This follows the call the codebase already makes for `new`/`this`/`super` + (see the comment in `token.rs::is_keyword`). A directive is recognized + instead by shape, in `Parser::at_bind_directive`: the word `bind`, then a + target scope (a name, optionally a `.`-separated hierarchical path), then + either the `:` of an instance list or the module name of the instantiation. + A declaration of a variable called `bind` reaches `;`, `,`, `=` or a + dimension at that point, so it never matches — pinned by + `bind_is_still_a_usable_identifier` in `parser.rs`. + A whole-word `grep` over the 820-file corpus found **no** use of `bind` as an + identifier, so this is belt-and-braces rather than a live constraint. +- **Recognition is item-position only.** `at_bind_directive` is consulted from + `parse_item_kind`, so nothing in expression or statement position changes. +- **The target is stored as one glued string** (`top.u_dut.u_core`), the same + way `Instantiation::module` glues `pkg::mod`. `BindDirective::target_span` + therefore slices back to the target only modulo whitespace written around + the dots — the caveat `module_span` already documents, and the reason + `tests/spans.rs` compares it despaced. +- **The head is one flat run of names.** `bind `, then the + instantiation. The head never breaks on its own: if the whole directive does + not fit, the instantiation's own groups (`#( )` first, then the connection + list) break exactly as they would without the `bind` prefix. Verified by + formatting the identically wide standalone instantiation and diffing — + same output, and the case comments say so. +- **A `bind` inside a `` `ifdef `` arm needs nothing special**: directives are + pass-through items, so the bind items around them parse normally (case: "an + `` `ifdef `` inside the connection list of a bind" plus a manual check of a + directive-split around whole directives). + +## Non-goals (clean parse error, never wrong output) + +- **An indexed hierarchical target** — `bind top.u_arr[0].u_core chk u (.*);`. + The path scan stops at `[`, so `at_bind_directive` declines and the file + fails to parse with `expected ';'`. There is no corpus hit + (`grep -rEn 'bind +[A-Za-z_][A-Za-z0-9_.]*\['` → zero), and supporting it + means the target stops being a plain name and becomes an expression. Left + out under "simplicity first"; the failure mode is an error with the input + emitted unchanged, which is the hard invariant, not corruption. +- **`bind` in the config-file/`bind_instantiation` sense of resolving the + target scope.** See Handshakes. + +## Handshakes + +### Consumed + +- `Parser::parse_instantiation` (`crates/vlog_parser/src/parser.rs`) — the + whole grammar after the target. `parse_bind` calls it and stores the result + verbatim; no fork, no copy. +- `Formatter::instantiation` (`crates/vlog_formatter/src/format.rs`) — the + whole layout after the target, `;` included. `Formatter::bind` emits + `text("bind [: ] ")` and then delegates. Every layout + decision listed in the brief (module name, `#(` overrides group, instance + name, connection-list group, alignment inference for named connections) + applies unchanged because none of them is re-implemented. + +### Promised / requested + +- **New AST variant `ItemKind::Bind(BindDirective)`** in + `crates/vlog_parser/src/ast.rs`. Two exhaustive matches in other crates + needed an arm; both got the minimal one: + - `crates/vlog_formatter/src/format.rs::item_kind` — delegates as above. + - `crates/vlog_semantic/src/bind.rs::bind_item` — **request for the + vlog_semantic owner.** The arm added records *only the instantiated + module name* (`bind_instantiation_module`), so a bind still makes the + bound module a resolvable dependency of the file for the workspace index. + It deliberately does **not** declare the instance or resolve the + connections: a bind instantiates into the *target* scope, so the instance + name does not belong to the enclosing scope and the connection + expressions name signals in the target module, not here — resolving them + against the enclosing scope would manufacture bogus unresolved-name + results. Whether the target scope (`b.target`, with `b.target_span` + already recorded for go-to-definition) and the connections should resolve + through the workspace index is a vlog_semantic design decision, not a + parser one. + - `crates/vlog_linter/src/visit.rs`, `vlog_formatter/src/{range,fence}.rs` + match with a wildcard arm and needed no change; a bind is a leaf item for + all three, which is correct (fences and range formatting work at item + granularity). +- `crates/vlog_parser/tests/spans.rs` — the item walker is exhaustive, so a + `Bind` arm was added. The `Instantiation` body was extracted into + `check_instantiation` and is now shared by both arms rather than duplicated. + +## Status / TODO + +- [x] Baseline score saved before any change (671/820, 81.8%). +- [x] `ItemKind::Bind` + `BindDirective` in `ast.rs`. +- [x] `Parser::at_bind_directive` (shape-based, no new keyword) and + `Parser::parse_bind`. +- [x] `Formatter::bind`, delegating wholesale to `Formatter::instantiation`. +- [x] Minimal arms in `vlog_semantic/src/bind.rs` and `tests/spans.rs`. +- [x] `crates/vlog_formatter/tests/cases/bind.cases` — 18 cases, one per + corpus shape cited above plus the `: instance_list` form, a + hierarchical target, top level, inside `generate`, attached comments, + a `` `ifdef `` inside the connection list, a `verilog_format: off` + fence, both sides of the 100-column boundary, and `obj.bind()`. +- [x] Parser-level tests: `bind_directive_forms`, + `a_bind_directive_wraps_an_ordinary_instantiation`, + `bind_is_still_a_usable_identifier`. +- [x] `cargo fmt --all`, `cargo clippy --all-targets`, `cargo test` all clean. +- [x] Score after: 699/820 (85.2%), passing set a strict superset. +- [x] `TODO.md` and `README.md` updated. + +## Work log + +### 2026-08-20 — dev + +- **Baseline.** `cargo build --release && scripts/score.sh` → + `{"passing":671,"total":820,"pct":81.8,"failures_by_category":{"interface":31,"bind":28,"dv-statements":26,"expressions":19,"directive-split":14,"assertions":13,"types-decls":11,"invalid-or-fragment":3,"lex-macro-number":2,"not-verilog":1,"other":1}}`. + TSV saved; all 28 `bind`-category rows are `expected ';' (found "")`, + i.e. the parser was reading `bind ` as a data declaration. +- **Keyword decision, made before writing code.** Grepped the whole corpus for + a whole-word `bind`: 64 hits, every one of them a real directive or a + comment — none is an identifier. Then checked the current binary on + `obj.bind(); x = obj.bind;` — it parses today precisely *because* `bind` is + an ordinary `Ident`, and member access after `.` demands `TokenKind::Ident`. + Adding `bind` to `is_keyword` would have broken it, so recognition is + shape-based instead. Recorded in Assumptions with the `new`/`this`/`super` + precedent, and pinned by a parser test and a formatter case. +- **Also checked before writing code:** whether `#(.SecureIbex, .ICache)` + (implicit named parameter overrides, no parens) already parses. It does — + `parse_connection` returns `expr: None` for a bare `.name`, and the pre-change + binary formats it. So the brief's contingency ("if not, that is in scope for + you") did not fire and no instantiation-grammar change was made at all. +- **Model.** `ItemKind::Bind(BindDirective { target, target_span, instances, + inst })`, with `inst: Instantiation` reused whole. `parse_bind` consumes + `bind`, the dotted target, the optional `: a, b` instance list, then calls + `parse_instantiation` — which also consumes the `;`. +- **Layout.** `Formatter::bind` is four lines: build the head string, then + `concat([head, self.instantiation(&b.inst, depth)])`. Confirmed by + experiment that this is genuinely the same layout: `bind prim_esc_rxtx_tb + prim_esc_rxtx_assert_fpv #(.TimeoutCntDw(6)) …` breaks its `#( )` group and + keeps the connection list flat, and a standalone instantiation padded to the + same total width makes the identical choice. Alignment inference is likewise + untouched — the `ibex_simple_system_cosim_checker_bind` case keeps its + hand-aligned connection table. +- **After.** `{"passing":699,"total":820,"pct":85.2,"failures_by_category":{"interface":31,"dv-statements":26,"expressions":19,"directive-split":14,"assertions":13,"types-decls":11,"invalid-or-fragment":3,"lex-macro-number":2,"not-verilog":1,"other":1}}`. + `bind` is gone from the histogram: **28 gained, 0 lost**, and + `comm -23 ` is empty, so the passing set is a + strict superset. +- **Still failing in my category: none.** The three `common_cells/formal/*` + files that contain a top-level `bind` are counted under `assertions`, not + `bind`: they hit an unsupported `assume` (line 38 / 36 / 61) *before* the + parser reaches the `bind` at the end of the file. Their directives were + extracted and fed through the new binary on their own — all three format + cleanly (`bind counter counter_properties #(...) i_counter_properties (.*);` + from `counter_properties.sv:96`), so nothing in this category is left over; + those files belong to the `assertions` owner. + +## QA log + +## Review