diff --git a/README.md b/README.md index c020dd3..4153357 100644 --- a/README.md +++ b/README.md @@ -330,6 +330,14 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset: 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` +- Interfaces (IEEE 1800 §25): `interface [import pkg::*;] [#( ... )] + [( ... )]; ... endinterface[: label]` — the module header's grammar, the + module body's items, plus `modport a (input x, output y), b (...);` and + `clocking cb @(posedge clk); ... endclocking` (including `default + clocking`, the anonymous and body-less spellings, and `#skew`/edge skews). + `virtual [interface] iface [#( ... )]` stands in every type position — a + `typedef` base type, a task/function argument, a declaration. See + `docs/features/interfaces/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` @@ -462,8 +470,14 @@ corpus baseline this ordering comes from: `assertions` bucket and moved the parse rate from 85.2% to 86.8%. `picorv32.v` — 3000 lines of Verilog-2001, blocked on `restrict property` since item 6 — now formats end to end -8. Interfaces/modports/clocking blocks, streaming operators, specify blocks, - `let`/`checker` — rare in the corpus RTL +8. ~~Interfaces/modports/clocking blocks~~ — **done**; see + `docs/features/interfaces/README.md`. `interface … endinterface` (header + `import`s, ANSI ports, parameters), `modport`, `clocking` blocks and + `virtual` interface types in every type position unblocked 28 corpus files + and moved the parse rate from 86.8% to 90.2%; the other 3 advanced to + blockers in the `expressions` and `other` buckets. Still open in this item: + streaming operators, specify blocks, `let`/`checker`, `program` and + `interface class` — all rare in the corpus RTL Like ruff, `vfmt` refuses to output anything for a file it cannot fully parse, so it can never corrupt code. diff --git a/TODO.md b/TODO.md index c10643d..14a7eb4 100644 --- a/TODO.md +++ b/TODO.md @@ -336,6 +336,14 @@ Adapt each: (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. + → interfaces (`docs/features/interfaces/README.md`) then took it from + 712/820 (86.8%, the baseline after round 21) to **740/820 (90.2%)** — + 28 of the 31 `interface` files gained, 0 lost, passing set verified as + a strict superset and all 28 round-tripped individually. + `interface`/`modport`/`clocking` and `virtual` interface types in + every type position are done; the 3 files left advanced to blockers in + the `expressions` and `other` buckets. `dv-statements` (26 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 c1c1b34..4232ea7 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -949,7 +949,7 @@ impl<'a> Fmt<'a> { /// A split item's closing keyword, laid out. fn tail_doc(kind: &ItemKind) -> Option { match kind { - ItemKind::Module(m) => Some(Self::closing("endmodule", &m.end_label)), + ItemKind::Module(m) => Some(Self::closing(m.end_kw(), &m.end_label)), ItemKind::Package { end_label, .. } => Some(Self::closing("endpackage", end_label)), _ => None, } @@ -1009,6 +1009,8 @@ impl<'a> Fmt<'a> { ItemKind::Function(f) => self.function(f), ItemKind::Task(t) => self.task(t), ItemKind::Class(c) => self.class(c, depth), + ItemKind::Modport(decls) => self.modport(decls), + ItemKind::Clocking(c) => self.clocking(c), ItemKind::Verbatim(raw) => self.raw_text(raw), ItemKind::Defparam(pairs) => { let parts: Vec = pairs @@ -1037,7 +1039,7 @@ impl<'a> Fmt<'a> { body.extend(self.dangling(&m.dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); - docs.push(Self::closing("endmodule", &m.end_label)); + docs.push(Self::closing(m.end_kw(), &m.end_label)); concat(docs) } @@ -1198,7 +1200,15 @@ impl<'a> Fmt<'a> { } let mut docs = Vec::new(); let mut need_space = false; + // `virtual clk_rst_if`, `virtual interface bus_if`. + if let Some(v) = ty.virt { + docs.push(text(v.text())); + need_space = true; + } if !ty.name.is_empty() { + if need_space { + docs.push(text(" ")); + } docs.push(text(ty.name.clone())); need_space = true; } @@ -1974,6 +1984,115 @@ impl<'a> Fmt<'a> { concat(docs) } + /// `modport a (input x, output y), b (...);` (IEEE 1800 §25.5). + /// + /// Each modport's port list is a breakable group of its own, laid out + /// exactly like a header port list: one line when it fits, one entry per + /// line when it does not. A direction keyword and the names it governs are + /// one entry, so the source's grouping (`input valid, data`) survives. + fn modport(&self, decls: &[ModportDecl]) -> Doc { + let mut docs = vec![text("modport")]; + let last = decls.len().saturating_sub(1); + let mut on_fresh_line = false; + for (i, d) in decls.iter().enumerate() { + if !on_fresh_line { + docs.push(text(" ")); + } + docs.extend(self.leading(&d.meta)); + docs.push(text(format!("{} ", d.name))); + let items: Vec = d + .ports + .iter() + .map(|p| ListItem::from_meta(&p.meta, self.modport_port(p)).with_comma(p.comma)) + .collect(); + docs.push(self.delimited_dangling("(", items, &d.dangling, ")", false)); + let ends_line = self.inline_comments(&d.meta.before_sep, &mut docs); + if i < last { + if ends_line { + docs.push(Doc::HardLine); + } + docs.push(text(",")); + } + on_fresh_line = false; + if let Some(tr) = &d.meta.trailing { + docs.push(text(" ")); + docs.push(self.comment(tr)); + if i < last { + docs.push(Doc::HardLine); + on_fresh_line = true; + } + } + } + docs.push(text(";")); + concat(docs) + } + + /// One direction group of a modport port list: `input valid, data`. + fn modport_port(&self, p: &ModportPort) -> Doc { + text(format!("{} {}", p.kw, join_names(&p.names))) + } + + /// `clocking cb @(posedge clk); ... endclocking` (IEEE 1800 §14.3), one + /// item per line — the body is a declaration list, not an expression, so + /// there is nothing here worth collapsing onto the header's line. + fn clocking(&self, c: &ClockingDecl) -> Doc { + let mut head = String::from(if c.is_default { "default clocking" } else { "clocking" }); + if let Some(n) = &c.name { + head.push(' '); + head.push_str(&n.text); + } + let mut docs = vec![text(head)]; + // `default clocking cb;` selects an existing block: no event, no body. + let Some(event) = &c.event else { + docs.push(text(";")); + return concat(docs); + }; + docs.push(text(" ")); + docs.push(self.sens_list(event)); + docs.push(text(";")); + let mut body = Vec::new(); + for item in &c.items { + body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + body.extend(self.leading_comments(&item.meta)); + body.push(concat(vec![self.clocking_item(&item.kind), text(";")])); + body.extend(self.trailing(&item.meta)); + } + body.extend(self.dangling(&c.dangling)); + docs.push(indent(body)); + if c.has_end { + docs.push(Doc::HardLine); + docs.push(Self::closing("endclocking", &c.end_label)); + } + concat(docs) + } + + fn clocking_item(&self, kind: &ClockingItemKind) -> Doc { + match kind { + ClockingItemKind::Default { input, output } => { + let mut s = String::from("default"); + if let Some(skew) = input { + s.push_str(" input "); + s.push_str(skew); + } + if let Some(skew) = output { + s.push_str(" output "); + s.push_str(skew); + } + text(s) + } + ClockingItemKind::Signals { dir, skew, names } => { + let mut s = dir.clone(); + if let Some(skew) = skew { + s.push(' '); + s.push_str(skew); + } + s.push(' '); + s.push_str(&join_names(names)); + text(s) + } + } + } + /// `export "DPI-C" function f;` / `export pkg::*;` — one line either way; /// no list here is long enough to be worth a breakable group. fn export(e: &ExportDecl) -> Doc { diff --git a/crates/vlog_formatter/tests/cases/interfaces.cases b/crates/vlog_formatter/tests/cases/interfaces.cases new file mode 100644 index 0000000..2874c2f --- /dev/null +++ b/crates/vlog_formatter/tests/cases/interfaces.cases @@ -0,0 +1,343 @@ +# an interface is a module with a different closing keyword +# IEEE 1800-2017 25.3 +interface simple_if; +logic a; +endinterface +---- +interface simple_if; + logic a; +endinterface +==== +# ANSI ports with no type at all, and a string parameter +# corpus/ibex/vendor/lowrisc_ip/dv/sv/common_ifs/clk_rst_if.sv:15 +interface clk_rst_if #(parameter string IfName = "main") (inout clk, inout rst_n); + bit o_clk; +endinterface +---- +interface clk_rst_if #(parameter string IfName = "main") (inout clk, inout rst_n); + bit o_clk; +endinterface +==== +# directional ports with no type, and an `endinterface : name` label +# corpus/ibex/vendor/lowrisc_ip/dv/sv/common_ifs/rst_shadowed_if.sv:11 +interface rst_shadowed_if(input rst_n, output rst_shadowed_n); + logic rst_shadowed_n_int; +endinterface : rst_shadowed_if +---- +interface rst_shadowed_if (input rst_n, output rst_shadowed_n); + logic rst_shadowed_n_int; +endinterface : rst_shadowed_if +==== +# a package import between the interface name and its port list +# corpus/ibex/dv/uvm/core_ibex/fcov/core_ibex_fcov_if.sv:8 +interface core_ibex_fcov_if import ibex_pkg::*; ( + input clk_i, + input rst_ni +); + logic x; +endinterface +---- +interface core_ibex_fcov_if + import ibex_pkg::*; +(input clk_i, input rst_ni); + logic x; +endinterface +==== +# the same import between the name and a `#(` parameter port list +# corpus/ibex/dv/uvm/core_ibex/fcov/core_ibex_pmp_fcov_if.sv:7 +interface core_ibex_pmp_fcov_if import ibex_pkg::*; #( + parameter bit PMPEnable = 1'b0 +) ( + input clk_i +); + logic y; +endinterface +---- +interface core_ibex_pmp_fcov_if + import ibex_pkg::*; +#(parameter bit PMPEnable = 1'b0) (input clk_i); + logic y; +endinterface +==== +# an import written on its own line after the name +# corpus/ibex/dv/uvm/icache/dv/env/ibex_icache_ram_if.sv:5 +interface ibex_icache_ram_if + import ibex_pkg::*; +#( + parameter int unsigned TagSizeECC = 1 +) ( + input clk +); + logic z; +endinterface +---- +interface ibex_icache_ram_if + import ibex_pkg::*; +#(parameter int unsigned TagSizeECC = 1) (input clk); + logic z; +endinterface +==== +# the same header import grammar on a module (IEEE 1800-2017 23.2.1) +module m import pkg_a::*; import pkg_b::t; #(parameter int W = 8) (input logic clk); +endmodule +---- +module m + import pkg_a::*; + import pkg_b::t; +#(parameter int W = 8) (input logic clk); +endmodule +==== +# two parameters, the second defaulting from the first +# corpus/ibex/vendor/lowrisc_ip/dv/sv/push_pull_agent/push_pull_if.sv:7 +interface push_pull_if #(parameter int HostDataWidth = 32, + parameter int DeviceDataWidth = HostDataWidth) ( + input clk, + input rst_n +); + logic req; +endinterface +---- +interface push_pull_if #( + parameter int HostDataWidth = 32, + parameter int DeviceDataWidth = HostDataWidth +) (input clk, input rst_n); + logic req; +endinterface +==== +# a doc comment on each parameter and each port +# corpus/common_cells/src/stream_intf.sv:18 +interface STREAM_DV #( + /// Custom payload type. + parameter type payload_t = logic +)( + /// Interface clock. + input logic clk_i +); + payload_t data; +endinterface +---- +interface STREAM_DV #( + /// Custom payload type. + parameter type payload_t = logic +) ( + /// Interface clock. + input logic clk_i +); + payload_t data; +endinterface +==== +# modport port lists collapse when they fit, like every other port list +# corpus/common_cells/src/stream_intf.sv:29 +interface STREAM_DV; + logic valid, ready; + modport In ( + output ready, + input valid, data + ); + modport Out ( + output valid, data, + input ready + ); +endinterface +---- +interface STREAM_DV; + logic valid, ready; + modport In (output ready, input valid, data); + modport Out (output valid, data, input ready); +endinterface +==== +# a modport too wide for one line breaks one direction group per line +interface wide_if; + modport producer (output data_valid_signal, data_payload_signal, input backpressure_signal_from_sink); +endinterface +---- +interface wide_if; + modport producer ( + output data_valid_signal, data_payload_signal, + input backpressure_signal_from_sink + ); +endinterface +==== +# several modports in one declaration, and the import/export/clocking forms +# IEEE 1800-2017 25.5 +interface m_if; + modport master (input a, output b), slave (output a, input b); + modport tb (clocking cb, import drive_task, check_task); +endinterface +---- +interface m_if; + modport master (input a, output b), slave (output a, input b); + modport tb (clocking cb, import drive_task, check_task); +endinterface +==== +# a clocking block: one item per line, skews as written +# corpus/common_cells/test/stream_register_tb.sv:75 +module stream_register_tb; + clocking cb @(posedge clk); + default input #2 output #4; + output clr, inp_data, inp_valid, oup_ready; + input inp_ready, oup_valid, oup_data; + endclocking +endmodule +---- +module stream_register_tb; + clocking cb @(posedge clk); + default input #2 output #4; + output clr, inp_data, inp_valid, oup_ready; + input inp_ready, oup_valid, oup_data; + endclocking +endmodule +==== +# an edge skew, and a `default output` half with no `input` half +# corpus/ibex/dv/uvm/icache/dv/ibex_icache_core_agent/ibex_icache_core_if.sv:31 +interface ibex_icache_core_if (input clk, input rst_n); + clocking driver_cb @(posedge clk); + default output negedge; + output req; + input negedge valid; + endclocking +endinterface +---- +interface ibex_icache_core_if (input clk, input rst_n); + clocking driver_cb @(posedge clk); + default output negedge; + output req; + input negedge valid; + endclocking +endinterface +==== +# a named `default clocking`, and an `endclocking : label` +# corpus/ibex/dv/uvm/icache/dv/ibex_icache_mem_agent/ibex_icache_mem_if.sv:19 +interface ibex_icache_mem_if (input clk); + default clocking driver_cb @(posedge clk); + input req; + endclocking : driver_cb +endinterface +---- +interface ibex_icache_mem_if (input clk); + default clocking driver_cb @(posedge clk); + input req; + endclocking : driver_cb +endinterface +==== +# an anonymous `default clocking` with an empty body +# corpus/ibex/dv/formal/check/top.sv:143 +module top; +default clocking @(posedge clk_i); endclocking +endmodule +---- +module top; + default clocking @(posedge clk_i); + endclocking +endmodule +==== +# `default clocking cb;` selects an existing block: no event, no body +# IEEE 1800-2017 14.12 +module m; + clocking cb @(posedge clk); + input a; + endclocking + default clocking cb; +endmodule +---- +module m; + clocking cb @(posedge clk); + input a; + endclocking + default clocking cb; +endmodule +==== +# a virtual interface type in a typedef +# corpus/ibex/dv/uvm/icache/dv/env/ibex_icache_env_pkg.sv:28 +package p; + typedef virtual push_pull_if#(.DeviceDataWidth(194)) scrambling_key_vif; + typedef virtual pins_if #(NUM_MAX_INTERRUPTS) intr_vif; + typedef virtual interface bus_if plain_vif; +endpackage +---- +package p; + typedef virtual push_pull_if #(.DeviceDataWidth(194)) scrambling_key_vif; + typedef virtual pins_if #(NUM_MAX_INTERRUPTS) intr_vif; + typedef virtual interface bus_if plain_vif; +endpackage +==== +# a virtual interface type as a function argument +# corpus/common_cells/test/stream_test.sv:31 +package p; + class stream_driver; + virtual STREAM_DV stream; + function new (virtual STREAM_DV dv_if, int unsigned n); + this.stream = dv_if; + endfunction + endclass +endpackage +---- +package p; + class stream_driver; + virtual STREAM_DV stream; + function new(virtual STREAM_DV dv_if, int unsigned n); + this.stream = dv_if; + endfunction + endclass +endpackage +==== +# comments everywhere: before the interface, in the port list, between +# modport entries, and after `endinterface` +// what this interface is for +interface commented_if ( + // the clock + input clk, + input rst_n // and the reset +); + // a modport + modport in_mp ( + // only the clock + input clk + ); + modport out_mp (input rst_n); // and this one +endinterface // done +---- +// what this interface is for +interface commented_if ( + // the clock + input clk, + input rst_n // and the reset +); + // a modport + modport in_mp ( + // only the clock + input clk + ); + modport out_mp (input rst_n); // and this one +endinterface // done +==== +# a `// verilog_format: off` fence inside an interface body is honoured, +# exactly as it is inside a module body +interface fenced_if; + logic a; + // verilog_format: off + logic b ; + logic c ; + // verilog_format: on + logic d; +endinterface +---- +interface fenced_if; + logic a; + // verilog_format: off + logic b ; + logic c ; + // verilog_format: on + logic d; +endinterface +==== +# an interface is instantiated and connected like a module +module tb; + clk_rst_if #(.IfName("main")) clk_rst_if_inst (.clk(clk), .rst_n(rst_n)); + dut u_dut (.bus(bus_if_inst.master)); +endmodule +---- +module tb; + clk_rst_if #(.IfName("main")) clk_rst_if_inst (.clk(clk), .rst_n(rst_n)); + dut u_dut (.bus(bus_if_inst.master)); +endmodule diff --git a/crates/vlog_linter/src/rules/module_filename.rs b/crates/vlog_linter/src/rules/module_filename.rs index 7c79140..9c8d867 100644 --- a/crates/vlog_linter/src/rules/module_filename.rs +++ b/crates/vlog_linter/src/rules/module_filename.rs @@ -26,8 +26,11 @@ impl Rule for ModuleFilename { guide makes the file name match the module it declares. The rule only \ speaks when the file declares exactly one module: a package of small \ modules, or a file with none, is a deliberate choice it has nothing to \ - say about. It is silent for input with no file name (stdin), and \ - offers no fix — renaming a file is not the linter's business." + say about. An `interface` counts as a module here: a one-interface \ + file is found by its interface name the same way, and the convention \ + in real RTL is the same. It is silent for input with no file name \ + (stdin), and offers no fix — renaming a file is not the linter's \ + business." } fn check(&self, ctx: &LintContext) -> Vec { @@ -44,7 +47,7 @@ impl Rule for ModuleFilename { let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or(stem); vec![Violation::new( NAME, - format!("module `{}` does not match file name `{file_name}`", module.name), + format!("{} `{}` does not match file name `{file_name}`", module.kw, module.name), module.name_span, )] } @@ -74,6 +77,14 @@ mod tests { assert!(violations("module foo;\nendmodule\n", Some("rtl/foo.v")).is_empty()); } + #[test] + fn an_interface_is_held_to_the_same_rule() { + let found = violations("interface bus_if;\nendinterface\n", Some("rtl/bar.sv")); + assert_eq!(found.len(), 1); + assert!(found[0].message.starts_with("interface `bus_if`"), "{}", found[0].message); + assert!(violations("interface bus_if;\nendinterface\n", Some("rtl/bus_if.sv")).is_empty()); + } + #[test] fn silent_without_a_file_name() { assert!(violations("module foo;\nendmodule\n", None).is_empty()); diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index 49c81ea..96ae677 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -232,6 +232,12 @@ pub enum ItemKind { Task(TaskDecl), /// A `class` / `virtual class` declaration and its body. Class(ClassDecl), + /// `modport a (input x, output y), b (...);` (IEEE 1800 §25.5). One + /// declaration may name several modports, so the payload is a list. + Modport(Vec), + /// `clocking cb @(posedge clk); ... endclocking` and the `default` + /// spellings of it (IEEE 1800 §14). + Clocking(ClockingDecl), /// A block vfmt deliberately does not model, kept byte-for-byte: /// `constraint c { ... }`, `covergroup ... endgroup`, a concurrent /// assertion (`assert property ( ... );`) and a `property`/`sequence` @@ -248,6 +254,12 @@ pub enum ItemKind { Error(RawText), } +/// A `module` / `macromodule` / `interface` declaration. +/// +/// An interface header is the module header's grammar (IEEE 1800 §25.3) and an +/// interface body is the module body's item list plus `modport` and `clocking`, +/// so the two share one node; `kw` says which was written and +/// [`Module::end_kw`] the closing keyword that goes with it. #[derive(Debug)] pub struct Module { pub kw: String, @@ -285,6 +297,17 @@ pub struct Module { pub end_label_span: Option, } +impl Module { + /// The keyword that closes this declaration: `endmodule` or `endinterface`. + pub fn end_kw(&self) -> &'static str { + if self.kw == "interface" { + "endinterface" + } else { + "endmodule" + } + } +} + /// One `import` statement in a module header, with the comments written /// around it. A header import is not an [`Item`], so it needs its own place /// to keep them. @@ -363,6 +386,19 @@ pub struct ParamPort { /// `name` may be empty for implicit types (`input [7:0] x`). #[derive(Debug, Clone, Default)] pub struct DataType { + /// The `virtual` / `virtual interface` prefix of a virtual interface type + /// reference, as written (IEEE 1800 §25.9): `virtual clk_rst_if`, + /// `virtual interface bus_if`. Legal in every type position — a typedef's + /// base type, a task/function argument, a variable declaration. + /// + /// A *declaration* keeps it in [`DataDecl::qualifiers`] instead, where the + /// rest of the member qualifiers already live; this field carries the + /// positions that have no qualifier list of their own. + /// + /// A one-byte enum rather than the text, for the same reason `params` is + /// boxed: every `Expr` carries a `DataType` through [`ExprKind::Type`], + /// so a rare field must not widen the common case. + pub virt: Option, pub name: String, /// The `#( ... )` of a parameterized type reference, verbatim: /// `uvm_analysis_port #(bit [31:0]) port;`. Its arguments are types as @@ -379,13 +415,35 @@ pub struct DataType { impl DataType { pub fn is_implicit(&self) -> bool { - self.name.is_empty() + self.virt.is_none() + && self.name.is_empty() && self.params.is_none() && self.signing.is_none() && self.packed.is_empty() } } +/// How a virtual interface type reference is spelled. The `interface` keyword +/// is optional (IEEE 1800 §25.9) and both spellings occur, so which one was +/// written is recorded and printed back. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VirtualKw { + /// `virtual bus_if h;` + Bare, + /// `virtual interface bus_if h;` + Interface, +} + +impl VirtualKw { + /// The prefix as it is written, `interface` keyword included. + pub fn text(self) -> &'static str { + match self { + VirtualKw::Bare => "virtual", + VirtualKw::Interface => "virtual interface", + } + } +} + /// A dimension: `[expr]`, `[a:b]`, `[]`, or `[*]`. #[derive(Debug, Clone)] pub struct Dim { @@ -808,6 +866,80 @@ pub struct ClassExtends { pub span: TextRange, } +/// One modport of a `modport a (...), b (...);` declaration (IEEE 1800 §25.5). +#[derive(Debug)] +pub struct ModportDecl { + /// Comments written around this modport within the declaration. + pub meta: Meta, + pub name: String, + /// Byte range of `name`. + pub name_span: TextRange, + pub ports: Vec, + /// Comments written after the last port and before the `)`. + pub dangling: Vec, + /// True when a `,` followed this modport in the source. + pub comma: bool, + /// Code extent from the name through the closing `)`. + pub span: TextRange, +} + +/// One direction group of a modport's port list: the keyword plus every name +/// it governs. `input a, b, output c` is two groups, which is how the source's +/// grouping survives a reformat. +#[derive(Debug)] +pub struct ModportPort { + pub meta: Meta, + /// `input`, `output`, `inout`, `ref`, `import`, `export` or `clocking`. + pub kw: String, + /// The names this keyword governs. A `clocking` group names exactly one. + pub names: Vec, + /// True when a `,` followed the last name of this group in the source. + pub comma: bool, + /// Code extent from the keyword through its last name. + pub span: TextRange, +} + +/// `clocking cb @(posedge clk); ... endclocking` (IEEE 1800 §14.3), including +/// the `default clocking` spellings and the body-less +/// `default clocking cb;` clocking assignment (§14.12). +#[derive(Debug)] +pub struct ClockingDecl { + /// True when the declaration was written `default clocking ...`. + pub is_default: bool, + /// `None` for the anonymous `default clocking @(posedge clk);` form. + pub name: Option, + /// The `@( ... )` clocking event. `None` for `default clocking cb;`, which + /// selects an existing clocking block and has no body. + pub event: Option, + /// Empty when there is no body (`default clocking cb;`). + pub items: Vec, + pub dangling: Vec, + /// True when the declaration wrote an `endclocking`. + pub has_end: bool, + /// Label after `endclocking :`. + pub end_label: Option, + /// Byte range of `end_label`. + pub end_label_span: Option, +} + +/// One item of a clocking block's body. +#[derive(Debug)] +pub struct ClockingItem { + pub meta: Meta, + pub kind: ClockingItemKind, + /// Code extent of the item, its `;` excluded. + pub span: TextRange, +} + +#[derive(Debug)] +pub enum ClockingItemKind { + /// `default input #1step output #0;` — at least one half is written. + Default { input: Option, output: Option }, + /// `input #2 a, b;`, `output negedge c;`, `inout d;`. `skew` is the delay + /// or edge as written (`#2`, `negedge`), or `None` when omitted. + Signals { dir: String, skew: Option, names: Vec }, +} + #[derive(Debug)] pub struct FunctionDecl { /// `Some` when this is a DPI import — `import "DPI-C" function ...;` — diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index 140de0b..00646c1 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -99,12 +99,14 @@ const ELAB_TASKS: &[&str] = &["$fatal", "$error", "$warning", "$info"]; const SYNC_CLOSERS: &[&str] = &[ "end", "endmodule", + "endinterface", "endpackage", "endgenerate", "endfunction", "endtask", "endcase", "endclass", + "endclocking", "join", "join_any", "join_none", @@ -115,7 +117,7 @@ const SYNC_CLOSERS: &[&str] = &[ /// `class` is deliberately absent: unlike a module or a package it nests /// (inside a package, and inside another class), so stopping recovery before /// one would end the enclosing body at the wrong place. -const SYNC_OPENERS: &[&str] = &["module", "macromodule", "package"]; +const SYNC_OPENERS: &[&str] = &["module", "macromodule", "interface", "package"]; /// Keywords that may stand *before* the one that names a class member: /// `virtual function`, `pure virtual task`, `extern function`, @@ -1074,7 +1076,19 @@ impl<'a> Parser<'a> { fn parse_keyword_item(&mut self) -> PResult { let kw = self.cur().text.clone(); match kw.as_str() { - "module" | "macromodule" => self.parse_module().map(ItemKind::Module), + "module" | "macromodule" => self.parse_module("endmodule").map(ItemKind::Module), + // `interface class` is a class, not an interface (IEEE 1800 + // §8.26): a different construct that vfmt does not model, so it + // falls through to the unsupported-construct error below. + "interface" if !self.nth(1).is_kw("class") => { + self.parse_module("endinterface").map(ItemKind::Module) + } + "modport" => self.parse_modport().map(ItemKind::Modport), + "clocking" => self.parse_clocking(false).map(ItemKind::Clocking), + "default" if self.nth(1).is_kw("clocking") => { + self.bump(); + self.parse_clocking(true).map(ItemKind::Clocking) + } "package" => self.parse_package(), "import" => { // A string right after `import` is a DPI linkage spec, not a @@ -1689,7 +1703,10 @@ impl<'a> Parser<'a> { // Module // ------------------------------------------------------------------ - fn parse_module(&mut self) -> PResult { + /// A `module` / `macromodule` / `interface` declaration. The three share + /// one header grammar (IEEE 1800 §23.2.1, §25.3) and one body item list — + /// only the closing keyword differs, so `end_kw` is the whole difference. + fn parse_module(&mut self, end_kw: &str) -> PResult { let kw = self.bump().text; let Name { text: name, span: name_span } = self.expect_name()?; let mut imports = Vec::new(); @@ -1709,11 +1726,11 @@ impl<'a> Parser<'a> { let (ports, port_dangling, port_directives) = self.parse_port_list()?; self.expect_sym(";")?; let mut items = Vec::new(); - while !self.at_body_end("endmodule") { + while !self.at_body_end(end_kw) { items.push(self.item_or_recover()?); } let dangling = self.take_dangling(); - self.expect_closer("endmodule")?; + self.expect_closer(end_kw)?; let (end_label, end_label_span) = split_label(self.parse_label()?); Ok(Module { kw, @@ -1735,6 +1752,178 @@ impl<'a> Parser<'a> { }) } + /// `modport a (input x, output y), b (...);` (IEEE 1800 §25.5). + fn parse_modport(&mut self) -> PResult> { + self.expect_kw("modport")?; + let mut out = Vec::new(); + loop { + let start = self.here(); + let mut meta = self.take_meta(); + let Name { text: name, span: name_span } = self.expect_name()?; + self.expect_sym("(")?; + let mut ports = Vec::new(); + while !self.cur().is_sym(")") && !self.at_eof() { + ports.push(self.parse_modport_port()?); + if !ports.last().is_some_and(|p: &ModportPort| p.comma) { + break; + } + } + let dangling = self.take_dangling(); + self.expect_sym(")")?; + let span = self.span_from(start); + if let Some(last) = ports.last_mut() { + if last.meta.trailing.is_none() { + last.meta.trailing = self.take_trailing(); + } + } + self.take_before_sep(&mut meta, ","); + let comma = self.eat_sym(","); + meta.trailing = self.take_trailing(); + out.push(ModportDecl { meta, name, name_span, ports, dangling, comma, span }); + if !comma { + break; + } + } + self.expect_sym(";")?; + Ok(out) + } + + /// One direction group of a modport's port list. `input a, b, output c` is + /// two groups: the comma keeps the group open only while a plain name + /// follows it — a direction keyword starts the next group. + fn parse_modport_port(&mut self) -> PResult { + const MODPORT_KEYWORDS: &[&str] = + &["input", "output", "inout", "ref", "import", "export", "clocking"]; + let start = self.here(); + let mut meta = self.take_meta(); + let t = self.cur(); + if t.kind != TokenKind::Keyword || !MODPORT_KEYWORDS.contains(&t.text.as_str()) { + return self.error("expected a modport port direction"); + } + let kw = self.bump().text; + let mut names = vec![self.expect_name()?]; + let mut span = self.span_from(start); + let mut comma = false; + loop { + self.take_before_sep(&mut meta, ","); + if !self.eat_sym(",") { + break; + } + if self.cur().kind != TokenKind::Ident { + // The comma separates this group from the next one. + comma = true; + break; + } + names.push(self.expect_name()?); + span = self.span_from(start); + } + if meta.trailing.is_none() { + meta.trailing = self.take_trailing(); + } + Ok(ModportPort { meta, kw, names, comma, span }) + } + + /// `clocking cb @(posedge clk); ... endclocking` (IEEE 1800 §14.3). The + /// `default` keyword, when written, has already been consumed. + fn parse_clocking(&mut self, is_default: bool) -> PResult { + self.expect_kw("clocking")?; + let name = + if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None }; + // `default clocking cb;` selects an existing block and has no body. + let event = if self.eat_sym("@") { Some(self.parse_sens_list()?) } else { None }; + self.expect_sym(";")?; + if event.is_none() { + return Ok(ClockingDecl { + is_default, + name, + event, + items: Vec::new(), + dangling: Vec::new(), + has_end: false, + end_label: None, + end_label_span: None, + }); + } + let mut items = Vec::new(); + while !self.at_body_end("endclocking") { + items.push(self.parse_clocking_item()?); + } + let dangling = self.take_dangling(); + self.expect_closer("endclocking")?; + let (end_label, end_label_span) = split_label(self.parse_label()?); + Ok(ClockingDecl { + is_default, + name, + event, + items, + dangling, + has_end: true, + end_label, + end_label_span, + }) + } + + /// One item of a clocking block's body: `default input #1step output #0;` + /// or a direction group (`input #2 a, b;`). + fn parse_clocking_item(&mut self) -> PResult { + let start = self.here(); + let mut meta = self.take_meta(); + let kind = if self.eat_kw("default") { + let input = if self.eat_kw("input") { Some(self.parse_clocking_skew()?) } else { None }; + let output = + if self.eat_kw("output") { Some(self.parse_clocking_skew()?) } else { None }; + if input.is_none() && output.is_none() { + return self.error("expected `input` or `output` after `default`"); + } + ClockingItemKind::Default { input, output } + } else { + let t = self.cur(); + if !(t.is_kw("input") || t.is_kw("output") || t.is_kw("inout")) { + return self.error("expected a clocking item"); + } + let dir = self.bump().text; + let skew = + if self.at_clocking_skew() { Some(self.parse_clocking_skew()?) } else { None }; + let mut names = vec![self.expect_name()?]; + while self.eat_sym(",") { + names.push(self.expect_name()?); + } + ClockingItemKind::Signals { dir, skew, names } + }; + let span = self.span_from(start); + self.expect_sym(";")?; + if meta.trailing.is_none() { + meta.trailing = self.take_trailing(); + } + Ok(ClockingItem { meta, kind, span }) + } + + /// True when the cursor is on a clocking skew rather than on the first + /// signal name: `#2`, `#1step`, `posedge`, `negedge`, `edge`. + fn at_clocking_skew(&self) -> bool { + let t = self.cur(); + t.is_sym("#") || t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") + } + + /// A clocking skew, as written: `#2`, `#1step`, `negedge`. Kept as text — + /// it is a delay or an edge, never something vfmt re-lays out — so the + /// printer writes back exactly what the source said. The `#(min:typ:max)` + /// spelling is not supported; see the feature README's Assumptions. + fn parse_clocking_skew(&mut self) -> PResult { + if self.eat_sym("#") { + let t = self.cur(); + if !matches!(t.kind, TokenKind::Number | TokenKind::Ident) { + return self.error("expected a clocking skew delay"); + } + return Ok(format!("#{}", self.bump().text)); + } + let t = self.cur(); + if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") { + return Ok(self.bump().text); + } + self.error("expected a clocking skew") + } + /// A `#( parameter ... )` port list, shared by module and class headers. /// `ports` is `None` when no `#(` was written at the cursor at all. fn parse_param_port_list(&mut self) -> PResult { @@ -1931,6 +2120,16 @@ impl<'a> Parser<'a> { /// Parse a possibly-implicit data type. Stops before the declarator name. fn parse_opt_data_type(&mut self) -> PResult { let mut ty = DataType::default(); + // `virtual [interface] ` — a virtual interface type reference + // (IEEE 1800 §25.9). It stands wherever a type does: a typedef's base + // type, a task/function argument, a variable. (A *declaration* reaches + // this function with the `virtual` already taken into + // `DataDecl::qualifiers`, so this only fires for the other positions.) + if self.cur().is_kw("virtual") { + self.bump(); + ty.virt = + Some(if self.eat_kw("interface") { VirtualKw::Interface } else { VirtualKw::Bare }); + } let t = self.cur(); if t.kind == TokenKind::Keyword && TYPE_KEYWORDS.contains(&t.text.as_str()) { ty.name = self.bump().text; @@ -5328,4 +5527,116 @@ mod tests { assert!(matches!(&task.stmts[0].kind, StmtKind::MacroStmt(_))); assert!(matches!(&task.stmts[1].kind, StmtKind::ExprStmt(_))); } + + #[test] + fn an_interface_is_a_module_with_its_own_closing_keyword() { + let f = parse_ok("interface bus_if (input clk);\n logic a;\nendinterface : bus_if\n"); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected an interface") }; + assert_eq!(m.kw, "interface"); + assert_eq!(m.end_kw(), "endinterface"); + assert_eq!(m.end_label.as_deref(), Some("bus_if")); + assert!(matches!(&m.ports, PortList::Ansi(p) if p.len() == 1)); + } + + #[test] + fn an_interface_header_takes_the_module_header_imports() { + // corpus/ibex/dv/uvm/core_ibex/fcov/core_ibex_pmp_fcov_if.sv:7 + let f = parse_ok( + "interface fcov_if import ibex_pkg::*; #(parameter int W = 1) (input clk);\nendinterface\n", + ); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected an interface") }; + assert_eq!(m.imports.len(), 1); + assert_eq!(m.imports[0].paths[0].text(), "ibex_pkg::*"); + assert_eq!(m.param_ports.as_ref().map(Vec::len), Some(1)); + } + + #[test] + fn interface_class_is_not_an_interface() { + // IEEE 1800-2017 8.26: a different construct, deliberately unsupported. + assert!(parse_err("interface class ic;\nendclass\n").contains("`interface`")); + } + + #[test] + fn a_modport_keeps_the_grouping_the_source_wrote() { + // corpus/common_cells/src/stream_intf.sv:29 + let f = parse_ok( + "interface i;\n modport In (output ready, input valid, data);\nendinterface\n", + ); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected an interface") }; + let ItemKind::Modport(decls) = &m.items[0].kind else { panic!("expected a modport") }; + assert_eq!(decls.len(), 1); + assert_eq!(decls[0].name, "In"); + assert_eq!(decls[0].ports.len(), 2); + assert_eq!(decls[0].ports[0].kw, "output"); + assert_eq!(decls[0].ports[1].kw, "input"); + let names: Vec<&str> = decls[0].ports[1].names.iter().map(|n| n.text.as_str()).collect(); + assert_eq!(names, ["valid", "data"]); + } + + #[test] + fn one_modport_declaration_may_name_several_modports() { + let f = parse_ok("interface i;\n modport a (input x), b (output x);\nendinterface\n"); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected an interface") }; + let ItemKind::Modport(decls) = &m.items[0].kind else { panic!("expected a modport") }; + assert_eq!(decls.len(), 2); + assert_eq!(decls[0].name, "a"); + assert_eq!(decls[1].name, "b"); + } + + #[test] + fn a_clocking_block_parses_its_items() { + // corpus/common_cells/test/stream_register_tb.sv:75 + let f = parse_ok( + "module m;\n clocking cb @(posedge clk);\n default input #2 output #4;\n input a, b;\n output negedge c;\n endclocking\nendmodule\n", + ); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + let ItemKind::Clocking(c) = &m.items[0].kind else { panic!("expected a clocking block") }; + assert!(!c.is_default); + assert_eq!(c.name.as_ref().map(|n| n.text.as_str()), Some("cb")); + assert_eq!(c.items.len(), 3); + assert!(matches!( + &c.items[0].kind, + ClockingItemKind::Default { input: Some(i), output: Some(o) } if i == "#2" && o == "#4" + )); + assert!(matches!( + &c.items[1].kind, + ClockingItemKind::Signals { dir, skew: None, names } if dir == "input" && names.len() == 2 + )); + assert!(matches!( + &c.items[2].kind, + ClockingItemKind::Signals { dir, skew: Some(s), .. } if dir == "output" && s == "negedge" + )); + } + + #[test] + fn a_default_clocking_may_be_anonymous_or_body_less() { + // corpus/ibex/dv/formal/check/top.sv:143, and IEEE 1800-2017 14.12. + let f = parse_ok("module m;\n default clocking @(posedge clk); endclocking\n default clocking cb;\nendmodule\n"); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + let ItemKind::Clocking(anon) = &m.items[0].kind else { + panic!("expected a clocking block") + }; + assert!(anon.is_default && anon.name.is_none() && anon.event.is_some() && anon.has_end); + let ItemKind::Clocking(sel) = &m.items[1].kind else { panic!("expected a clocking block") }; + assert!(sel.is_default && sel.event.is_none() && !sel.has_end); + } + + #[test] + fn a_virtual_interface_type_stands_in_every_type_position() { + // corpus/ibex/dv/uvm/icache/dv/env/ibex_icache_env_pkg.sv:28 (typedef) + // and corpus/common_cells/test/stream_test.sv:31 (argument). + let f = parse_ok( + "package p;\n typedef virtual push_pull_if #(.W(4)) vif_t;\n function void f(virtual interface bus_if h);\n endfunction\nendpackage\n", + ); + let ItemKind::Package { items, .. } = &f.items[0].kind else { + panic!("expected a package") + }; + let ItemKind::Typedef(t) = &items[0].kind else { panic!("expected a typedef") }; + let TypedefKind::Alias(ty) = &t.kind else { panic!("expected a type alias") }; + assert_eq!(ty.virt, Some(VirtualKw::Bare)); + assert_eq!(ty.name, "push_pull_if"); + let ItemKind::Function(fun) = &items[1].kind else { panic!("expected a function") }; + assert_eq!(fun.args[0].ty.virt, Some(VirtualKw::Interface)); + assert_eq!(fun.args[0].ty.name, "bus_if"); + } } diff --git a/crates/vlog_parser/src/token.rs b/crates/vlog_parser/src/token.rs index 8faf7aa..efa709f 100644 --- a/crates/vlog_parser/src/token.rs +++ b/crates/vlog_parser/src/token.rs @@ -109,6 +109,8 @@ pub fn is_keyword(s: &str) -> bool { | "program" | "endprogram" | "modport" + | "clocking" + | "endclocking" | "input" | "output" | "inout" diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index 369649e..f2ba4ed 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -567,6 +567,28 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { check_item(src, item, here); } } + ItemKind::Modport(decls) => { + for d in decls { + assert_inside(src, "modport", d.span, here); + check_name(src, "modport name", &d.name, d.name_span, d.span); + for p in &d.ports { + assert_inside(src, "modport port", p.span, d.span); + check_names(src, "modport port name", &p.names, p.span); + } + } + } + ItemKind::Clocking(c) => { + if let Some(n) = &c.name { + check_name(src, "clocking name", &n.text, n.span, here); + } + check_opt_name(src, "endclocking label", c.end_label.as_ref(), c.end_label_span, here); + for item in &c.items { + assert_inside(src, "clocking item", item.span, here); + if let ClockingItemKind::Signals { names, .. } = &item.kind { + check_names(src, "clocking signal", names, item.span); + } + } + } // A `constraint`/`covergroup` block: one verbatim leaf whose span is // the item's own, checked above. ItemKind::Verbatim(_) => {} diff --git a/crates/vlog_semantic/src/bind.rs b/crates/vlog_semantic/src/bind.rs index e935243..950130c 100644 --- a/crates/vlog_semantic/src/bind.rs +++ b/crates/vlog_semantic/src/bind.rs @@ -298,7 +298,15 @@ impl<'a> Binder<'a> { // (an `import` alongside it does that). Resolving either one is a // vlog_semantic decision, not the parser's — see // `docs/features/dpi-export/README.md` Handshakes. - ItemKind::Export(_) + // `modport` and `clocking` are leaves here for now: both name + // signals that are declared in the enclosing interface, so + // resolving them is a reference-binding question rather than a + // declaration one, and whether a modport or a clocking block + // should itself be a symbol is a vlog_semantic decision — see + // `docs/features/interfaces/README.md` Handshakes. + ItemKind::Modport(_) + | ItemKind::Clocking(_) + | ItemKind::Export(_) | ItemKind::Directive(_) | ItemKind::MacroItem(_) | ItemKind::Timeunit(_) diff --git a/docs/features/interfaces/README.md b/docs/features/interfaces/README.md new file mode 100644 index 0000000..7fba413 --- /dev/null +++ b/docs/features/interfaces/README.md @@ -0,0 +1,220 @@ +# interfaces + +## Goal + +Make `interface … endinterface` and the two constructs that only live +inside one — `modport` and `clocking` — first-class, structurally parsed +and canonically laid out, and make a `virtual ` type reference +legal in every type position rather than only as a class property. An +interface header is the module header's grammar (IEEE 1800-2017 §25.3 +vs §23.2.1) and an interface body is the module body's item list plus +those two extra items, so the whole feature is mostly a matter of +*sharing* the module machinery rather than writing a second copy of it. + +At the start of this round `interface` was the corpus's top blocker at +31 of 820 files. + +## Assumptions + +- **An interface is a `Module` node with a different keyword.** There is + no `ItemKind::Interface`: `ItemKind::Module` carries `kw` (`module` / + `macromodule` / `interface`) and `Module::end_kw()` derives + `endmodule` / `endinterface` from it. Everything that already walks a + module — the formatter, `fence.rs`, `range.rs`, `vlog_linter::visit`, + `vlog_semantic::bind` — therefore handles interfaces unchanged, and + the parser's header and body code is literally the same code. The cost + is that a consumer that wants to tell the two apart must read `kw`; + that is the same thing it already had to do for `macromodule`. +- **`interface class` is not an interface** (IEEE 1800-2017 §8.26). It + is a class-like construct with a different body grammar and is + deliberately left as an "unsupported construct" parse error. No corpus + file uses it (0 of 820). +- **`program … endprogram` is out of scope** for this round even though + it shares the same header/body grammar and would be a one-line + addition here. No corpus file uses it (0 of 820), so it buys nothing + measurable; see Handshakes. +- A modport port is a **direction keyword plus the names it governs**. + The source's grouping is preserved (`input valid, data` is one group, + not two ports), because regrouping it would be a token-order change + for no gain. The explicit modport port (`.name(expr)`) and the modport + method *prototype* (`import task drive(int x);` with a signature) are + not supported — a bare `import drive_task, check_task;` is. Neither + prototype form occurs in the corpus. +- A clocking skew is kept as **text as written** (`#2`, `#1step`, + `negedge`), not as an expression: it is a delay or an edge and vfmt + never re-lays-out either. The `#(min:typ:max)` skew spelling is not + supported (0 corpus uses). +- A clocking item's optional `= expression` (`input data = top.dut.d;`, + IEEE 1800-2017 §14.4) is not supported. 0 corpus uses. +- `virtual` / `virtual interface` in a **type position** is recorded on + `DataType::virt` as a one-byte `VirtualKw`, not as a `String`: every + `Expr` carries a `DataType` through `ExprKind::Type`, and a `String` + there pushes `DimKind` past clippy's `large_enum_variant` threshold + (measured: `DimKind::Range` 192 → 208 bytes). A *declaration* keeps + the prefix where it always did, in `DataDecl::qualifiers`, so the + class-property path is untouched. +- A `// verilog_format: off` fence inside a **modport or clocking body** + is not a fence scope, exactly as a fence inside a class body or a + statement body is not (`fence.rs::scan_nested` has no arm for either). + A fence in an *interface* body works, because that is a module body. + +## Handshakes + +Consumed: + +- `Parser::parse_module`, `parse_param_port_list`, `parse_port_list`, + `parse_sens_list`, and the whole `Fmt::module`/`module_head` layout — + all reused verbatim for interfaces. +- `Fmt::delimited_dangling` for a modport's port list, so it breaks and + aligns exactly like a header port list. + +Promised / changed for others: + +- **`ast::Module` now also models an interface.** `Module::kw` may be + `"interface"`; `Module::end_kw()` is the closing keyword. Any consumer + that assumed `ItemKind::Module` means `module` must read `kw`. +- **`ast::DataType` has a new field, `virt: Option`.** + `DataType::is_implicit()` now returns `false` when it is set. + `DataType::default()` is unchanged, so constructing one still + compiles. +- **Two new `ItemKind` variants**, `Modport(Vec)` and + `Clocking(ClockingDecl)`. Minimal arms were added where the match had + to stay exhaustive: `vlog_semantic::bind::bind_item` (both are opaque + leaves) and `vlog_parser/tests/spans.rs`. `vlog_linter::visit`, + `fence.rs`, `range.rs` and `vfmt_server` all have catch-all arms and + needed no change. +- **`clocking` and `endclocking` are now reserved words** (`token.rs`). + A design that used either as an identifier would change meaning; no + corpus file does, and the passing set was verified to be a strict + superset. +- **`module-filename` now applies to interfaces** and its message names + the construct (`interface \`bus_if\` does not match file name …`) + instead of hard-coding "module". This is the intended behaviour: a + one-interface file is looked up by its interface name exactly the way + a one-module file is. + +Requests to other owners (not done here): + +- **`vlog_semantic`**: an interface is currently declared as + `SymbolKind::Module`, which is what makes go-to-definition on an + interface *instantiation* work today for free (an instantiation + resolves its module name against the same index). Whether interfaces + deserve their own `SymbolKind::Interface` — and with it + `vfmt_server`'s `LspKind::INTERFACE` in `symbols.rs` instead of + `LspKind::CLASS` — is the semantic owner's call; it is a mechanical + change across `model.rs`, `symbols.rs`, `hover.rs` and `workspace.rs`, + which is why it is not made here. Likewise, a `modport` name and a + `clocking` block name are plausible symbols, and the signal names + inside both are *references* to nets declared in the enclosing + interface; neither is bound today. +- **expressions owner**: `corpus/ibex/dv/formal/check/top.sv:432` now + parses past its interface/`default clocking` blockers and fails on + `(data_we_o -> …)`, the implication operator in an ordinary + expression. `corpus/ibex/vendor/lowrisc_ip/dv/sv/common_ifs/pins_if.sv:97` + likewise fails on the drive-strength spec `assign (pull0, pull1) x = …`. + Both are classified `expressions` by `scripts/score.sh`. +- **whoever owns the `other` bucket**: + `corpus/ibex/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils_pkg.sv:104` + now fails on `function automatic int max(const ref int int_q[$]);` — + the `const` qualifier on a task/function argument, which + `Parser::parse_tf_ports` does not accept. +- **`program … endprogram`**: whoever picks it up gets it for two lines + in `parse_keyword_item` plus one in `Module::end_kw`, since the + grammar is the one already implemented here. + +## Status / TODO + +- [x] `interface [import pkg::*;] [#(params)] [(ports)]; … endinterface + [: label]`, sharing the module header and body parse +- [x] `import pkg::*;` between the name and the `#(`/`(` — verified it + already worked for modules too (`Module::imports`), so nothing new + was needed there; a module case was added to the case table +- [x] ANSI ports with no type (`inout clk`, `input rst_n`), string + parameters, multi-parameter headers +- [x] `endinterface : label` +- [x] `modport a (…), b (…);` — `input`/`output`/`inout`/`ref`/`import`/ + `export`/`clocking` groups, several modports per declaration +- [x] `clocking name @(event); … endclocking [: label]`, `default + clocking`, anonymous `default clocking @(…)`, body-less `default + clocking cb;` +- [x] clocking items: `default input #s output #s;`, `input [skew] a, b;`, + `output [skew] c;`, `inout d;` +- [x] `virtual [interface] [#(…)]` in a typedef base type and in a + task/function argument (the declaration position already worked) +- [x] `module-filename` generalized to interfaces, with a test +- [x] 22 formatter cases in `crates/vlog_formatter/tests/cases/interfaces.cases` + plus 8 parser unit tests, covering every corpus shape cited above, + comments in every position, a `verilog_format: off` fence and the + line-length boundary +- [ ] Not done, and not planned here: `interface class`, `program`, + explicit modport ports, modport method prototypes, clocking + `= expr` items, `#(min:typ:max)` skews (see Assumptions) + +## Work log + +### 2026-08-20 — dev + +Baseline (`cargo build --release && scripts/score.sh`, at `d488f0a`): + +``` +{"passing":712,"total":820,"pct":86.8,"failures_by_category":{"interface":31,"dv-statements":26,"expressions":19,"directive-split":14,"types-decls":11,"invalid-or-fragment":3,"lex-macro-number":2,"not-verilog":1,"other":1}} +``` + +After: + +``` +{"passing":740,"total":820,"pct":90.2,"failures_by_category":{"dv-statements":26,"expressions":21,"directive-split":14,"types-decls":11,"invalid-or-fragment":3,"lex-macro-number":2,"other":2,"not-verilog":1}} +``` + ++28 files, 0 lost — the passing set was verified to be a strict superset +by diffing the before/after `.score-results.tsv` by path. The +`interface` bucket is empty; the 3 files that did not reach `pass` +advanced to blockers owned by other categories (listed in Handshakes). +All 28 newly-formatting files were additionally round-tripped twice to +confirm idempotency on the real sources. + +Key decisions: + +1. **Reuse `Module` instead of adding an `Interface` node.** The header + grammar and the body item list are the same grammar; the only + difference is the closing keyword. `parse_module` took an `end_kw` + parameter and `parse_keyword_item` gained one arm. This is what made + the header `import` (the interesting bit of §25.3) work with no new + code at all: `Module::imports` already existed for + `module m import pkg::*; (…)`, so both §23.2.1 and §25.3 are the same + code path. A case for the module spelling was added to lock that in. +2. **`modport` port lists reuse `delimited_dangling`**, so they collapse + onto one line when they fit and break one direction group per line + when they do not — the same rule every other bracketed list in vfmt + follows. `interface STREAM_DV`'s three modports collapse; a 100-column + one breaks. +3. **Clocking blocks are parsed structurally**, not kept verbatim: the + item grammar is small and closed (`default input/output `, and + direction groups with an optional skew), so there was no reason to + hand it to the verbatim path. One item per line, indented, closing + keyword aligned with the opener. +4. **`virtual` moved into `parse_opt_data_type`.** That one place is + reached by the typedef base type, task/function arguments, struct + members, ports and parameter ports, so a single change generalized it + to every type position. The declaration path (`parse_data_decl`) is + untouched: it consumes `virtual` into `qualifiers` before ever + reaching `parse_opt_data_type`, so the class-property behaviour and + its tests are bit-identical. +5. **`DataType::virt` is a one-byte enum, not a `String`.** The first + cut used `Option` and made clippy's `large_enum_variant` fire + on `DimKind` (`Range` grew 192 → 208 bytes, past the 200-byte + threshold) — every `Expr` carries a `DataType`. `Option>` + was still 208. `VirtualKw` (1 byte, with a `text()` accessor) fits in + the existing padding and is honest: the prefix is one of exactly two + spellings. + +Deviations from the brief: none, except that `default disable iff (…)` +was looked for in the corpus (`grep -rn 'default disable' corpus`) and +does not occur in any `.sv`/`.v` file, so it was not implemented. + +`verify.rs` was not touched: nothing here widens the safety net's +forgiveness, so no masked-corruption attack tests are owed. + +## QA log + +## Review