Add classes: SystemVerilog class support, corpus 58.0% -> 70.5%

The top corpus blocker (142 extends-blocked UVM/DV files) falls.
Structural support: class/virtual class with parameter ports,
extends (named/ordered params), implements, property qualifiers
(rand/randc/local/protected/static/const), virtual interface
properties, parameterized types, method qualifiers with extern and
pure-virtual prototypes plus out-of-body cls::method definitions,
typedef class, scoped parameterized calls, disable fork. Class
bodies reuse the existing item loop, so Meta, directives, macros and
nesting work with no per-site code. Constraint blocks, covergroups
and parameterized-type #() arguments are span-sliced verbatim leaves
-- their internals are a distinct sub-language where formatting has
no payoff and corruption risk is highest, so 9 masked-corruption
rejection tests ship although verify.rs is byte-identical
(invariant-4 discipline, voluntarily; QA's sabotage recreated the
historical in-string corruption and exactly one pin turned red).

Corpus: 476 -> 578/820 formattable (70.5%), parse-error 344 -> 242,
zero regressions by path, all 578 formattable files round-tripped
individually. 72 of the 142 extends files format; 70 advance to
named next blockers -- queues/dynamic arrays are now the top corpus
blocker (41 files). Two verification failures fixed en route: a
pre-existing lexer blank-line-after-continuation bug (proven
pre-existing on a HEAD worktree) and raw_inline convergence for
mid-line verbatim starts.

Handshakes filed: fences inactive inside class bodies; the four
AST-walking lint rules skip class members (line-based rules still
fire); vlog_semantic treats class bodies as opaque -- the LSP
navigation gap is that crate's natural next round. parse() now takes
the source (verbatim capture in strict mode); single caller updated.

612 workspace tests (397 cases). Dev: Opus agent; QA: Sonnet agent
(pre-feature worktree diff, full 578-file round-trip, UVM torture,
two reverted sabotages); review in docs/features/classes/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-19 13:45:18 -07:00
1 parent 26a59c1d6a
commit 7f2e78fc1c
13 files changed
+2343 -79

No files matched your search

+21 -4
View File
@@ -238,7 +238,19 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
parameter overrides, instance arrays
- `generate` regions and module-level `if`/`for`/`case`
- Functions and tasks (ANSI and old-style port declarations)
- `typedef` (aliases, `enum`, packed `struct`/`union`)
- `typedef` (aliases, `enum`, packed `struct`/`union`, `typedef class`
forward declarations)
- Classes: `class`/`virtual class` … `endclass[: label]`, `#( ... )` class
parameters, `extends Base[#( ... )]`, `implements`, and class-scope members —
properties with `rand`/`randc`/`local`/`protected`/`static`/`const`, virtual
interface handles, parameterized types (`uvm_analysis_port #(bit [31:0]) p;`),
methods with `virtual`/`static`/`local`/`protected`/`automatic`, `function
new`, `extern` and `pure virtual` prototypes and their out-of-body
definitions, plus everything that already works at module scope (`typedef`,
`localparam`, `import`, directives, macro items, nested classes). `constraint
c { ... }` and `covergroup … endgroup` are **passed through verbatim** — two
grammars with no layout convention worth inventing. See
`docs/features/classes/README.md`
- Expressions: the full operator precedence table, ternaries,
concatenation/replication, slices (`+:`/`-:`), casts (`int'(x)`),
assignment patterns (`'{...}`), `inside`, hierarchical and package-scoped
@@ -271,10 +283,15 @@ corpus baseline this ordering comes from:
(`` `ASSERT_INIT(...) `` style)~~ — **done**; see
`docs/features/macro-items/README.md`. Unblocked 179 corpus files and
moved the parse rate from 35.2% to 57.1%
2. Classes/constraints (mostly blocks DV/UVM code, not RTL) — now the top
blocker at 142 files, all `extends`
2. ~~Classes/constraints (mostly blocks DV/UVM code, not RTL) — the top
blocker at 142 files, all `extends`~~ — **done**; see
`docs/features/classes/README.md`. Unblocked 102 corpus files and moved
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
4. Dynamic arrays and queues
4. Dynamic arrays and queues — now the top blocker at 41 files (`bit x[$]`,
`int q[]`)
5. Declarations with identifier (typedef'd) types in some positions
(`my_t [N-1:0] x;`)
6. ~~`` `ifdef``/`` `define``/`` `include`` inside a port, parameter or enum
+7
View File
@@ -233,6 +233,13 @@ Adapt each:
→ `tools/corpus_fetch.sh` + `tools/corpus_check.sh`, baseline and
findings in `docs/features/corpus-check/README.md`. CI wiring is the
one part left open (network access is a separate decision).
→ Latest movement: classes/constraints
(`docs/features/classes/README.md`) took the corpus from 476/820
formattable (58.0%) to **578/820 (70.5%)** — 102 files gained, 0 lost,
0 verification errors, 0 crashes, checked by diffing the two TSVs by
path. 72 of the 142 `extends`-blocked files now format; the other 70
advanced to a second blocker, and the new top blocker is dynamic
arrays and queues (README roadmap item 4, 41 files).
- [ ] **[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.
+110 -2
View File
@@ -173,6 +173,18 @@ impl<'a> Fmt<'a> {
self.raw_lines(&raw.text, raw.col)
}
/// Verbatim text that does *not* start the line it is printed on: the
/// `#( ... )` of a parameterized type or class reference.
///
/// It is emitted exactly as written, continuation lines included.
/// `raw_lines`'s dedent-by-column only reaches a fixed point when the text
/// begins its own line — the dedent has to cancel the indent the printer
/// adds back — and this text never does, so re-indenting it would drift.
/// Emitting it unchanged is idempotent by construction.
fn raw_inline(&self, raw: &RawText) -> Doc {
text(raw.text.clone())
}
/// A macro invocation standing as an item or a statement. The invocation
/// itself is verbatim source — we do not expand macros, so re-spacing the
/// argument list would be guesswork — and the trailing `;` is reproduced
@@ -671,6 +683,8 @@ impl<'a> Fmt<'a> {
ItemKind::GenCase(g) => self.gen_case(g),
ItemKind::Function(f) => self.function(f),
ItemKind::Task(t) => self.task(t),
ItemKind::Class(c) => self.class(c),
ItemKind::Verbatim(raw) => self.raw_text(raw),
ItemKind::Defparam(pairs) => {
let parts: Vec<Doc> = pairs
.iter()
@@ -828,6 +842,16 @@ impl<'a> Fmt<'a> {
docs.push(text(ty.name.clone()));
need_space = true;
}
// `uvm_analysis_port #(bit [31:0]) port;` — spaced before the `#(`,
// like an instantiation's overrides and unlike the tight `#(` of a
// parameterized name in expression position.
if let Some(params) = &ty.params {
if need_space {
docs.push(text(" "));
}
docs.push(self.raw_inline(params));
need_space = true;
}
if let Some(s) = &ty.signing {
if need_space {
docs.push(text(" "));
@@ -1008,6 +1032,7 @@ impl<'a> Fmt<'a> {
fn typedef(&self, t: &Typedef) -> Doc {
match &t.kind {
TypedefKind::ForwardClass => text(format!("typedef class {};", t.name)),
TypedefKind::Alias(ty) => {
let mut docs = vec![text("typedef ")];
if let Some(d) = self.data_type(ty) {
@@ -1443,8 +1468,69 @@ impl<'a> Fmt<'a> {
self.delimited("(", items, ")", false)
}
/// A class: header on one line (its parameter and `extends` override
/// lists break like any other list when they do not fit), body items at
/// one more indent level, `endclass` with the label the source wrote.
fn class(&self, c: &ClassDecl) -> Doc {
let mut head = String::new();
for q in &c.prefix {
head.push_str(q);
head.push(' ');
}
head.push_str("class ");
if let Some(lifetime) = &c.lifetime {
head.push_str(lifetime);
head.push(' ');
}
head.push_str(&c.name);
let mut docs = vec![text(head)];
let on_fresh_line = self.bracket_comments(&c.param_comments, &mut docs, false);
if let Some(params) = &c.param_ports {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
.collect();
let items = self.list_entries(items, &c.param_directives);
let broken = !c.param_directives.is_empty();
docs.push(text(if on_fresh_line { "#" } else { " #" }));
docs.push(self.delimited_dangling("(", items, &c.param_dangling, ")", broken));
}
if let Some(ext) = &c.extends {
docs.push(text(format!(" extends {}", ext.name)));
let fresh = self.bracket_comments(&ext.param_comments, &mut docs, false);
if let Some(params) = &ext.params {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma))
.collect();
let items = self.list_entries(items, &ext.param_directives);
let broken = !ext.param_directives.is_empty();
docs.push(text(if fresh { "#" } else { " #" }));
docs.push(self.delimited("(", items, ")", broken));
}
}
if !c.implements.is_empty() {
docs.push(text(format!(" implements {}", join_names(&c.implements))));
}
docs.push(text(";"));
let mut body = Vec::new();
if !c.items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(&c.items));
}
body.extend(self.dangling(&c.dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(Self::closing("endclass", &c.end_label));
concat(docs)
}
fn function(&self, f: &FunctionDecl) -> Doc {
let mut header = vec![text("function ")];
let mut header = Vec::new();
for q in &f.prefix {
header.push(text(format!("{q} ")));
}
header.push(text("function "));
for q in &f.qualifiers {
header.push(text(format!("{q} ")));
}
@@ -1454,11 +1540,19 @@ impl<'a> Fmt<'a> {
header.push(text(" "));
}
}
if let Some(scope) = &f.scope {
header.push(text(format!("{scope}::")));
}
header.push(text(f.name.clone()));
if f.has_parens {
header.push(self.tf_args(&f.args));
}
header.push(text(";"));
// A prototype (`extern`/`pure virtual`) is the header and nothing
// else: no body, no `endfunction`.
if f.is_prototype {
return concat(header);
}
let mut body = Vec::new();
if !f.stmts.is_empty() {
body.push(Doc::HardLine);
@@ -1474,15 +1568,25 @@ impl<'a> Fmt<'a> {
}
fn task(&self, t: &TaskDecl) -> Doc {
let mut header = vec![text("task ")];
let mut header = Vec::new();
for q in &t.prefix {
header.push(text(format!("{q} ")));
}
header.push(text("task "));
for q in &t.qualifiers {
header.push(text(format!("{q} ")));
}
if let Some(scope) = &t.scope {
header.push(text(format!("{scope}::")));
}
header.push(text(t.name.clone()));
if t.has_parens {
header.push(self.tf_args(&t.args));
}
header.push(text(";"));
if t.is_prototype {
return concat(header);
}
let mut body = Vec::new();
if !t.stmts.is_empty() {
body.push(Doc::HardLine);
@@ -1958,6 +2062,10 @@ impl<'a> Fmt<'a> {
ExprKind::Scope { base, name } => {
concat(vec![self.expr(base), text(format!("::{name}"))])
}
// Written tight, like the `::` it almost always precedes.
ExprKind::Parameterized { base, params } => {
concat(vec![self.expr(base), self.raw_inline(params)])
}
ExprKind::Concat(items) => self.expr_list("{", items, "}"),
ExprKind::Repl { count, inner } => concat(vec![
text("{"),
@@ -0,0 +1,493 @@
# empty class
class c;
endclass
----
class c;
endclass
====
# class body is indented one level and endclass keeps its label
class c;
localparam int W = 8;
endclass : c
----
class c;
localparam int W = 8;
endclass : c
====
# virtual class
virtual class base;
endclass
----
virtual class base;
endclass
====
# extends a plain base class
class c extends base;
endclass
----
class c extends base;
endclass
====
# extends a package-scoped base class
class c extends pkg::base;
endclass
----
class c extends pkg::base;
endclass
====
# extends with named parameter overrides, joined onto the header line
class ibex_icache_core_driver
extends dv_base_driver #(.ITEM_T (req_item),
.CFG_T (agent_cfg));
endclass
----
class ibex_icache_core_driver extends dv_base_driver #(.ITEM_T(req_item), .CFG_T(agent_cfg));
endclass
====
# extends overrides break one per line when the header does not fit
class ibex_icache_core_agent extends dv_base_agent #(.CFG_T(ibex_icache_core_agent_cfg), .DRIVER_T(ibex_icache_core_driver), .MONITOR_T(ibex_icache_core_monitor));
endclass
----
class ibex_icache_core_agent extends dv_base_agent #(
.CFG_T(ibex_icache_core_agent_cfg),
.DRIVER_T(ibex_icache_core_driver),
.MONITOR_T(ibex_icache_core_monitor)
);
endclass
====
# extends with ordered (positional) overrides
class cov extends dv_base_agent_cov #(agent_cfg);
endclass
----
class cov extends dv_base_agent_cov #(agent_cfg);
endclass
====
# class parameter port list, and an extends clause using those parameters
class push_pull_driver #(
parameter int HostDataWidth = 32,
parameter int DeviceDataWidth = HostDataWidth
) extends dv_base_driver #(.CFG_T(cfg_t));
endclass
----
class push_pull_driver #(
parameter int HostDataWidth = 32,
parameter int DeviceDataWidth = HostDataWidth
) extends dv_base_driver #(.CFG_T(cfg_t));
endclass
====
# implements clause
class c implements a, b;
endclass
----
class c implements a, b;
endclass
====
# rand and randc properties
class item extends uvm_sequence_item;
rand bit [31:0] branch_addr;
randc int num_insns;
endclass
----
class item extends uvm_sequence_item;
rand bit [31:0] branch_addr;
randc int num_insns;
endclass
====
# local, protected, static and const properties
class c;
local int a;
protected bit b;
static int count;
const int limit = 4;
endclass
----
class c;
local int a;
protected bit b;
static int count;
const int limit = 4;
endclass
====
# a virtual-interface property
class cfg extends dv_base_agent_cfg;
virtual ibex_icache_core_if vif;
virtual interface other_if oif;
endclass
----
class cfg extends dv_base_agent_cfg;
virtual ibex_icache_core_if vif;
virtual interface other_if oif;
endclass
====
# a property whose type is parameterized
class c;
uvm_analysis_port #(bit [31:0]) analysis_port;
push_pull_agent_cfg #(HostDataWidth, DeviceDataWidth) cfg;
endclass
----
class c;
uvm_analysis_port #(bit [31:0]) analysis_port;
push_pull_agent_cfg #(HostDataWidth, DeviceDataWidth) cfg;
endclass
====
# methods: new, void function, task, and the qualifiers before them
class c;
function new(string name, uvm_component parent);
super.new(name, parent);
endfunction : new
virtual function void build_phase(uvm_phase phase);
super.build_phase(phase);
endfunction
virtual task automatic reset_signals();
cfg.vif.reset();
endtask
local function int helper();
return 1;
endfunction
endclass
----
class c;
function new(string name, uvm_component parent);
super.new(name, parent);
endfunction : new
virtual function void build_phase(uvm_phase phase);
super.build_phase(phase);
endfunction
virtual task automatic reset_signals();
cfg.vif.reset();
endtask
local function int helper();
return 1;
endfunction
endclass
====
# pure virtual prototypes have no body and no endfunction/endtask
virtual class sub_driver;
pure virtual function void reset_signals();
pure virtual task wait_cb(int num = 1);
endclass
----
virtual class sub_driver;
pure virtual function void reset_signals();
pure virtual task wait_cb(int num = 1);
endclass
====
# extern prototypes, and the out-of-body definition that goes with one
class dv_base_mem;
extern function void set_enable(bit enable);
endclass
function void dv_base_mem::set_enable(bit enable);
this.enable = enable;
endfunction
----
class dv_base_mem;
extern function void set_enable(bit enable);
endclass
function void dv_base_mem::set_enable(bit enable);
this.enable = enable;
endfunction
====
# a constraint block is reproduced byte for byte, only re-indented
class item;
constraint c_branch_addr_alignment {
// The branch address is always required to be half-word aligned.
!branch_addr[0];
(trans_type != Branch) -> branch_addr == 0;
solve trans_type before branch_addr;
}
endclass
----
class item;
constraint c_branch_addr_alignment {
// The branch address is always required to be half-word aligned.
!branch_addr[0];
(trans_type != Branch) -> branch_addr == 0;
solve trans_type before branch_addr;
}
endclass
====
# a constraint written at column 1 is re-indented into the class body
class item;
constraint c_dist {
num_insns dist { 0 :/ 5, [1:20] :/ 20, [21:100] :/ 1 };
}
endclass
----
class item;
constraint c_dist {
num_insns dist { 0 :/ 5, [1:20] :/ 20, [21:100] :/ 1 };
}
endclass
====
# a covergroup is reproduced byte for byte too, endgroup label included
class cov;
covergroup branch_dest_cg with function sample (bit [31:0] addr);
coverpoint addr {
bins zero = { 0 };
bins mid = default;
}
endgroup : branch_dest_cg
endclass
----
class cov;
covergroup branch_dest_cg with function sample (bit [31:0] addr);
coverpoint addr {
bins zero = { 0 };
bins mid = default;
}
endgroup : branch_dest_cg
endclass
====
# macro items inside a class body
class c extends base;
`uvm_component_utils(c)
`uvm_component_new
endclass
----
class c extends base;
`uvm_component_utils(c)
`uvm_component_new
endclass
====
# a bare macro item followed by a parameterized-type declaration
class c;
`uvm_component_new
uvm_analysis_port #(bit [31:0]) analysis_port;
endclass
----
class c;
`uvm_component_new
uvm_analysis_port #(bit [31:0]) analysis_port;
endclass
====
# compiler directives between class members
class c;
`ifdef VERILATOR
int a;
`else
int b;
`endif
`define CB cfg.vif.host_push_cb
endclass
----
class c;
`ifdef VERILATOR
int a;
`else
int b;
`endif
`define CB cfg.vif.host_push_cb
endclass
====
# a class inside a package
package p;
class c extends base;
int x;
endclass : c
endpackage
----
package p;
class c extends base;
int x;
endclass : c
endpackage
====
# a class nested inside a class
class outer;
class inner;
int x;
endclass
int y;
endclass
----
class outer;
class inner;
int x;
endclass
int y;
endclass
====
# typedef forward-declaring a class
typedef class push_pull_sub_driver;
typedef class push_host_driver;
----
typedef class push_pull_sub_driver;
typedef class push_host_driver;
====
# comments on class members, and a blank line between them
class c;
// what this holds
int a; // trailing
// and this
int b;
endclass
----
class c;
// what this holds
int a; // trailing
// and this
int b;
endclass
====
# a comment written just before endclass stays inside the class
class c;
int a;
// last word
endclass
----
class c;
int a;
// last word
endclass
====
# a comment after a constraint's closing brace is not swallowed by it
class c;
constraint x {
a == 0;
} // why
int b;
endclass
----
class c;
constraint x {
a == 0;
} // why
int b;
endclass
====
# statements a class body needs: new, super, scoped create, disable fork
class c;
function void build_phase(uvm_phase phase);
super.build_phase(phase);
analysis_port = new("analysis_port", this);
rsp = rsp_item::type_id::create("rsp");
endfunction
task t();
fork
a();
join_any
disable fork;
endtask
endclass
----
class c;
function void build_phase(uvm_phase phase);
super.build_phase(phase);
analysis_port = new("analysis_port", this);
rsp = rsp_item::type_id::create("rsp");
endfunction
task t();
fork
a();
join_any
disable fork;
endtask
endclass
====
# a parameterized class reference in expression position stays tight
class c;
function void build_phase(uvm_phase phase);
if (!uvm_config_db#(virtual core_if)::get(this, "", "vif", cfg.vif)) begin
`uvm_fatal(`gfn, "no vif")
end
sub = push_host_driver#(HostDataWidth, DeviceDataWidth)::type_id::create("sub");
endfunction
endclass
----
class c;
function void build_phase(uvm_phase phase);
if (!uvm_config_db#(virtual core_if)::get(this, "", "vif", cfg.vif)) begin
`uvm_fatal(`gfn, "no vif")
end
sub = push_host_driver#(HostDataWidth, DeviceDataWidth)::type_id::create("sub");
endfunction
endclass
====
# a local variable of virtual-interface type inside a method
class c;
virtual task body();
virtual core_ibex_dut_probe_if ibex_dut_vif;
x = 1;
endtask
endclass
----
class c;
virtual task body();
virtual core_ibex_dut_probe_if ibex_dut_vif;
x = 1;
endtask
endclass
====
# a declaration of a parameterized type inside a method body
class c;
task t();
item #(A, B) req;
req = null;
endtask
endclass
----
class c;
task t();
item #(A, B) req;
req = null;
endtask
endclass
====
# an instantiation still wins over a parameterized-type declaration
module m;
sub #(.W(8)) u (.a(a));
port_t #(int) p;
endmodule
----
module m;
sub #(.W(8)) u (.a(a));
port_t #(int) p;
endmodule
====
# a typedef and an import inside a class body
class c;
typedef enum logic [1:0] {A, B} state_e;
import pkg::thing;
endclass
----
class c;
typedef enum logic [1:0] {A, B} state_e;
import pkg::thing;
endclass
====
# a class with a static lifetime keyword
class static c;
int x;
endclass
----
class static c;
int x;
endclass
====
# a constraint standing alone with no braces (prototype form)
class c;
constraint x;
endclass
----
class c;
constraint x;
endclass
====
# a string inside a constraint keeps its bytes when the block is re-indented
class c;
constraint x {
name == "a
b";
}
endclass
----
class c;
constraint x {
name == "a
b";
}
endclass
@@ -679,3 +679,92 @@ fn an_instantiation_list_directive_may_still_be_reindented() {
"module m;\n sub u (\n .a(x),\n `ifdef X\n .b(y)\n `endif\n );\nendmodule\n";
verify_equivalence(input, output).expect("only indentation changed");
}
// ----------------------------------------------------------------------
// Verbatim class-scope blocks (`docs/features/classes/README.md`).
//
// `constraint` and `covergroup` bodies are copied out of the source by span
// and re-indented, so the net must still see every token inside them. These
// are the invariant-#4 attack tests for that capture: no normalization was
// added for it, and each pair below proves a real change inside a verbatim
// block is refused rather than forgiven as "just re-indentation".
// ----------------------------------------------------------------------
#[test]
fn a_constraint_block_may_be_reindented() {
let input = "class c;\nconstraint x {\n a == 0;\n}\nendclass\n";
let output = "class c;\n constraint x {\n a == 0;\n }\nendclass\n";
verify_equivalence(input, output).expect("only per-line indentation changed");
}
#[test]
fn a_changed_constraint_expression_is_rejected() {
let input = "class c;\n constraint x {\n a == 0;\n }\nendclass\n";
let output = "class c;\n constraint x {\n a == 1;\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_constraint_line_is_rejected() {
let input = "class c;\n constraint x {\n a == 0;\n b == 1;\n }\nendclass\n";
let output = "class c;\n constraint x {\n a == 0;\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_comment_inside_a_constraint_is_rejected() {
let input = "class c;\n constraint x {\n // why\n a == 0;\n }\nendclass\n";
let output = "class c;\n constraint x {\n a == 0;\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_reindented_string_inside_a_constraint_is_rejected() {
let input = "class c;\n constraint x {\n n == \"a\n b\";\n }\nendclass\n";
let output = "class c;\n constraint x {\n n == \"a\n b\";\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_constraint_carrying_a_multiline_string_is_left_alone_end_to_end() {
// The formatter must not move those bytes at all: `raw_text` emits a
// token whose line break falls inside a string verbatim.
let input = "class c;\nconstraint x {\nn == \"a\n b\";\n}\nendclass\n";
let output = format_source(input, &Config::default()).expect("must format");
assert!(output.contains("\"a\n b\""), "the string's bytes changed:\n{output}");
}
#[test]
fn a_changed_covergroup_bin_is_rejected() {
let input = "class c;\n covergroup g;\n coverpoint a {\n bins z = { 0 };\n }\n endgroup\nendclass\n";
let output = "class c;\n covergroup g;\n coverpoint a {\n bins z = { 1 };\n }\n endgroup\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_covergroup_label_is_rejected() {
let input = "class c;\n covergroup g;\n coverpoint a;\n endgroup : g\nendclass\n";
let output = "class c;\n covergroup g;\n coverpoint a;\n endgroup\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_changed_parameterized_type_argument_is_rejected() {
let input = "class c;\n port_t #(bit [31:0]) p;\nendclass\n";
let output = "class c;\n port_t #(bit [30:0]) p;\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_class_end_label_is_rejected() {
let input = "class c;\n int a;\nendclass : c\n";
let output = "class c;\n int a;\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_method_qualifier_is_rejected() {
let input = "class c;\n virtual function void f();\n endfunction\nendclass\n";
let output = "class c;\n function void f();\n endfunction\nendclass\n";
expect_divergence(input, output);
}
+106 -2
View File
@@ -184,6 +184,12 @@ pub enum ItemKind {
GenCase(GenCase),
Function(FunctionDecl),
Task(TaskDecl),
/// A `class` / `virtual class` declaration and its body.
Class(ClassDecl),
/// A block vfmt deliberately does not model, kept byte-for-byte:
/// `constraint c { ... }` and `covergroup ... endgroup`. See
/// `docs/features/classes/README.md` for why each one is verbatim.
Verbatim(RawText),
Defparam(Vec<(Expr, Expr)>),
/// Source that could not be parsed as an item, kept verbatim.
///
@@ -310,13 +316,25 @@ pub struct ParamPort {
#[derive(Debug, Clone, Default)]
pub struct DataType {
pub name: String,
/// The `#( ... )` of a parameterized type reference, verbatim:
/// `uvm_analysis_port #(bit [31:0]) port;`. Its arguments are types as
/// often as expressions (`#(virtual bus_if)`, `#(item #(A, B))`), so vfmt
/// reproduces them as written instead of modelling a second grammar.
///
/// Boxed to keep `DataType` — and through `ExprKind::Type`, every `Expr`
/// — small: a parameterized type reference is rare and every expression
/// would otherwise carry the whole `RawText` inline.
pub params: Option<Box<RawText>>,
pub signing: Option<String>,
pub packed: Vec<Dim>,
}
impl DataType {
pub fn is_implicit(&self) -> bool {
self.name.is_empty() && self.signing.is_none() && self.packed.is_empty()
self.name.is_empty()
&& self.params.is_none()
&& self.signing.is_none()
&& self.packed.is_empty()
}
}
@@ -343,6 +361,8 @@ pub enum TypedefKind {
Alias(DataType),
Enum(EnumType),
Struct(StructType),
/// A forward declaration: `typedef class my_class;`
ForwardClass,
}
#[derive(Debug)]
@@ -401,7 +421,10 @@ pub struct DataDecl {
pub net: Option<String>,
/// Net delay: the `5` in `wire #5 w;`
pub delay: Option<Expr>,
/// `var` / `automatic` / `static` / `const` qualifiers, in order.
/// Qualifiers written before the type, in source order: `var`,
/// `automatic`, `static`, `const`, and — inside a class body — `rand`,
/// `randc`, `local`, `protected`, and the `virtual [interface]` of a
/// virtual-interface property.
pub qualifiers: Vec<String>,
pub ty: DataType,
pub declarators: Vec<Declarator>,
@@ -645,9 +668,76 @@ pub struct GenBlock {
pub span: TextRange,
}
/// A `class` declaration. Its body is an ordinary item list, so every item
/// kind that already works at module or package scope — declarations,
/// `typedef`, `localparam`, `import`, compiler directives, macro invocations
/// — works inside a class without any per-site code.
#[derive(Debug)]
pub struct ClassDecl {
/// Keywords written before `class`; `virtual` is the only one real code
/// uses. Kept as a list so the source order is reproduced verbatim.
pub prefix: Vec<String>,
/// `static`/`automatic` lifetime written after `class`, if any.
pub lifetime: Option<String>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// Comments written between the class name and the `#` of its parameter
/// port list.
pub param_comments: Vec<Comment>,
/// `None` when the header wrote no `#( ... )`; an empty `Some` is a
/// written-but-empty `#()`.
pub param_ports: Option<Vec<ParamPort>>,
/// Directives written between the parameter ports, in source order.
pub param_directives: Vec<ListDirective>,
/// Comments written after the last parameter port and before its `)`.
pub param_dangling: Vec<Comment>,
/// The `extends Base #( ... )` clause, if written.
pub extends: Option<ClassExtends>,
/// Interface classes named by `implements A, B`.
pub implements: Vec<Name>,
pub items: Vec<Item>,
pub dangling: Vec<Comment>,
/// Label after `endclass :`.
pub end_label: Option<String>,
/// Byte range of `end_label`.
pub end_label_span: Option<TextRange>,
}
/// The `extends Base #( ... )` clause of a class header. The overrides are
/// [`Connection`]s — the same node an instantiation's `#( ... )` uses, because
/// both spell named (`.CFG_T(cfg_t)`) and ordered (`cfg_t`) overrides the same
/// way.
#[derive(Debug)]
pub struct ClassExtends {
/// The base-class name as written, package scope included (`pkg::base`).
pub name: String,
/// Byte range covering `name`, its `::` chain included.
pub name_span: TextRange,
/// Comments written between the base-class name and the `#`.
pub param_comments: Vec<Comment>,
/// `None` when no `#( ... )` was written.
pub params: Option<Vec<Connection>>,
/// Directives written between the overrides, in source order.
pub param_directives: Vec<ListDirective>,
/// Code extent of the clause, from `extends` through its last token.
pub span: TextRange,
}
#[derive(Debug)]
pub struct FunctionDecl {
/// Class-member qualifiers written *before* the `function` keyword, in
/// source order: `virtual`, `local`, `protected`, `static`, `pure`,
/// `extern`. Empty outside a class body.
pub prefix: Vec<String>,
pub qualifiers: Vec<String>,
/// True for a body-less prototype — `extern function ...;` or
/// `pure virtual function ...;` — which has no `endfunction`.
pub is_prototype: bool,
/// The `my_class::` written before the name when an `extern` method is
/// *defined* outside its class body. Kept apart from `name` so
/// `src[name_span] == name` still holds for the method's own name.
pub scope: Option<String>,
pub ret: Option<DataType>,
pub name: String,
/// Byte range of `name`.
@@ -665,7 +755,14 @@ pub struct FunctionDecl {
#[derive(Debug)]
pub struct TaskDecl {
/// Class-member qualifiers written *before* the `task` keyword; see
/// [`FunctionDecl::prefix`].
pub prefix: Vec<String>,
pub qualifiers: Vec<String>,
/// True for a body-less prototype; see [`FunctionDecl::is_prototype`].
pub is_prototype: bool,
/// Out-of-body definition scope; see [`FunctionDecl::scope`].
pub scope: Option<String>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
@@ -919,6 +1016,13 @@ pub enum ExprKind {
base: Box<Expr>,
name: String,
},
/// A parameterized class reference: the `uvm_config_db#(virtual bus_if)`
/// of `uvm_config_db#(virtual bus_if)::get(...)`. The `#( ... )` is
/// verbatim, for the reason [`DataType::params`] gives.
Parameterized {
base: Box<Expr>,
params: RawText,
},
Concat(Vec<ExprItem>),
Repl {
count: Box<Expr>,
+36
View File
@@ -187,10 +187,25 @@ impl<'a> RawLexer<'a> {
}
// Line continuation: `define FOO \ <next line>
while self.text_ends_with_continuation(start) && self.peek() == b'\n' {
// A blank continuation line ends the directive and is *not*
// part of it: the token's text is trimmed back to the last
// `\` anyway, so consuming the newline here would hide a
// blank line from the attachment phase — and the formatter
// would then print whatever follows directly under a line
// ending in `\`, which re-lexes as part of the directive.
let mark = (self.pos, self.line, self.col);
self.bump();
let line_start = self.pos;
while self.pos < self.src.len() && self.peek() != b'\n' {
self.bump();
}
if self.src[line_start..self.pos].iter().all(u8::is_ascii_whitespace) {
let (pos, line, col) = mark;
self.pos = pos;
self.line = line;
self.col = col;
break;
}
}
let text = self.text_from(start).trim_end().to_string();
// Short directives like `WIDTH used inside expressions (macro
@@ -779,6 +794,27 @@ mod tests {
assert!(toks.iter().any(|(k, t)| *k == TokenKind::Ident && t == "`WIDTH"));
}
#[test]
fn a_blank_continuation_line_ends_a_directive_and_stays_a_blank_line() {
// The `\` on the last body line continues onto an *empty* line, which
// is what ends the directive. That empty line is not part of the
// token, and the comment after it must still see a blank line before
// it — otherwise the formatter prints the comment directly under a
// line ending in `\` and it re-lexes as part of the directive.
let toks = tokenize("`define A \\\n x \\\n\n// c\nwire w;\n").unwrap();
assert_eq!(toks[0].kind, TokenKind::Directive);
assert_eq!(toks[0].text, "`define A \\\n x \\");
let comment = &toks[1].leading[0];
assert_eq!(comment.text, "// c");
assert!(comment.blank_before, "the blank line before the comment was swallowed");
}
#[test]
fn a_nonblank_continuation_line_is_still_part_of_the_directive() {
let toks = tokenize("`define A \\\n x \\\n y\nwire w;\n").unwrap();
assert_eq!(toks[0].text, "`define A \\\n x \\\n y");
}
#[test]
fn macro_call_captures_balanced_arguments() {
// Nested brackets of every flavour, a string and a comment holding
+1 -1
View File
@@ -20,7 +20,7 @@ pub use span::TextRange;
/// Convenience: lex and parse in one step.
pub fn parse_source(source: &str) -> Result<ast::SourceFile, Error> {
let tokens = tokenize(source).map_err(Error::Lex)?;
parse(tokens).map_err(Error::Parse)
parse(tokens, source).map_err(Error::Parse)
}
/// Lex and parse without ever failing: the parts that do not parse become
+647 -68
View File
@@ -98,6 +98,7 @@ const SYNC_CLOSERS: &[&str] = &[
"endfunction",
"endtask",
"endcase",
"endclass",
"join",
"join_any",
"join_none",
@@ -105,8 +106,30 @@ const SYNC_CLOSERS: &[&str] = &[
/// Keywords that can only *begin* a construct at file scope. Recovery stops
/// before them too, so garbage written in front of a module cannot swallow it.
/// `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"];
/// Keywords that may stand *before* the one that names a class member:
/// `virtual function`, `pure virtual task`, `extern function`,
/// `local rand int x`, `protected static function`. They are looked at
/// without being consumed (see [`Parser::member_head`]) so the construct they
/// belong to keeps ownership of them.
const MEMBER_QUALIFIERS: &[&str] = &[
"virtual",
"pure",
"extern",
"local",
"protected",
"rand",
"randc",
"static",
"automatic",
"const",
"var",
];
const ASSIGN_OPS: &[&str] =
&["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<<=", ">>>="];
@@ -139,6 +162,16 @@ pub const MAX_NESTING_DEPTH: u32 = 64;
/// [`MAX_NESTING_DEPTH`], does not move the worst case.
pub const MAX_CHAIN_LENGTH: u32 = 256;
/// The three pieces a `#( parameter ... )` port list yields, so module and
/// class headers can share one parse.
#[derive(Default)]
struct ParamPortList {
/// `None` when no `#( ... )` was written at all.
ports: Option<Vec<ParamPort>>,
directives: Vec<ListDirective>,
dangling: Vec<Comment>,
}
/// What [`Parser::take_list_directives`] found between two list elements.
#[derive(Default)]
struct Harvested {
@@ -160,16 +193,21 @@ pub struct Parser<'a> {
links: u32,
/// Recover from errors instead of returning them; see [`parse_tolerant`].
tolerant: bool,
/// The text the tokens were lexed from. Read only by recovery, to copy a
/// skipped range into an error node, so strict mode passes `""`.
/// The text the tokens were lexed from, in both modes: recovery copies a
/// skipped range into an error node out of it, and so do the verbatim
/// class-scope blocks.
source: &'a str,
/// Errors recovered from, in source order. Always empty in strict mode.
diagnostics: Vec<ParseDiagnostic>,
}
/// Parse a token stream, stopping at the first error.
pub fn parse(tokens: Vec<Token>) -> PResult<SourceFile> {
Parser::new(tokens, "", false).parse_source_file()
///
/// `source` must be the exact text `tokens` were lexed from: the constructs
/// vfmt keeps verbatim (`constraint`, `covergroup` — see
/// `docs/features/classes/README.md`) copy their bytes out of it by span.
pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
Parser::new(tokens, source, false).parse_source_file()
}
/// Parse a token stream that may be broken, recording errors instead of
@@ -406,8 +444,7 @@ impl<'a> Parser<'a> {
RawText { text: self.slice(span), col, span }
}
/// The source text `span` covers. Empty in strict mode, which never
/// recovers and is therefore never given the source.
/// The source text `span` covers.
fn slice(&self, span: TextRange) -> String {
self.source.get(span.as_range()).unwrap_or_default().to_string()
}
@@ -701,7 +738,10 @@ impl<'a> Parser<'a> {
/// `` `TYPE [3:0] x; ``);
/// * next token is a plain identifier — `` `TYPE x; `` /
/// `` `MOD u (...); ``, *unless* this invocation has an argument list,
/// which no type or module name in real RTL does;
/// which no type or module name in real RTL does, or the identifier is
/// itself followed by a `#(` — `` `uvm_component_new `` ⏎
/// `` uvm_analysis_port #(bit [31:0]) p; `` is a standalone macro and a
/// parameterized-type declaration, never one construct;
/// * anything else (a keyword, another macro, a directive, end of file) —
/// the invocation stands alone.
///
@@ -718,7 +758,9 @@ impl<'a> Parser<'a> {
}
match next.kind {
TokenKind::Symbol => false,
TokenKind::Ident if !next.is_macro() => self.cur().has_macro_args(),
TokenKind::Ident if !next.is_macro() => {
self.cur().has_macro_args() || (self.nth(2).is_sym("#") && self.nth(3).is_sym("("))
}
_ => true,
}
}
@@ -771,6 +813,63 @@ impl<'a> Parser<'a> {
}
}
/// The first token past the run of [`MEMBER_QUALIFIERS`] at the cursor —
/// the one that says what is being declared. Consumes nothing.
fn member_head(&self) -> &Token {
let mut i = self.pos;
while self.tokens[i].kind == TokenKind::Keyword
&& MEMBER_QUALIFIERS.contains(&self.tokens[i].text.as_str())
&& i + 1 < self.tokens.len()
{
i += 1;
}
&self.tokens[i]
}
/// Consume the run of [`MEMBER_QUALIFIERS`] at the cursor, in source order.
fn take_member_prefix(&mut self) -> Vec<String> {
let mut out = Vec::new();
while self.cur().kind == TokenKind::Keyword
&& MEMBER_QUALIFIERS.contains(&self.cur().text.as_str())
{
out.push(self.bump().text);
}
out
}
/// A method name, with the `my_class::` scope of an out-of-body
/// definition split off so the returned [`Name`] is only the method's own.
fn parse_method_name(&mut self) -> PResult<(Option<String>, Name)> {
let mut name = self.expect_name()?;
let mut scope: Option<String> = None;
while self.cur().is_sym("::") {
self.bump();
let next = self.expect_name()?;
match &mut scope {
Some(s) => {
s.push_str("::");
s.push_str(&name.text);
}
None => scope = Some(name.text),
}
name = next;
}
Ok((scope, name))
}
/// A `pkg::name` chain, returned as the joined text plus the
/// range covering the whole chain.
fn parse_scoped_name(&mut self) -> PResult<(String, TextRange)> {
let start = self.here();
let mut name = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
name.push_str("::");
name.push_str(&self.expect_ident()?);
}
Ok((name, self.span_from(start)))
}
/// Given `self.tokens[i]` == an opening bracket, return the index just
/// past its matching close. Used for disambiguating lookahead only.
fn scan_matching(&self, mut i: usize, open: &str, close: &str) -> usize {
@@ -913,6 +1012,23 @@ impl<'a> Parser<'a> {
"case" => self.parse_gen_case().map(ItemKind::GenCase),
"function" => self.parse_function().map(ItemKind::Function),
"task" => self.parse_task().map(ItemKind::Task),
"class" => self.parse_class().map(ItemKind::Class),
"constraint" => self.parse_constraint().map(ItemKind::Verbatim),
"covergroup" => self.parse_covergroup().map(ItemKind::Verbatim),
// A run of member qualifiers (`virtual`, `local rand`, `static`,
// `pure virtual`, ...) does not say what it qualifies; the first
// keyword past the run does. Nothing is consumed here, so each
// branch parses its own construct from the first qualifier on.
_ if MEMBER_QUALIFIERS.contains(&kw.as_str()) => {
match self.member_head().text.as_str() {
"class" => self.parse_class().map(ItemKind::Class),
"function" => self.parse_function().map(ItemKind::Function),
"task" => self.parse_task().map(ItemKind::Task),
"constraint" => self.parse_constraint().map(ItemKind::Verbatim),
"covergroup" => self.parse_covergroup().map(ItemKind::Verbatim),
_ => self.parse_data_decl().map(ItemKind::DataDecl),
}
}
"defparam" => {
self.bump();
let mut pairs = Vec::new();
@@ -933,10 +1049,7 @@ impl<'a> Parser<'a> {
}
_ if NET_KEYWORDS.contains(&kw.as_str())
|| TYPE_KEYWORDS.contains(&kw.as_str())
|| matches!(
kw.as_str(),
"var" | "automatic" | "static" | "const" | "signed" | "unsigned"
) =>
|| matches!(kw.as_str(), "signed" | "unsigned") =>
{
let d = self.parse_data_decl()?;
Ok(ItemKind::DataDecl(d))
@@ -955,6 +1068,19 @@ impl<'a> Parser<'a> {
}
let t1 = self.nth(p + 1 - self.pos);
if t1.is_sym("#") {
// `sub #(.W(8)) u (...);` and `port_t #(int) p;` open the same
// way. What follows the name after the overrides tells them
// apart: an instance has a connection list or an array range,
// a declaration goes straight to `;`, `,` or `=`.
if self.tokens.get(p + 2).is_some_and(|t| t.is_sym("(")) {
let name = self.scan_matching(p + 2, "(", ")");
let after = self.tokens.get(name + 1);
if self.tokens.get(name).is_some_and(|t| t.kind == TokenKind::Ident)
&& !after.is_some_and(|t| t.is_sym("(") || t.is_sym("["))
{
return self.parse_data_decl().map(ItemKind::DataDecl);
}
}
return self.parse_instantiation().map(ItemKind::Instantiation);
}
if t1.kind == TokenKind::Ident {
@@ -1011,6 +1137,209 @@ impl<'a> Parser<'a> {
Ok(paths)
}
// ------------------------------------------------------------------
// Classes
// ------------------------------------------------------------------
/// `[virtual] class [lifetime] name [#(params)] [extends base [#(...)]]
/// [implements a, b]; items endclass [: label]`.
///
/// The body is parsed by the ordinary item loop, so everything that
/// already works at module scope — declarations, `typedef`, `localparam`,
/// `import`, directives, macro invocations — works inside a class for
/// free, and nesting is charged against the item budget by `parse_item`.
fn parse_class(&mut self) -> PResult<ClassDecl> {
let prefix = self.take_member_prefix();
self.expect_kw("class")?;
let lifetime = if self.cur().is_kw("static") || self.cur().is_kw("automatic") {
Some(self.bump().text)
} else {
None
};
let Name { text: name, span: name_span } = self.expect_name()?;
let param_comments = self.take_before_open("#");
let params = self.parse_param_port_list()?;
let extends =
if self.cur().is_kw("extends") { Some(self.parse_class_extends()?) } else { None };
let mut implements = Vec::new();
if self.eat_kw("implements") {
loop {
let (text, span) = self.parse_scoped_name()?;
implements.push(Name { text, span });
if !self.eat_sym(",") {
break;
}
}
}
self.expect_sym(";")?;
let mut items = Vec::new();
while !self.at_body_end("endclass") {
items.push(self.item_or_recover()?);
}
let dangling = self.take_dangling();
self.expect_closer("endclass")?;
let (end_label, end_label_span) = split_label(self.parse_label()?);
Ok(ClassDecl {
prefix,
lifetime,
name,
name_span,
param_comments,
param_ports: params.ports,
param_directives: params.directives,
param_dangling: params.dangling,
extends,
implements,
items,
dangling,
end_label,
end_label_span,
})
}
/// `extends base [#( overrides )]`. The overrides are the same
/// [`Connection`] list an instantiation's `#( ... )` uses.
fn parse_class_extends(&mut self) -> PResult<ClassExtends> {
let start = self.here();
self.expect_kw("extends")?;
let (name, name_span) = self.parse_scoped_name()?;
let param_comments = self.take_before_open("#");
let mut params = None;
let mut param_directives = Vec::new();
if self.cur().is_sym("#") {
self.bump();
self.expect_sym("(")?;
let mut list = Vec::new();
self.take_list_directives(&mut param_directives, 0);
if !self.cur().is_sym(")") {
loop {
list.push(self.parse_connection()?);
if let Some(last) = list.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = list.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(&mut param_directives, list.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
}
let n = list.len();
self.take_last_entry_before_close(
list.last_mut().map(|c| &mut c.meta),
&mut param_directives,
n,
);
self.expect_sym(")")?;
params = Some(list);
}
Ok(ClassExtends {
name,
name_span,
param_comments,
params,
param_directives,
span: self.span_from(start),
})
}
/// `constraint name { ... }`, kept as verbatim source.
///
/// The constraint language is a grammar of its own (`dist`, `->`,
/// `solve ... before`, `inside`, `foreach`, `if`/`else`) that vfmt models
/// none of, and reflowing it has no payoff, so the block is copied out of
/// the source by span. A prototype (`constraint c;`) has no braces.
fn parse_constraint(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
self.take_member_prefix();
self.expect_kw("constraint")?;
self.expect_name()?;
if !self.eat_sym(";") {
self.expect_sym("{")?;
self.skip_balanced("{", "}")?;
// `constraint c { ... };` — a stray `;` is legal and belongs to the
// block, not to the item that follows it.
self.eat_sym(";");
}
Ok(self.verbatim_since(start, col))
}
/// `covergroup name ... endgroup [: label]`, kept as verbatim source, for
/// the same reason constraints are: coverpoints, bins and crosses are a
/// separate grammar with nothing to gain from canonical layout.
fn parse_covergroup(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
self.take_member_prefix();
self.expect_kw("covergroup")?;
while !self.at_eof() && !self.cur().is_kw("endgroup") {
self.bump();
}
self.expect_closer("endgroup")?;
self.parse_label()?;
self.eat_sym(";");
Ok(self.verbatim_since(start, col))
}
/// True when the cursor opens a parameterized type's `#( ... )`.
fn at_type_params(&self) -> bool {
self.cur().is_sym("#") && self.nth(1).is_sym("(")
}
/// The `#( ... )` of a parameterized type or class reference, verbatim.
fn parse_type_params(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
self.expect_sym("#")?;
self.expect_sym("(")?;
self.skip_balanced("(", ")")?;
Ok(self.verbatim_since(start, col))
}
/// Consume tokens through the `close` that matches the `open` already
/// consumed. Brackets inside strings and comments cannot appear here —
/// the lexer has already turned those into single tokens.
fn skip_balanced(&mut self, open: &str, close: &str) -> PResult<()> {
let mut depth = 1usize;
while depth > 0 {
if self.at_eof() {
return self.error(format!("expected `{close}`"));
}
let t = self.cur();
if t.is_sym(open) {
depth += 1;
} else if t.is_sym(close) {
depth -= 1;
}
self.bump();
}
Ok(())
}
/// The source bytes consumed since `start`, as verbatim text.
///
/// A comment written *inside* the block is part of those bytes, so the
/// copy [`Parser::bump`] moved into a pending bucket is dropped — leaving
/// it there would reattach it to the next node and print it a second time.
/// The filter is by span rather than by a saved length precisely so the
/// comment written *after* the block's last token on the same line
/// (`} // end of constraint`) survives: it is outside the span, so it
/// stays pending and is harvested by whoever comes next.
fn verbatim_since(&mut self, start: u32, col: u32) -> RawText {
let span = self.span_from(start);
let outside = |c: &Comment| c.span.end <= span.start || c.span.start >= span.end;
self.pending_leading.retain(outside);
self.pending_trailing.retain(outside);
RawText { text: self.slice(span), col, span }
}
// ------------------------------------------------------------------
// Module
// ------------------------------------------------------------------
@@ -1026,42 +1355,11 @@ impl<'a> Parser<'a> {
imports.push(HeaderImport { meta, paths });
}
let param_comments = self.take_before_open("#");
let mut param_ports = None;
let mut param_directives = Vec::new();
let mut param_dangling = Vec::new();
if self.cur().is_sym("#") {
self.bump();
self.expect_sym("(")?;
let mut list = Vec::new();
self.take_list_directives(&mut param_directives, 0);
if !self.cur().is_sym(")") {
loop {
list.push(self.parse_param_port()?);
if let Some(last) = list.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = list.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(&mut param_directives, list.len());
// Without a comma and without a directive the list is
// over. With one, only the closing bracket says so: an
// `` `ifdef`` arm may end without a comma and another arm
// may still follow (`` `else``), or the arm may have been
// the tail of the list.
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
}
param_dangling = self.take_dangling();
self.expect_sym(")")?;
param_ports = Some(list);
}
let ParamPortList {
ports: param_ports,
directives: param_directives,
dangling: param_dangling,
} = self.parse_param_port_list()?;
let port_comments = self.take_before_open("(");
let (ports, port_dangling, port_directives) = self.parse_port_list()?;
self.expect_sym(";")?;
@@ -1092,6 +1390,46 @@ impl<'a> Parser<'a> {
})
}
/// 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<ParamPortList> {
let mut out = ParamPortList::default();
if !self.cur().is_sym("#") {
return Ok(out);
}
self.bump();
self.expect_sym("(")?;
let mut list = Vec::new();
self.take_list_directives(&mut out.directives, 0);
if !self.cur().is_sym(")") {
loop {
list.push(self.parse_param_port()?);
if let Some(last) = list.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = list.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(&mut out.directives, list.len());
// Without a comma and without a directive the list is over.
// With one, only the closing bracket says so: an `` `ifdef``
// arm may end without a comma and another arm may still follow
// (`` `else``), or the arm may have been the tail of the list.
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
}
out.dangling = self.take_dangling();
self.expect_sym(")")?;
out.ports = Some(list);
Ok(out)
}
fn parse_param_port(&mut self) -> PResult<ParamPort> {
let start = self.here();
let mut meta = self.take_meta();
@@ -1258,7 +1596,14 @@ impl<'a> Parser<'a> {
while self.tokens.get(p + 1).is_some_and(|t| t.is_sym("::")) {
p += 2;
}
let next = p + 1;
let mut next = p + 1;
// A parameterized type puts `#( ... )` between the name and the
// declarator (`uvm_analysis_port #(bit [31:0]) port;`).
if self.tokens.get(next).is_some_and(|t| t.is_sym("#"))
&& self.tokens.get(next + 1).is_some_and(|t| t.is_sym("("))
{
next = self.scan_matching(next + 1, "(", ")");
}
let is_type = match self.tokens.get(next) {
Some(n) if n.kind == TokenKind::Ident => true,
Some(n) if n.is_sym("[") => {
@@ -1275,6 +1620,9 @@ impl<'a> Parser<'a> {
name.push_str(&self.expect_ident()?);
}
ty.name = name;
if self.at_type_params() {
ty.params = Some(Box::new(self.parse_type_params()?));
}
}
}
if self.cur().is_kw("signed") || self.cur().is_kw("unsigned") {
@@ -1353,12 +1701,15 @@ impl<'a> Parser<'a> {
let t = self.cur();
if t.kind == TokenKind::Keyword && NET_KEYWORDS.contains(&t.text.as_str()) {
net = Some(self.bump().text);
} else if t.is_kw("var")
|| t.is_kw("automatic")
|| t.is_kw("static")
|| t.is_kw("const")
{
} else if t.kind == TokenKind::Keyword && MEMBER_QUALIFIERS.contains(&t.text.as_str()) {
let was_virtual = t.is_kw("virtual");
qualifiers.push(self.bump().text);
// `virtual interface my_if h;` — the `interface` keyword is
// part of the qualifier, not a construct of its own, and is
// only ever legal directly after `virtual`.
if was_virtual && self.cur().is_kw("interface") {
qualifiers.push(self.bump().text);
}
} else {
break;
}
@@ -1394,6 +1745,18 @@ impl<'a> Parser<'a> {
fn parse_typedef(&mut self) -> PResult<Typedef> {
self.expect_kw("typedef")?;
if self.eat_kw("class") {
// Forward declaration: `typedef class my_class;` — no type to
// alias, just a name promised to exist later in the compilation.
let Name { text: name, span: name_span } = self.expect_name()?;
self.expect_sym(";")?;
return Ok(Typedef {
name,
name_span,
unpacked: Vec::new(),
kind: TypedefKind::ForwardClass,
});
}
if self.cur().is_kw("enum") {
self.bump();
let base = {
@@ -1955,6 +2318,11 @@ impl<'a> Parser<'a> {
// ------------------------------------------------------------------
fn parse_function(&mut self) -> PResult<FunctionDecl> {
let prefix = self.take_member_prefix();
// `extern` and `pure virtual` introduce a prototype: a header, a `;`,
// and no `endfunction`. The body is written elsewhere (or, for a pure
// virtual, nowhere at all).
let is_prototype = prefix.iter().any(|q| q == "extern" || q == "pure");
self.expect_kw("function")?;
let mut qualifiers = Vec::new();
while self.cur().is_kw("automatic") || self.cur().is_kw("static") {
@@ -1974,14 +2342,23 @@ impl<'a> Parser<'a> {
}
}
};
let Name { text: name, span: name_span } = self.expect_name()?;
// Out-of-body definitions of an `extern` method write the class name
// in front: `function void my_class::configure(...)`.
let (scope, Name { text: name, span: name_span }) = self.parse_method_name()?;
let has_parens = self.cur().is_sym("(");
let args = self.parse_tf_ports()?;
self.expect_sym(";")?;
let (stmts, dangling, end) = self.parse_tf_body("endfunction")?;
let (stmts, dangling, end) = if is_prototype {
(Vec::new(), Vec::new(), None)
} else {
self.parse_tf_body("endfunction")?
};
let (end_label, end_label_span) = split_label(end);
Ok(FunctionDecl {
prefix,
qualifiers,
is_prototype,
scope,
ret,
name,
name_span,
@@ -1995,19 +2372,28 @@ impl<'a> Parser<'a> {
}
fn parse_task(&mut self) -> PResult<TaskDecl> {
let prefix = self.take_member_prefix();
let is_prototype = prefix.iter().any(|q| q == "extern" || q == "pure");
self.expect_kw("task")?;
let mut qualifiers = Vec::new();
while self.cur().is_kw("automatic") || self.cur().is_kw("static") {
qualifiers.push(self.bump().text);
}
let Name { text: name, span: name_span } = self.expect_name()?;
let (scope, Name { text: name, span: name_span }) = self.parse_method_name()?;
let has_parens = self.cur().is_sym("(");
let args = self.parse_tf_ports()?;
self.expect_sym(";")?;
let (stmts, dangling, end) = self.parse_tf_body("endtask")?;
let (stmts, dangling, end) = if is_prototype {
(Vec::new(), Vec::new(), None)
} else {
self.parse_tf_body("endtask")?
};
let (end_label, end_label_span) = split_label(end);
Ok(TaskDecl {
prefix,
qualifiers,
is_prototype,
scope,
name,
name_span,
has_parens,
@@ -2304,6 +2690,13 @@ impl<'a> Parser<'a> {
}
"disable" => {
self.bump();
// `disable fork;` kills every process the enclosing `fork`
// started; `fork` is a keyword, not a block name.
if self.cur().is_kw("fork") {
self.bump();
self.expect_sym(";")?;
return Ok(StmtKind::Disable("fork".to_string()));
}
let mut name = self.expect_ident()?;
while self.cur().is_sym(".") {
self.bump();
@@ -2362,9 +2755,12 @@ impl<'a> Parser<'a> {
let d = self.parse_port_decl()?;
Ok(StmtKind::PortDecl(d))
}
// `virtual` here is a local variable of virtual-interface type
// (`virtual my_if h;`), the only class-member qualifier that can
// also start a statement.
_ if NET_KEYWORDS.contains(&kw.as_str())
|| TYPE_KEYWORDS.contains(&kw.as_str())
|| matches!(kw.as_str(), "var" | "automatic" | "static" | "const") =>
|| matches!(kw.as_str(), "var" | "automatic" | "static" | "const" | "virtual") =>
{
// A type keyword followed by `'` is a cast expression, not a
// declaration.
@@ -2444,7 +2840,15 @@ impl<'a> Parser<'a> {
while self.tokens.get(p + 1).is_some_and(|t| t.is_sym("::")) {
p += 2;
}
let next = &self.tokens[(p + 1).min(self.tokens.len() - 1)];
let mut n = p + 1;
// `item #(A, B) req;` declares a variable of a parameterized type;
// the overrides sit between the type name and the declarator.
if self.tokens.get(n).is_some_and(|t| t.is_sym("#"))
&& self.tokens.get(n + 1).is_some_and(|t| t.is_sym("("))
{
n = self.scan_matching(n + 1, "(", ")");
}
let next = &self.tokens[n.min(self.tokens.len() - 1)];
if next.kind == TokenKind::Ident {
let d = self.parse_data_decl()?;
return Ok(StmtKind::VarDecl(d));
@@ -2722,7 +3126,15 @@ impl<'a> Parser<'a> {
}
/// True if the current token continues a postfix chain.
fn at_postfix_segment(&self) -> bool {
///
/// `base` is what has been parsed so far: a `#( ... )` only continues a
/// *name* (`uvm_config_db#(virtual bus_if)::get(...)`), never an arbitrary
/// expression, so `x #(y)` after anything else stays what it was.
fn at_postfix_segment(&self, base: &Expr) -> bool {
if self.at_type_params() && matches!(base.kind, ExprKind::Ident(_) | ExprKind::Scope { .. })
{
return true;
}
let t = self.cur();
t.is_sym(".")
|| t.is_sym("::")
@@ -2745,13 +3157,17 @@ impl<'a> Parser<'a> {
fn parse_postfix_inner(&mut self) -> PResult<Expr> {
let mut expr = self.parse_primary()?;
while self.at_postfix_segment() {
while self.at_postfix_segment(&expr) {
self.link()?;
// Every segment wraps what came before, so each new node starts
// where the expression so far started.
let start = expr.span.start;
let t = self.cur();
if t.is_sym(".") {
if t.is_sym("#") {
let params = self.parse_type_params()?;
expr =
self.expr_at(start, ExprKind::Parameterized { base: Box::new(expr), params });
} else if t.is_sym(".") {
self.bump();
let name = self.expect_ident()?;
expr = self.expr_at(start, ExprKind::Member { base: Box::new(expr), name });
@@ -2963,7 +3379,7 @@ mod tests {
fn parse_ok(src: &str) -> SourceFile {
let toks = tokenize(src).expect("lex error");
match parse(toks) {
match parse(toks, src) {
Ok(f) => f,
Err(e) => panic!("parse error in {src:?}: {e}"),
}
@@ -2976,7 +3392,7 @@ mod tests {
fn parse_deep(src: String) -> PResult<SourceFile> {
std::thread::Builder::new()
.stack_size(16 * 1024 * 1024)
.spawn(move || parse(tokenize(&src).expect("lex error")))
.spawn(move || parse(tokenize(&src).expect("lex error"), &src))
.expect("spawn parser thread")
.join()
.expect("parser thread crashed")
@@ -3612,7 +4028,7 @@ mod tests {
// elements. One written mid-declaration is out of scope by design;
// this pins that it is refused rather than half-parsed.
let src = "module m (\n input\n`ifdef X\n logic\n`endif\n a\n);\nendmodule\n";
assert!(parse(tokenize(src).expect("lex error")).is_err());
assert!(parse(tokenize(src).expect("lex error"), src).is_err());
}
fn instantiation_of(file: &SourceFile) -> &Instantiation {
@@ -3739,7 +4155,7 @@ mod tests {
// scope by design; this pins that it is refused rather than half-read.
let src =
"module m;\n sub u (\n .a(\n`ifdef X\n y\n`endif\n )\n );\nendmodule\n";
assert!(parse(tokenize(src).expect("lex error")).is_err());
assert!(parse(tokenize(src).expect("lex error"), src).is_err());
}
/// The strict entry point keeps its contract: it fails at the *first*
@@ -3748,10 +4164,173 @@ mod tests {
#[test]
fn strict_parsing_still_stops_at_the_first_error() {
let src = "module m;\n wire a\n wire b;\n wire c\nendmodule\n";
let err = parse(tokenize(src).expect("lex error")).expect_err("strict must refuse");
let err = parse(tokenize(src).expect("lex error"), src).expect_err("strict must refuse");
let (_, diags) = crate::parse_source_tolerant(src);
assert_eq!(diags.len(), 2, "tolerant mode reports both");
assert_eq!(err.message, diags[0].message);
assert_eq!((err.line, err.col), (diags[0].line, diags[0].col));
}
fn class_of(file: &SourceFile) -> &ClassDecl {
let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") };
c
}
#[test]
fn class_header_parts_are_kept_apart() {
let f = parse_ok(
"virtual class c #(parameter int W = 8) extends pkg::base #(.A(1), b) \
implements i, j;\nendclass : c\n",
);
let c = class_of(&f);
assert_eq!(c.prefix, ["virtual"]);
assert_eq!(c.name, "c");
assert_eq!(c.param_ports.as_ref().expect("a parameter port list").len(), 1);
let ext = c.extends.as_ref().expect("an extends clause");
assert_eq!(ext.name, "pkg::base");
let params = ext.params.as_ref().expect("base parameter overrides");
assert_eq!(params.len(), 2);
assert_eq!(params[0].name, "A");
// An ordered override has no name, only an expression.
assert_eq!(params[1].name, "");
assert_eq!(c.implements.iter().map(|n| n.text.as_str()).collect::<Vec<_>>(), ["i", "j"]);
assert_eq!(c.end_label.as_deref(), Some("c"));
}
#[test]
fn class_bodies_hold_ordinary_items() {
let f = parse_ok(
"class c;\n `M(x)\n`ifdef Y\n int a;\n`endif\n typedef int t;\n \
localparam int W = 1;\n import p::q;\n rand bit [3:0] r;\nendclass\n",
);
let kinds: Vec<&str> = class_of(&f)
.items
.iter()
.map(|i| match &i.kind {
ItemKind::MacroItem(_) => "macro",
ItemKind::Directive(_) => "directive",
ItemKind::Typedef(_) => "typedef",
ItemKind::ParamDecl(_) => "param",
ItemKind::Import(_) => "import",
ItemKind::DataDecl(_) => "data",
_ => "other",
})
.collect();
assert_eq!(
kinds,
["macro", "directive", "data", "directive", "typedef", "param", "import", "data"]
);
}
#[test]
fn member_qualifiers_land_on_the_construct_they_qualify() {
let f = parse_ok(
"class c;\n local rand int a;\n pure virtual function void g();\n \
extern task t(int x);\n protected virtual task automatic u();\n endtask\nendclass\n",
);
let items = &class_of(&f).items;
let ItemKind::DataDecl(d) = &items[0].kind else { panic!("expected a declaration") };
assert_eq!(d.qualifiers, ["local", "rand"]);
let ItemKind::Function(g) = &items[1].kind else { panic!("expected a function") };
assert_eq!(g.prefix, ["pure", "virtual"]);
assert!(g.is_prototype && g.stmts.is_empty());
let ItemKind::Task(t) = &items[2].kind else { panic!("expected a task") };
assert_eq!(t.prefix, ["extern"]);
assert!(t.is_prototype);
let ItemKind::Task(u) = &items[3].kind else { panic!("expected a task") };
assert_eq!(u.prefix, ["protected", "virtual"]);
assert_eq!(u.qualifiers, ["automatic"]);
assert!(!u.is_prototype);
}
#[test]
fn an_out_of_body_method_keeps_its_class_scope_apart_from_its_name() {
let f = parse_ok("function void my_class::configure(int x);\nendfunction\n");
let ItemKind::Function(g) = &f.items[0].kind else { panic!("expected a function") };
assert_eq!(g.scope.as_deref(), Some("my_class"));
assert_eq!(g.name, "configure");
}
#[test]
fn constraints_and_covergroups_are_captured_verbatim() {
let src = "class c;\n constraint x {\n a == 0; // why\n }\n \
covergroup g;\n coverpoint a;\n endgroup : g\nendclass\n";
let f = parse_ok(src);
let items = &class_of(&f).items;
let ItemKind::Verbatim(a) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(a.text, "constraint x {\n a == 0; // why\n }");
assert_eq!(a.text, src[a.span.as_range()]);
let ItemKind::Verbatim(b) = &items[1].kind else { panic!("expected a verbatim block") };
assert_eq!(b.text, "covergroup g;\n coverpoint a;\n endgroup : g");
}
#[test]
fn a_comment_after_a_verbatim_block_stays_outside_it() {
// The comment is written past the block's last token, so it must not
// be swallowed by the capture *or* dropped from the plumbing.
let f =
parse_ok("class c;\n constraint x {\n a == 0;\n } // why\n int b;\nendclass\n");
let items = &class_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(!raw.text.contains("why"), "the capture swallowed the comment: {:?}", raw.text);
assert_eq!(items[0].meta.trailing.as_ref().expect("the comment survived").text, "// why");
}
#[test]
fn a_parameterized_type_is_a_declaration_and_a_parameterized_module_is_an_instance() {
let f =
parse_ok("module m;\n port_t #(bit [3:0]) p;\n sub #(.W(8)) u (.a(a));\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") };
assert_eq!(d.ty.name, "port_t");
assert_eq!(d.ty.params.as_ref().expect("type parameters").text, "#(bit [3:0])");
assert!(matches!(m.items[1].kind, ItemKind::Instantiation(_)));
}
#[test]
fn a_parameterized_class_reference_is_one_expression_segment() {
let f = parse_ok("class c;\n function void f();\n \
x = uvm_config_db#(virtual bus_if)::get(this);\n endfunction\nendclass\n");
let ItemKind::Function(g) = &class_of(&f).items[0].kind else {
panic!("expected a function")
};
let StmtKind::Assign { rhs, .. } = &g.stmts[0].kind else {
panic!("expected an assignment")
};
// call( scope( parameterized( ident ) ) )
let ExprKind::Call { callee, .. } = &rhs.kind else { panic!("expected a call") };
let ExprKind::Scope { base, name } = &callee.kind else { panic!("expected a scope") };
assert_eq!(name, "get");
let ExprKind::Parameterized { base, params } = &base.kind else {
panic!("expected a parameterized reference")
};
assert_eq!(params.text, "#(virtual bus_if)");
assert!(matches!(&base.kind, ExprKind::Ident(n) if n == "uvm_config_db"));
}
#[test]
fn a_typedef_can_forward_declare_a_class() {
let f = parse_ok("typedef class c;\n");
let ItemKind::Typedef(t) = &f.items[0].kind else { panic!("expected a typedef") };
assert_eq!(t.name, "c");
assert!(matches!(t.kind, TypedefKind::ForwardClass));
}
#[test]
fn class_bodies_are_charged_against_the_nesting_budget() {
// Classes nest through `parse_item`, like modules and packages, so a
// pathologically nested file is a clean error rather than a crash.
let deep = |n: usize| {
let mut s = String::new();
for i in 0..n {
s.push_str(&format!("class c{i};\n"));
}
for _ in 0..n {
s.push_str("endclass\n");
}
s
};
assert!(parse_deep(deep(MAX_NESTING_DEPTH as usize - 1)).is_ok());
assert_too_deep(deep(MAX_NESTING_DEPTH as usize + 1));
}
}
+18
View File
@@ -207,6 +207,24 @@ pub fn is_keyword(s: &str) -> bool {
| "generate"
| "endgenerate"
| "genvar"
// Class-related reserved words. `new`, `this`, `super` and `null`
// are deliberately *not* here: they stand in expression position
// and already parse as ordinary names, so promoting them to
// keywords would break `x = new(...)` and `super.f()` for nothing.
| "class"
| "endclass"
| "extends"
| "implements"
| "virtual"
| "pure"
| "extern"
| "rand"
| "randc"
| "local"
| "protected"
| "constraint"
| "covergroup"
| "endgroup"
| "function"
| "endfunction"
| "task"
+45 -1
View File
@@ -59,6 +59,10 @@ const SOURCES: &[&str] = &[
"module m;\n sub #(\n`ifdef X\n .P(1),\n`endif\n .Q(2)\n ) u (\n .a(x),\n`ifndef Y\n .b(y),\n`endif\n .c(z)\n );\nendmodule\n",
// A list that is nothing but a directive, in both brackets.
"module m;\n sub #(\n`include \"config.vh\"\n ) u (\n`ifdef X\n`endif\n );\nendmodule\n",
// Classes: header parts, qualified members, prototypes, verbatim blocks.
"virtual class base #(parameter int W = 8) extends pkg::top #(.A(1), b) implements i, j;\n rand bit [W-1:0] v;\n local int n;\n virtual my_if h;\n pure virtual function void f();\n extern task t(int x);\nendclass : base\n",
"class c;\n port_t #(bit [3:0]) p;\n constraint x {\n a == 0; // why\n } // after\n covergroup g;\n coverpoint a;\n endgroup : g\n function new(string name);\n super.new(name);\n x = db#(virtual bus_if)::get(this);\n endfunction : new\nendclass\n",
"typedef class fwd;\npackage p;\n class inner extends fwd;\n endclass\nendpackage\nfunction void inner::configure(int x);\nendfunction\n",
];
/// A token or a comment, in source order.
@@ -530,6 +534,44 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
check_gen_block(src, &i.body, i.span);
}
}
ItemKind::Class(c) => {
check_name(src, "class name", &c.name, c.name_span, here);
check_opt_name(src, "endclass label", c.end_label.as_ref(), c.end_label_span, here);
check_names(src, "implemented interface", &c.implements, here);
for d in &c.param_directives {
assert_inside(src, "list directive", d.raw.span, here);
}
for p in c.param_ports.iter().flatten() {
assert_inside(src, "class parameter port", p.span, here);
check_name(src, "class parameter port name", &p.name, p.name_span, p.span);
check_opt_expr(src, p.default.as_ref(), p.span);
}
if let Some(ext) = &c.extends {
assert_inside(src, "extends clause", ext.span, here);
// A scope-qualified base name (`pkg::base`) is stored with its
// `::` glued, so the slice matches it modulo that whitespace.
assert_inside(src, "base class name", ext.name_span, ext.span);
assert_eq!(
despace(slice(src, ext.name_span)),
despace(&ext.name),
"the base class span does not slice back to its name"
);
for d in &ext.param_directives {
assert_inside(src, "list directive", d.raw.span, ext.span);
}
for c in ext.params.iter().flatten() {
assert_inside(src, "base parameter override", c.span, ext.span);
check_name(src, "base parameter override name", &c.name, c.name_span, c.span);
check_opt_expr(src, c.expr.as_ref(), c.span);
}
}
for item in &c.items {
check_item(src, item, here);
}
}
// A `constraint`/`covergroup` block: one verbatim leaf whose span is
// the item's own, checked above.
ItemKind::Verbatim(_) => {}
ItemKind::Function(f) => {
check_name(src, "function name", &f.name, f.name_span, here);
check_opt_name(src, "endfunction label", f.end_label.as_ref(), f.end_label_span, here);
@@ -726,7 +768,9 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
check_expr(src, msb, here);
check_expr(src, lsb, here);
}
ExprKind::Member { base, .. } | ExprKind::Scope { base, .. } => check_expr(src, base, here),
ExprKind::Member { base, .. }
| ExprKind::Scope { base, .. }
| ExprKind::Parameterized { base, .. } => check_expr(src, base, here),
ExprKind::Concat(items) | ExprKind::Inside { ranges: items, .. } => {
for i in items {
assert_inside(src, "element", i.span, here);
+17 -1
View File
@@ -229,7 +229,14 @@ impl<'a> Binder<'a> {
ItemKind::Directive(_)
| ItemKind::MacroItem(_)
| ItemKind::Timeunit(_)
| ItemKind::Error(_) => {}
| ItemKind::Error(_)
| ItemKind::Verbatim(_) => {}
// Classes are parsed and formatted but deliberately not modelled
// here: their scoping rules (inheritance, `this`/`super`, static
// vs. instance members) are a separate design question, and a
// half-model would resolve names wrongly rather than not at all.
// See `docs/features/classes/README.md`.
ItemKind::Class(_) => {}
}
}
@@ -352,6 +359,12 @@ impl<'a> Binder<'a> {
}
}
}
// `typedef class c;` promises a class this crate does not model
// (see `ItemKind::Class` above); the name is still declared, so a
// reference to it resolves to the forward declaration.
TypedefKind::ForwardClass => {
self.declare(scope, &t.name, SymbolKind::Typedef, ns, span);
}
}
self.bind_dims(&t.unpacked, scope);
}
@@ -734,6 +747,9 @@ impl<'a> Binder<'a> {
// `a.b`: only the head is resolved — see the README.
ExprKind::Member { base, .. } => self.bind_expr(base, scope),
ExprKind::Scope { base, name } => self.bind_scoped(base, name, e.span, scope),
// The `#( ... )` is verbatim text this crate makes no claims
// about; the name it parameterizes is still an ordinary use.
ExprKind::Parameterized { base, .. } => self.bind_expr(base, scope),
ExprKind::Concat(items) => {
for i in items {
self.bind_expr(&i.expr, scope);
+753
View File
@@ -0,0 +1,753 @@
# classes
## Goal
Parse and format SystemVerilog `class` declarations well enough to unblock the
DV half of the corpus. `docs/features/corpus-check/README.md` measured
`extends` as the single largest remaining blocker after macro-items — **142 of
820 files**, all of them UVM/DV under `ibex/dv/`, `ibex/vendor/lowrisc_ip/dv/`,
`ibex/vendor/google_riscv-dv/` and `opentitan/hw/ip/uart/dv/`. The design point
is deliberately split: the *shape* of a class (header, `extends`, members,
methods) is a real AST that gets canonical layout, while the two sublanguages a
class body can contain — constraints and covergroups — are captured **verbatim**
by span, exactly the way `` `define`` and macro invocations already are.
Formatting them would mean modelling a second grammar with no payoff and real
corruption risk.
## What is structural, and what is verbatim
Every choice below was made from real corpus files, named here so the next
reader can check the evidence rather than the reasoning.
### Structural (parsed, laid out canonically)
| construct | corpus evidence |
|---|---|
| `class c;` … `endclass[: c]` | everywhere |
| `virtual class c;` | `lowrisc_ip/dv/sv/push_pull_agent/push_pull_driver_lib.sv:85`, `dv_utils/dv_vif_wrap.sv:13` |
| `class c #(parameter int W = 32, ...)` | `push_pull_driver_lib.sv:16` |
| `extends base` | `ibex_icache_core_agent_cfg.sv:5` |
| `extends pkg::base` | scope-qualified bases in `core_ibex_*` |
| `extends base #(.A(x), .B(y))` (named overrides) | `ibex_icache_core_driver.sv:6-8`, `uart_env.sv:5` |
| `extends base #(x)` (ordered overrides) | `ibex_icache_core_agent_cov.sv:5` |
| `implements a, b` | not in the corpus; two lines of grammar, taken for completeness |
| properties with `rand`/`randc`/`local`/`protected`/`static`/`const` | `ibex_icache_core_req_item.sv:8-26` |
| `virtual my_if vif;` / `virtual interface my_if vif;` | `ibex_icache_core_agent_cfg.sv:8` |
| parameterized property types (`uvm_analysis_port #(bit [31:0]) p;`) | `ibex_icache_core_driver.sv:15`, `push_pull_driver_lib.sv:24` |
| `function` / `task`, with `virtual`/`static`/`local`/`protected`/`automatic` | `ibex_icache_core_driver.sv:17-27` |
| `function new(...)` | `ibex_icache_env_cov.sv:21` |
| `endfunction : name` / `endtask : name` | `ibex_icache_env_cov.sv:24` |
| `pure virtual function/task ...;` prototypes | `push_pull_driver_lib.sv:96-102` |
| `extern function/task ...;` prototypes | `dv_base_reg/dv_base_mem.sv:24-46` |
| out-of-body definitions (`function void dv_base_mem::configure(...)`) | `dv_base_mem.sv` |
| `typedef class c;` forward declarations | `push_pull_driver_lib.sv:5-9`, `core_ibex_test_pkg.sv:28` |
| parameterized class references in expressions (`uvm_config_db#(virtual bus_if)::get(...)`) | `ibex_icache_core_agent.sv:20`, `push_pull_driver_lib.sv:34` |
| `disable fork;` | `ibex_icache_core_driver.sv:81` |
| `typedef`, `localparam`, `import`, directives, macro items in a class body | `push_pull_driver_lib.sv:112` (`` `define`` inside a class) |
Class bodies are **item lists**. `parse_class` runs the same
`item_or_recover()` loop a module or package body runs, so everything the item
machinery already supports — `Meta` comments, blank-line preservation,
`` `ifdef`` at item position, macro items, nested classes — works inside a
class without a line of per-site code.
### Verbatim (captured by span, reproduced byte for byte)
| construct | why | corpus evidence |
|---|---|---|
| `constraint c { ... }` | the constraint language is its own grammar — `dist { 0 :/ 5, [1:20] :/ 20 }`, `->` implication, `solve x before y`, `inside`, `foreach`, `if`/`else`. None of it appears anywhere else in vfmt, and there is no layout convention worth inventing for it. | `ibex_icache_core_req_item.sv:28-62` (five blocks, all four of those forms) |
| `covergroup ... endgroup[: label]` | same argument: `coverpoint`, `cross`, `bins`/`ignore_bins`/`illegal_bins`, `binsof ... intersect`, `with function sample`. | `ibex_icache_core_agent_cov.sv:17-46`, `uart_env_cov.sv:8-55` |
| the `#( ... )` of a parameterized **type** reference | its arguments are types as often as expressions (`#(virtual ibex_icache_core_if)`, `#(push_pull_item #(A, B))`), so `parse_expr` cannot represent them. | `push_pull_driver_lib.sv:20-24`, `ibex_icache_core_driver.sv:15` |
`randsequence` is **not** handled: `grep -rn randsequence corpus` finds zero
occurrences in all four repos. Adding a verbatim capture for a construct the
corpus does not contain would be building for a user that does not exist.
Verbatim capture reuses the existing `RawText { text, col, span }` leaf and the
`recover()` pattern that error-recovery already established: skip the tokens,
slice `source[span]`, drop the trivia copies the skip made. This is why
`vlog_parser::parse` now takes the source text (see Handshakes).
## Assumptions
- **The class body is an item list, not a member list.** SystemVerilog's
`class_item` production overlaps almost exactly with what vfmt already
accepts at module scope, so the alternative — a separate `ClassItem` enum —
would have duplicated a dozen variants to gain nothing. The cost is that a
construct only legal at module scope (`always_ff`, an instantiation) parses
inside a class instead of being rejected. vfmt is a formatter, not a
compiler; it does not check legality anywhere else either.
- **A verbatim block's *relative* layout is what survives, not its absolute
layout.** `raw_lines` dedents continuation lines by `col - 1` and the
printer re-indents them, so a `constraint` written entirely at column 1
stays flush with its own opening line after the block is indented into the
class body. This is the same contract multi-line macro invocations have had
since macro-items, and it is what makes the second pass a fixed point.
- **Verbatim `#( ... )` type parameters are emitted with *no* re-indent at
all.** They do not begin the line they are printed on, so the
dedent-by-column trick cannot converge — the dedent has to cancel an indent
the printer adds back, and mid-line there is none. `Fmt::raw_inline` emits
the text unchanged, which is idempotent by construction. A multi-line
`#( ... )` therefore keeps its original absolute alignment even if the line
it hangs off moves. Found by the corpus, not predicted:
`dv_base_reg/dv_base_mubi_cov.sv:63` is a `typedef mubi_cov #(...)` split
over three lines, and the dedent path drifted left on every pass.
- **`class`, `endclass`, `extends`, `implements`, `virtual`, `pure`, `extern`,
`rand`, `randc`, `local`, `protected`, `constraint`, `covergroup` and
`endgroup` are reserved words** and are safe to promote to keywords. Every
one is reserved by IEEE 1800; a file using one as an identifier is not legal
SystemVerilog. Confirmed empirically: the corpus re-run shows **zero** files
regressing.
- **`new`, `this`, `super` and `null` are deliberately *not* keywords.** They
stand in expression position, where they already parse as ordinary names:
`analysis_port = new("analysis_port", this)` is a call, `super.new(...)` a
member access. Promoting them would have broken working code to gain
nothing.
- **A one-token lookahead distinguishes a parameterized-type declaration from
an instantiation.** `port_t #(int) p;` and `sub #(.W(8)) u (...);` open
identically; what follows the name after the overrides decides — a `(` or
`[` means an instance, anything else a declaration. The corpus contains both
shapes and no counterexample. A wrong guess cannot corrupt: both readings
emit the same tokens in the same order, so the safety net still passes and
only the layout would differ.
- **`#( ... )` continues a postfix chain only after a *name*.** `at_postfix_segment`
accepts it when the expression so far is an `Ident` or a `Scope`, so
`uvm_config_db#(...)::get` parses while nothing else in the expression
grammar changes meaning.
- **Class members are not semantically analysed.** See the `vlog_semantic`
handshake below.
## Handshakes
**Changed, and every caller updated: `vlog_parser::parse` now takes the
source text.**
```rust
pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile>
```
It previously took only the tokens and passed `""` for the source, because
only error-recovery (a tolerant-mode-only path) read it. The verbatim class
blocks read it in **strict** mode, which is the mode the formatter uses, so
"strict mode has no source" had to go. Making the parameter mandatory rather
than optional is deliberate: a `parse()` that silently produced empty verbatim
text would be a corruption bug, and the type system now makes it unreachable.
`parse_source` / `parse_source_tolerant` are unchanged; they were the only
callers.
**Promised to `vlog_formatter`:**
- `ItemKind::Class(ClassDecl)` — header parts kept apart (`prefix`,
`lifetime`, `name`/`name_span`, `param_ports` + `param_directives` +
`param_dangling`, `extends`, `implements`, `items`, `dangling`,
`end_label`), so the formatter lays each out with the machinery it already
has: `param_port` for the parameter ports, `connection` for the `extends`
overrides, `item_seq` for the body, `Self::closing` for the footer.
- `ClassExtends { name, name_span, param_comments, params, param_directives,
span }` — `params` is a `Vec<Connection>`, the same node an instantiation's
`#( ... )` overrides use, because both spell named and ordered overrides the
same way.
- `ItemKind::Verbatim(RawText)` — one leaf for both `constraint` and
`covergroup`. `raw.col` is load-bearing exactly as it is for macro items:
it is what `Fmt::raw_lines` dedents continuation lines by.
- `DataType::params: Option<Box<RawText>>` and
`ExprKind::Parameterized { base, params }` — both verbatim, both printed
through `Fmt::raw_inline` (no re-indent). Boxed in `DataType` to keep
`ExprKind::Type` — and through it every `Expr` — small; without the box
clippy's `large_enum_variant` fires on `ItemKind`.
- `FunctionDecl` / `TaskDecl` gained `prefix: Vec<String>` (the qualifiers
written *before* the keyword), `is_prototype: bool` (no body, no
`endfunction`), and `scope: Option<String>` (the `my_class::` of an
out-of-body definition). `scope` is kept apart from `name` so
`src[name_span] == name` still holds, which is the `name-spans` contract
`vlog_semantic` depends on — gluing them broke ten symbols in
`dv_base_mem.sv` and was caught by that crate's corpus test.
- `TypedefKind::ForwardClass` for `typedef class c;`.
**Consumed from / required of `vlog_semantic` (minimal, documented):**
`bind.rs`'s `ItemKind` and `TypedefKind` matches are exhaustive, so the new
variants had to be answered or the crate would not compile. The minimum was
added and nothing more:
- `ItemKind::Class(_) => {}` and `ItemKind::Verbatim(_) => {}` — classes are
parsed and formatted but not modelled. Their scoping rules (inheritance,
`this`/`super`, static vs. instance members, `::` into a class) are a
separate design question, and a half-model would resolve names *wrongly*
rather than not at all.
- `TypedefKind::ForwardClass` declares the name and nothing else, so a
reference to a forward-declared class still resolves.
- `ExprKind::Parameterized { base, .. }` binds the base name and ignores the
verbatim `#( ... )`.
Consequence, stated plainly: **no name declared inside a class body is
indexed, hovered or navigable.** That is a real LSP gap, not an oversight, and
it is the natural next round for that crate.
**Requested of `vlog_formatter::fence` (out of this feature's scope):**
`scan_nested` enumerates the item scopes a fence can live in — module,
package, generate region, generate `if`/`for`/`case` — and ends in a `_ => {}`
catch-all, so a class body is not scanned. Probed and confirmed:
```systemverilog
class c;
// verilog_format: off
int a = 1; // ← re-formatted anyway
// verilog_format: on
endclass
```
is formatted normally, while the identical shape inside a `module` is left
verbatim. The fix is one arm —
`ItemKind::Class(c) => scan_scope(src, &c.items, &c.dangling, out)` — but
`fence.rs` was explicitly outside this round's scope, so it is filed here
rather than done. Nothing is corrupted by the gap; the fence is simply
inactive.
**Requested of `vlog_linter` (same shape, lower stakes):** `visit.rs`'s
`items()` walk has a `_ => {}` arm too, so the four **AST-walking** rules
(`case-missing-default`, `always-ff-non-blocking`, `always-comb-blocking`,
`explicit-parameter-storage-type`) do not see class members — a
`case-missing-default` inside a class method will not fire. The
**line/file-based** rules (`no-tabs`, `no-trailing-whitespace`,
`module-filename`, `unused-waiver`) still fire inside class bodies as
normal (QA-verified by probe; wording sharpened by the lead per the QA
log). The walk is additive-compatible — the crate compiles unchanged —
so this is a coverage gap, not a break.
**Requested of `macro-items` (refined here, one line):** `at_macro_item`'s
"next token is a plain identifier" arm now also treats the invocation as
standalone when that identifier is followed by `#(`. Real UVM writes
```systemverilog
`uvm_component_new
uvm_analysis_port #(bit [31:0]) analysis_port;
```
and the old rule read `` `uvm_component_new `` as a *type* and
`uvm_analysis_port` as its declarator, then failed at the `#`. The new clause
cannot regress anything: the old reading was already a parse error, and the
"both readings emit the same tokens" safety property is unchanged.
**Recursion/chain budgets (`docs/features/recursion-limit/README.md`):** no new
budget and none needed. `parse_class` is reached through `parse_item`, which
already charges `enter()`/`leave()`, and its body loop calls
`item_or_recover()` → `parse_item`, so nested classes are charged exactly like
nested packages. Pinned by
`class_bodies_are_charged_against_the_nesting_budget`: 63 nested classes parse,
65 are a clean `nesting too deep (limit 64)` error. The verbatim scans
(`skip_balanced`, the `covergroup` scan) are flat loops over the token vector,
not recursion. `ExprKind::Parameterized` is a postfix segment and charges
`link()` like every other one.
**`verify.rs` is untouched.** No normalization was added, broadened or
weakened, so CLAUDE.md hard invariant #4 does not strictly apply — but the
verbatim capture is new forgiveness-adjacent machinery, so it ships with the
attack tests anyway (see Status/TODO). The reason none was needed is worth
stating: a verbatim block is re-lexed as *ordinary tokens* on both sides, not
as one opaque token, so any changed byte inside it that is not inter-token
whitespace already diverges. And a string literal spanning a line break inside
a constraint is caught by the pre-existing `crosses_line_inside_string` guard
in `Fmt::raw_text`, which emits such a token with no re-indent at all.
## Design notes
### One dispatch for every member qualifier
A run of `virtual` / `pure` / `extern` / `local` / `protected` / `rand` /
`randc` / `static` / `automatic` / `const` / `var` does not say what it
qualifies; the first keyword *past* the run does. `Parser::member_head` walks
that run **without consuming**, and `parse_keyword_item` dispatches on what it
finds — `class`, `function`, `task`, `constraint`, `covergroup`, or (the
default) a data declaration. Each branch then consumes the qualifiers itself
via `take_member_prefix`. The alternative, consuming the run up front and
passing it down, needs every callee to accept a `Vec<String>` it may not want,
and gets `virtual interface my_if h;` wrong (the `interface` is part of the
qualifier, and only after `virtual`).
This also folded the pre-existing `var`/`automatic`/`static`/`const` arm into
the same path, so `static function` and `static constraint` work for free.
### A blank continuation line ends a `` `define`` (lexer bug, found by the corpus)
`dv_utils/dv_vif_wrap.sv:72` is a `` `define`` whose last body line ends in
`\` and is followed by a blank line and then a comment. The lexer *consumed*
the newline before the blank line and then trimmed the text back to the last
`\`, so the attachment phase saw one newline instead of two and the comment
lost its `blank_before` flag. The formatter then printed the comment directly
under a line ending in `\`, and the re-lexed output had the directive
swallowing the comment — a genuine equivalence failure, caught by the safety
net.
The fix is in the lexer's continuation loop: a blank continuation line is
*not* part of the directive, so the position is restored before the newline
that would have been consumed and the gap keeps both newlines. This is a
pre-existing bug — it reproduces on a file with no class syntax in it
(`` `define A \ `` ⏎ ` x \ ` ⏎ ⏎ `// c`) — that this feature merely made
reachable, and it is fixed here because the alternative was shipping a
non-zero verification-error count.
## Status / TODO
- [x] Keywords: 14 class-related reserved words, with `new`/`this`/`super`/
`null` deliberately excluded and the reason recorded in `token.rs`.
- [x] AST: `ClassDecl`, `ClassExtends`, `ItemKind::Class`,
`ItemKind::Verbatim`, `TypedefKind::ForwardClass`, `DataType::params`,
`ExprKind::Parameterized`, `FunctionDecl`/`TaskDecl` `prefix` /
`is_prototype` / `scope`.
- [x] Parser: `parse_class`, `parse_class_extends`, `parse_constraint`,
`parse_covergroup`, `skip_balanced`, `verbatim_since`, `member_head`,
`take_member_prefix`, `parse_method_name`, `parse_type_params`.
- [x] `parse_param_port_list` extracted from `parse_module` so module and
class headers share one parse (no duplicated list machinery).
- [x] Formatter: `Fmt::class`, `Fmt::raw_inline`, prototype and `scope`
handling in `function`/`task`, `DataType::params` in `data_type`.
- [x] `parse` takes the source; `slice()` is meaningful in strict mode.
- [x] Lexer: a blank continuation line ends a `` `define`` and stays a blank
line (pre-existing bug, see Design notes).
- [x] 38 cases in `crates/vlog_formatter/tests/cases/classes.cases`.
- [x] 10 parser unit tests, 2 lexer unit tests.
- [x] 11 verification tests in `tests/verification.rs` — the invariant-#4
attack set for the verbatim capture: a changed constraint expression, a
dropped constraint line, a dropped comment inside a constraint, a
re-indented string inside a constraint, a changed covergroup bin, a
dropped `endgroup` label, a changed `#( ... )` type argument, a dropped
`endclass` label and a dropped method qualifier are all asserted
**rejected**; a plain re-indent is asserted **accepted** (so the tests
are not vacuous).
- [x] Spans: three class sources added to `tests/spans.rs`'s `SOURCES`, and
`check_item` gained arms for `ItemKind::Class` (name, end label,
`implements` names, parameter ports, the `extends` clause and its
overrides, and every body item recursively) and `ItemKind::Verbatim`.
- [x] Corpus re-run: 0 regressions, 0 verification errors, 0 crashes.
- [x] `README.md` roadmap item 2 struck and supported-syntax updated.
- [ ] **Not done, deliberately:** semantic analysis of classes. See the
`vlog_semantic` handshake — an inheritance-aware scope model is its own
round, and a half-model resolves names wrongly.
- [ ] **Not done, deliberately:** canonical layout for constraint and
covergroup bodies. Two grammars, no layout convention worth inventing,
and the verbatim path is corruption-proof by construction.
- [ ] **Not done, out of scope:** fences inside class bodies (`fence.rs`, one
arm) and lint-rule coverage of class members (`visit.rs`, one arm).
Both filed under Handshakes.
- [ ] **Not done:** `` `uvm_field_int (x, y)`` — a macro invocation with a
space before its `(`. Ten of the 70 still-blocked ex-`extends` files die
on this, and it is the documented `macro-items` gap (their Assumptions,
2026-08-19), whose fix belongs in the lexer and has a known side effect
in expression position. Not this feature's to make.
## Corpus results
`./tools/corpus_check.sh corpus` over the same pinned 820-file corpus. All four
repos verified unmodified afterwards (`git status --porcelain` clean apart from
the pre-existing untracked `.vfmt-corpus-rev` stamps).
| metric | before | after |
|---|---|---|
| **parsed & formattable** | 476/820 (**58.0%**) | 578/820 (**70.5%**) |
| would-reformat | 468 | 568 |
| ok-unchanged (already clean) | 8 | 10 |
| parse-error | 344 (42.0%) | 242 (29.5%) |
| verification-error | 0 | **0** |
| crash | 0 | **0** |
```
outcome files share
-------------------- ----- -------
ok-unchanged 10 1.2%
would-reformat 568 69.3%
parse-error 242 29.5%
verification-error 0 0.0%
other-error 0 0.0%
crash 0 0.0%
-------------------- ----- -------
total 820 100.0%
```
**Diffed by path against the baseline TSV, not just by count:**
| transition | files |
|---|---|
| parse-error → would-reformat | 100 |
| parse-error → ok-unchanged | 2 |
| would-reformat → would-reformat | 468 |
| ok-unchanged → ok-unchanged | 8 |
| parse-error → parse-error | 242 |
| **any regression** | **0** |
102 files gained, **0 lost**, and no already-parsing file changed status in any
direction. Gained files by tree: `ibex/dv` 55, `ibex/vendor` 34,
`opentitan/hw` 11, `common_cells/test` 2.
**Honest reading of the numbers.**
- The corpus README predicted 142 files blocked on `extends`. **72 of those 142
now format**; the other **70 hit a second blocker**, which is exactly the
under-counting macro-items warned about. The remaining 30 of the 102 gained
files were blocked one token *earlier* than `extends` — 25 on the `#` of a
class parameter list or a parameterized type, and 5 on assorted shapes.
- **New first-blocker histogram for the 70 ex-`extends` files that are still
stuck**, which is the honest answer to "what is next":
| blocking token | files | what it is |
|---|---|---|
| `$` | 25 | queues — `bit x[$]`, `q[$] = {}` |
| `.` | 12 | named function arguments (`f(.arg(x))`) and `@hier.name` event control |
| `` `uvm_field_int `` | 9 | macro invocation with a space before `(` — the documented macro-items gap |
| `]` | 9 | dynamic arrays — `int q[]` |
| `inside` | 7 | `inside` used as a constraint/expression operator outside a constraint block |
| others (1 each) | 8 | `with`, `import` at statement position, assorted |
**34 of the 70 are queues and dynamic arrays** — README roadmap item 4,
untouched here by design. That, not classes, is now the top blocker.
- **Whole-corpus first-blocker histogram** after this round: `$` 41,
`interface` 25, `]` 23, `.` 21, `` `uvm_field_int `` 10, `inside` 7,
`"DPI-C"` 7, `'` 7, `$error` 6.
- **Verification errors stayed at 0.** Two appeared mid-round as files reached
the safety net for the first time, and both were fixed rather than
documented away: the `` `define``-blank-continuation lexer bug (Design
notes) and the mid-line verbatim re-indent drift (`Fmt::raw_inline`, see
Assumptions). Neither was caused by class syntax; both were caused by class
syntax letting the formatter reach code it had never seen.
- **Every formattable file was round-tripped**, not sampled: all 578 were
copied to a scratch directory, formatted in place and re-checked with
`--check`. All 578 are fixed points; none failed to format.
## Work log
### 2026-08-19 — dev agent
- Read `CLAUDE.md`, `README.md`, and the `macro-items`, `spans`,
`directives-in-lists` and `directives-in-instances` READMEs before touching
code. Baseline recorded first: `cargo test --workspace` **589 passed**,
clippy silent (0 warnings), fmt clean, corpus 476/820 formattable, 344
parse-error, 0 verification-error, 0 crash.
- **Read 15+ real corpus files before designing anything**, per the brief, and
let their shapes decide the split. Three things fell out of that reading that
I would not have guessed: (a) class parameter lists and `extends` override
lists are the *same* two list grammars module headers and instantiations
already have, so the machinery was reusable rather than new; (b) the DV
corpus leans on parameterized *type references* (`uvm_analysis_port #(...)`)
as heavily as on `extends`, which is why the `#` blocker at 40 files was
really part of this feature; (c) constraints and covergroups are big, common,
and completely disjoint from every grammar vfmt already has.
- **Chose verbatim for constraints and covergroups before writing a line of
parser.** The deciding argument is not effort but risk symmetry: a verbatim
block is re-lexed as ordinary tokens by the safety net, so a wrong byte is
caught, while a hand-rolled constraint grammar would be a new place to drop a
token that *looks* like formatting. The verbatim path also costs one AST leaf
instead of a dozen nodes.
- **Kept `new`, `this`, `super` and `null` as identifiers.** Adding them to the
keyword table was the obvious move and it is wrong: they only ever appear in
expression position, where the existing grammar already handles them, and
promoting them would have broken `x = new(...)` and `super.f()` to gain
nothing. Recorded in `token.rs` next to the list so the next person does not
re-add them.
- **`member_head` looks without consuming.** First attempt consumed the
qualifier run in `parse_keyword_item` and passed it down; that made every
callee take a `Vec<String>` and got `virtual interface my_if h;` wrong.
Rewrote it as a pure lookahead and let each construct consume its own prefix.
- **`parse` had to take the source.** Verbatim capture slices `source[span]`,
and strict mode was passing `""`. Made the parameter mandatory rather than
adding an optional variant: a `parse()` that silently produced empty verbatim
text is a corruption bug, and there was exactly one caller.
- **Comment plumbing for verbatim blocks was the one subtle part.** Copying
`recover()`'s `take_dangling()` would have been wrong — it also drains the
*next* token's leading comments, which are outside the block. Filtered by
span instead (`verbatim_since`), which drops exactly the comments inside the
block and keeps the one written after its closing brace on the same line.
Pinned by `a_comment_after_a_verbatim_block_stays_outside_it`.
- **Split the method scope out of the method name after `vlog_semantic`'s
corpus test failed.** First version stored `dv_base_mem::configure` in
`name`, following the `Instantiation::module` precedent. That precedent does
not apply: `vlog_semantic` re-derives `name_span` by scanning for identifier
*tokens*, and `a::b` is not one, so ten symbols in `dv_base_mem.sv` became
unplaceable. The fix is better design anyway — an LSP wants `configure`, not
the qualified spelling.
- **Two verification errors appeared at the corpus run and both were fixed, not
documented.** The first was a pre-existing lexer bug (`` `define`` with a
blank continuation line); reproduced it on a class-free input first to be
sure it was not mine, then fixed it in the continuation loop. The second was
mine: `raw_lines`'s dedent-by-column does not converge for text that starts
mid-line, which a three-line `typedef mubi_cov #(...)` exposed. Added
`raw_inline` for the mid-line case — idempotent by construction rather than
by argument, the same reasoning macro-items used for string-crossing tokens.
- **Removed `class` from `SYNC_OPENERS` after the tolerant-parse test caught
it.** I had added it by analogy with `package`, but unlike a module or a
package a class *nests*, so recovery stopping before one ended the enclosing
package body at the wrong place. The error-recovery suite's
"tolerant tree == strict tree" property found this within seconds, which is
the whole point of that test.
- **Boxed `DataType::params` because clippy asked.** Growing `DataType` grows
`ExprKind::Type`, which grows `Expr`, which grows `ItemKind::GenFor` past
`large_enum_variant`'s threshold. Verified the baseline was genuinely silent
before assuming the warning was mine.
- Corpus re-run diffed **by path** against the baseline TSV: 102 gained, 0
lost, 0 status changes among already-parsing files. Every one of the 578
formattable files was round-tripped through a real format + `--check`, not
sampled. All four corpus repos confirmed unmodified.
- Did not touch `verify.rs`, `fence.rs`, `tools/`, `corpus/`, `editors/`, or
the top-level release docs (a second agent is working there). The two
`vlog_semantic` arms are the documented minimum to keep the crate compiling.
Did not run `git commit` / `git push`.
- **TODO.md**: no checkbox matches this feature — the syntax-coverage roadmap
lives in `README.md`, which is updated. Added a corpus-delta annotation under
§5's corpus-check item, in the style the `directives-in-lists` round used,
leaving the item text intact.
**Results:** `cargo test --workspace` **612 passed, 0 failed** (up from 589:
+11 `vlog_formatter` verification, +10 `vlog_parser` parser unit, +2
`vlog_parser` lexer unit; the case table grew 359 → 397 cases inside its single
test). `cargo clippy --workspace --all-targets` silent, 0 warnings.
`cargo fmt --all --check` clean. Corpus: 578/820 formattable (70.5%, up from
476/58.0%), 242 parse-error (down from 344), **0 verification errors, 0
crashes, 0 regressions by path**; `tools/corpus_check.sh` exits 0.
Files touched: `crates/vlog_parser/src/{token,ast,lexer,parser,lib}.rs`,
`crates/vlog_parser/tests/spans.rs`,
`crates/vlog_formatter/src/format.rs`,
`crates/vlog_formatter/tests/verification.rs`,
`crates/vlog_formatter/tests/cases/classes.cases` (new),
`crates/vlog_semantic/src/bind.rs` (two skip arms, documented),
`README.md`, `TODO.md`, this README.
## QA log
### 2026-08-19 — QA agent
Read `CLAUDE.md`, this README (514 lines) and the full diff before touching
anything. All verification below was run against the working tree as handed
off (uncommitted); nothing was committed. Every sabotage described below was
reverted immediately after observing the result — confirmed by `git diff
--stat` matching the pre-sabotage numbers exactly and the full suite going
back to 612/612 green before moving on.
**Gates.** `cargo test --workspace`: **612 passed, 0 failed** (recount by
summing every `test result:` line, not trusted from the log alone).
`cargo clippy --workspace --all-targets`: silent, 0 warnings.
`cargo fmt --all --check`: clean. All three **PASS**, matching the claim.
**Corpus (claim 1).** Built the pre-feature parser/formatter in a separate
`git worktree` at HEAD (no stash, so the working tree was never disturbed)
and ran `tools/corpus_check.sh corpus` with both binaries against the same
pinned 820-file corpus, then diffed the two per-file TSVs **by path** in
Python (not just by count).
- Baseline: 476/820 formattable (58.0%), 344 parse-error, 0
verification-error, 0 crash — matches the README's "before" column exactly.
- After (working tree): 578/820 formattable (70.5%), 242 parse-error, 10
ok-unchanged, 568 would-reformat, 0 verification-error, 0 crash — matches
the README's "after" column exactly, including the whole-corpus blocker
histogram (`$` 41, `interface` 25, `]` 23, `.` 21, `` `uvm_field_int `` 10,
`inside` 7, `"DPI-C"` 7, `'` 7, `$error` 6 — all exact).
- By-path diff: parse-error→would-reformat 100, parse-error→ok-unchanged 2,
**0 files regressed in either direction**, 0 files changed status any other
way. Exact match to the claimed table.
- Re-derived the `extends`-blocked-142 breakdown independently (grepped the
baseline TSV for `found "extends"` diagnostics, then checked each of those
142 files' after-status): 72 now format, 70 still stuck, and the still-stuck
blocker histogram is `$` 25, `.` 12, `` `uvm_field_int `` 9, `]` 9, `inside`
7, others 8 (one each) — exact match, including the "34 of 70 are
queues/dynamic arrays" arithmetic (25+9).
- Round-tripped **all 578** formattable files (not sampled): copied each to a
scratch dir, `vfmt <file>` then `vfmt --check <file>`. **0 failures, 0
non-fixed-points.**
- Corpus repos confirmed unmodified: `git -C <repo> status --porcelain` clean
in all four (only the pre-existing untracked `.vfmt-corpus-rev` stamps),
before and after the round-trip.
- **Claim 1: PASS**, every number independently reproduced, not just
eyeballed against the README.
**randsequence (claim 3).** `grep -rln randsequence corpus` → 0 hits, all four
repos. **PASS.**
**Attack tests are real pins (claim 4).** Two sabotage experiments, both
reverted:
1. Weakened `Parser::verbatim_since` (`crates/vlog_parser/src/parser.rs`) to
drop the captured verbatim block's last content line. Result: `cargo test
-p vlog_formatter --test cases` failed on `classes.cases:224` (a covergroup
case) with `verification failed: token stream diverges` — `format_source`
refused to emit the corrupted output rather than silently producing it.
`cargo test -p vlog_parser` also caught it directly in
`constraints_and_covergroups_are_captured_verbatim`. This is the
invariant-#1 backstop working end-to-end, not just the crafted tests.
2. Widened `verify.rs::normalize` (untouched by this feature, so this
sabotage is *of* the safety net, testing whether the new attack tests
would catch a real weakening of it) to apply the historical
trim-blindly-not-string-aware treatment to `TokenKind::String` — i.e.
recreated the exact corruption class CLAUDE.md's history note warns about
(multi-line string re-indented and silently accepted). Result: exactly one
of the 9 rejection tests turned red —
`a_reindented_string_inside_a_constraint_is_rejected` — while the other 8
and the pre-existing macro/directive string-crossing tests stayed green.
This is precise evidence the test is a real, narrowly-targeted pin, not a
vacuous pass.
- `verify.rs`: confirmed byte-identical to HEAD both before and after these
experiments (`git diff` empty, not in `git status --porcelain`).
- **Claim 4: PASS.**
**Two mid-round fixes (claim 5).**
- (a) Lexer blank-continuation bug: built the pre-feature binary in the HEAD
worktree and fed it the exact class-free repro from the Design notes
(`` `define A \ `` / ` x \ ` / blank / `// c` / `wire w;`). It reproduces:
`verification failed: token stream diverges ... input has directive
"...x \\" ..., output has directive "...x \\\n// c"`. The fixed (working
tree) binary round-trips the same input cleanly (`--check` exit 0, blank
line preserved). Confirmed pre-existing and confirmed fixed. **PASS.**
- (b) `raw_inline` convergence: reverted `raw_inline` to call `raw_lines`
(the dedent-by-column path) and ran the **real** corpus file
`corpus/ibex/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_mubi_cov.sv`
(the file named in the Assumptions section) through the sabotaged binary:
it hit `verification failed: formatting is not idempotent; line 66 changed
from " .ValueTrue(...)," to ".ValueTrue(...),"` — reproducing the exact
documented drift on the exact documented file. The real (fixed) binary
formats this file cleanly and idempotently (`--check` exit 0 after one
reformat). A synthetic 3-line `typedef ... #(...)` case converges under the
real binary on all 3 passes. **PASS.**
**Handshakes (claim 6).**
- Fence inactive inside a class body: `// vfmt: off` around a member inside
`class c; ... endclass` is ignored (`int a = 1;` gets reformatted to
`int a = 1;`); the identical shape inside `module m; ... endmodule` is left
byte-for-byte alone. Also checked the *complementary* case not mentioned in
the README — a class **nested inside** a module-level fence — and confirmed
the fence still works there (the whole class, member formatting included,
stays byte-identical), since the module-scope fence copies the fenced
source span verbatim regardless of what is inside it. Nothing corrupted
either way. **PASS**, and the two cases don't contradict each other.
- vlog_semantic skips class bodies: built a throwaway probe crate
(path-dependency on `vlog_semantic`/`vlog_parser`, not added to the repo)
and called `Semantics::definition_of` on an identifier used inside a class
method body, and on a property's own declaration site. Both return `None`,
no panic, `symbols().len() == 0` for the whole file — matches "no name
declared inside a class body is indexed, hovered or navigable" exactly.
Separately confirmed `TypedefKind::ForwardClass` **is** indexed:
`typedef class fwd;` followed by a use of `fwd` as a type resolves
`definition_of` to `Some(("fwd", Typedef))`. **PASS.**
- `parse(tokens, source)`: grepped the whole workspace for callers; the only
caller is `parse_source` in `crates/vlog_parser/src/lib.rs`, which is
updated. `parse_source_tolerant` already took `source` before this feature
(calls `parse_tolerant`, a different function) and is untouched, matching
the README's claim. **PASS.**
- Lint rule coverage — **finding, not blocking**, see below.
**Lint-rule finding (non-blocking, documentation precision).** The
Handshakes section says plainly: *"`visit.rs`'s `items()` walk has a `_ =>
{}` arm too, so lint rules do not see class members."* That is broader than
what's actually true. Only the 4 rules that walk the tree through
`visit.rs`'s `walk_items`/`walk_all_stmts`
(`always_comb_blocking`, `always_ff_non_blocking`, `case_missing_default`,
`explicit_parameter_storage_type`) miss class members. The other 4 rules
(`module_filename`, `no_tabs`, `no_trailing_whitespace`, `unused_waiver`)
read raw source/line data directly and are unaffected. Probed directly:
```
class c;
int a; // ← literal tab
function void f(int x);
case (x)
1: a = 1;
endcase // ← no default
endfunction
endclass
```
`vfmt check` on this file reports `no-tabs` (line 2) but **not**
`case-missing-default` for the `case` inside the method — exactly the
asymmetry the broad wording obscures. Suggest tightening the sentence to name
which rules are affected (the 4 AST-walk ones), so a reader doesn't conclude
*no* lint rule fires inside a class. Left the Handshakes section itself
alone, per the QA/lead split in `CLAUDE.md` — filing this as a QA finding
for the lead rather than editing someone else's section.
**Structural support (claim 2) and UVM torture.** All of the following parse,
format, and are stable across 3 formatting passes (checked pass1==pass2==
pass3 byte-for-byte on every case, not just `--check` once):
class in package in `` `ifdef``; nested class-in-class; a class exercising
every member qualifier combination at once (`rand`/`randc`/`local`/
`protected`/`static`/`const`/`local rand`/`protected randc`/`local static`/
`virtual`/`virtual interface`/`pure virtual function`/`extern virtual task`);
`extern function` whose return type is a parameterized class
(`uvm_object_wrapper#(c)`), plus its out-of-body `c::get_wrapper()`
definition; a constraint containing a string literal with literal `{`/`}`
inside it (not mistaken for block delimiters) alongside an `inside {...}`
constraint; a covergroup with `option.per_instance`, `option.name`, an
empty-bracket array bin (`bins low[] = {[1:3]}`), `illegal_bins ... default`,
and a `cross` with `binsof ... intersect`; `` `uvm_object_utils_begin/end ``
with `` `uvm_field_* `` macro items between them as class items; `` `ifdef``/
`` `else``/`` `endif`` directives between ordinary class members; `endclass :
d` where the label doesn't match the class name `c` — **parses and is
preserved verbatim, not rejected and not "corrected"** (consistent with the
Assumptions section: vfmt does not check semantic legality); an empty class;
a 5-deep `extends` chain (`c5 extends c4 extends c3 extends c2 extends c1`);
and a combined case exercising `typedef class` forward declaration, class
parameters referenced in an `extends #(.W(W))` override, multiple
`implements`, a virtual-interface property, a parameterized property type,
`function new`, `fork`/`join_none`/`disable fork`, and a scoped parameterized
call (`uvm_config_db#(virtual my_if)::set(...)`) all in one file — every one
of these formatted correctly (or was already clean) with no dropped tokens,
no corrupted braces/strings, and no divergence from the input's semantic
content.
**Recursion budgets.** A class containing a function containing 60 nested
`begin`/`end` blocks: n=59 succeeds, n=60 hits `nesting too deep (limit 64)`
at a clean, correctly-located parse error — no stack overflow, no crash,
consistent with the class contributing exactly one level to the shared
budget as documented. A 300-member flat class body: parses and formats in
~5 ms, idempotent, no chain-length issue (flat item lists aren't recursive
per-item, as expected). **PASS.**
**Case table count.** `crates/vlog_formatter/tests/cases/classes.cases` has
37 `====` separators (38 cases, matching the claimed count). Total across all
`.cases` files, computed with the same last-block-may-be-empty rule the
harness (`parse_cases` in `tests/cases.rs`) uses: **397**, matching
"359 → 397" (359 = 397 − 38). **PASS.**
**Summary.** All 7 claims **PASS**. No corruption, no comma/label loss, no
verbatim byte alteration, no corpus regression found anywhere — including
under two independent, reverted sabotage experiments designed to surface
exactly those failure modes. One non-blocking documentation-precision finding
filed above (lint-rule handshake wording); no code changes were needed or
made.
## Review
**2026-08-19 — lead. Verdict: accepted and committed. The largest
corpus jump in the project's history: 58.0% → 70.5% formattable, +102
files, zero regressions — verified by path, all 578 formattable files
round-tripped individually.**
Points reviewed and accepted:
1. **The structural-vs-verbatim line was drawn by corpus evidence, not
taste**: constraints and covergroups verbatim (their internals are a
distinct sub-language with no formatting payoff and high corruption
risk — the attack tests exist precisely because verbatim capture is
where the historical corruption class lives), parameterized-type
`#()` args verbatim (they are types, not expressions), randsequence
absent because the corpus has zero. Class bodies reusing the item
loop is why Meta/directives/macros/nesting all worked for free.
2. **Voluntary invariant-#4 compliance**: verify.rs untouched, yet the
9 rejection + 2 acceptance attack tests shipped anyway — and QA's
sabotage recreated the exact historical in-string re-indent
corruption and found precisely one test turning red. That is the
masked-corruption discipline fully internalized.
3. **The two mid-round verification failures were triaged correctly**:
the lexer blank-line bug proven pre-existing on a HEAD worktree
before being fixed; raw_inline's convergence made true by
construction. Both reproduced independently by QA.
4. **The honest ledger**: 72 of 142 extends-blocked files format; 70
advanced to named next blockers, histogrammed. Queues/dynamic
arrays are now the top corpus blocker (41 files) — that data sets
the next parse round's priority.
5. **The handshakes are the right escalations**: fence-inactive inside
class bodies (one-arm fix, filed), lint AST-rule coverage
(lead-sharpened per QA: line-based rules still fire; only the four
AST-walking rules skip class bodies), and the real LSP gap — no
name inside a class body is indexed or navigable — stated plainly
as vlog_semantic's natural next round. The parse(tokens, source)
signature change made mandatory-not-optional for exactly the right
reason: an empty verbatim slice would be a corruption bug.
With this, vfmt formats the majority of real-world DV code as well as
RTL. Next per the owner's directive: alignment inference, content-hash
cache, range formatting, remaining lint rules — and the corpus says
queues/dynamic arrays after that.