The clocking wave: eight buckets in one round, 43 -> 11 on opentitan
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 22s

Clocking signal bindings (the one production the modelled node was
missing), default disable iff captured verbatim with six rejection
pairs, iff on event-control terms, indexed bare event names
(chain-charged), gate drive strengths (the mop-up's amortized skip),
program blocks as modules with a different closer, and macros as a
concurrent assertion's whole action — where QA caught a real
regression (a macro BEGINNING a statement, four UVM-idiom shapes) and
the rework moved the decision to the token after the call:
at_statement_tail, one line, with the failure asymmetry argued in the
doc and attacked by QA against the diff rather than trusted. Chain
limit 256 -> 1024 on measured need (567 links in pinmux_reg_top) with
PARSE_STACK_SIZE 16 -> 32 MiB restoring the 3.3x margin, a sabotage
probe proving it real, and parse_sens_list's uncharged chain loop
closed. Whole-tree superset: exactly one output move, ~55 lines of
prim_sync_reqack generate code freed from an assertion's opaque
bytes. Corpus 860 files byte-identical, 813/820. The 11 remaining:
macro fragments (preprocessing decision), vendor non-SV (exclude
patterns recommended), three written-up skips.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-29 18:46:58 -07:00
1 parent 5ad0772475
commit bc533c6cb1
14 files changed
+2081 -85

No files matched your search

+69 -1
View File
@@ -1372,7 +1372,75 @@ README.md, TODO.md §11 Lane B lines)
gate byte-identical at 813/820. Tolerant diagnostics over the failing
set 1 644 → 1 290, none worse anywhere.
`docs/features/testbench-mopup/README.md`.
- [ ] Skipped there, one file: a gate's drive strength
- [x] Skipped there, one file: a gate's drive strength
(`pullup (weak1) u (...)`, spi_host/dv/tb.sv:101) — a different
production from the cast bases bucket 6 named, costing two AST changes
for one file. See that README's Status for the exact shape.
Done in Round 2 below, at the amortized cost that round predicted.
### Round 2 (clocking wave) — every remaining grammar bucket, one round
Serial in the main tree (`docs/features/clocking-wave/README.md`). Baseline
43 failures over 3,943 files at `5ad0772`; **43 → 11**, and the eleven left
are the two OUT rows — macro fragments that need a preprocessor, and vendor
files that are not SystemVerilog. Zero newly failing; one previously-passing
file's output moves, and it moves because 55 lines that used to be swallowed
into an opaque blob are now parsed (see below). Corpus byte-identical at
813/820 over all 860 files; `verify.rs` untouched.
- [x] **Clocking signal bindings** — `output tms = _tms_internal;`, IEEE 1800
§14.4's `clocking_decl_assign`. **7 files.** Deviation from the brief:
clocking is already a modelled node with a printer, spans and a linter
guard, so the fix is the one missing field, not a verbatim capture that
would have thrown that model away. The *opacity* the brief wanted is
where it already lived — `analyze` keeps the block a leaf and the linter
takes the whole item span, binding included, out through `opaque_spans`
— and is now pinned by a lint case.
Files: `crates/vlog_parser/src/{ast,parser}.rs`,
`crates/vlog_formatter/src/format.rs`.
- [x] **`default disable iff expr;`** (IEEE 1800 §16.12) — **7 files**, and not
a clocking construct at all: the bucket label came from the error text,
and reading all 14 sites is what split it 7 + 7. Verbatim capture, the
round's only one, with six masked-corruption attack pairs.
- [x] **A macro as a concurrent assertion's action statement** — not in the
brief; the next blocker on 6 of the above once they parsed.
`assert property (p) else \`ASSERT_ERROR(A)` has no `;` to scan to, so
`skip_action_stmt` used to run through whatever followed. **This is the
one change with a whole-tree output effect**: `prim_sync_reqack.sv` had
~55 lines of generate-block code absorbed into an assertion's opaque
bytes; they are now parsed and laid out.
- [x] **`iff` on an event-control term** (§9.4.2) — **5 files**. LRM scope
checked: `iff` gates one event-expression term, so `@( … )` is the only
position; the paren-less form and `wait` have no `iff` alternative.
- [x] **Bare event control over an indexed hierarchical path** —
`@cfg.agents["k"].vif.cb`, **3 files** (the rstmgr shape). Also closed a
pre-existing hole: that loop boxed a layer per `.name` without charging
the chain budget.
- [x] **`program … endprogram`** (§24.3) — **3 files**, one dispatch arm
reusing `parse_module`.
- [x] **Chain limit 256 → 1024, `PARSE_STACK_SIZE` 16 → 32 MiB** — **7 files**,
an engineering measurement, not a grammar change. Real generated register
files need up to **567** links (`pinmux_reg_top.sv`); 9.20 KiB of debug
stack per postfix link; the new worst case is **9 894 KiB** (a maximal
chain inside nesting), so 32 MiB keeps the 2.7×-or-better margin. This
round retires the feature's own "chains do not move the worst case" —
true at 256, false at 1024 — while re-verifying the phase argument that
keeps the two budgets additive.
`docs/features/recursion-limit/README.md` round 4.
- [ ] **Skipped, `jtag_if.sv`**: its clocking blocker is fixed; a
**pre-existing** one sits behind it. Two rival, bracket-*balanced*
interface headers in an `` `ifdef ``/`` `else `` region, which
`at_split_conditional` does not fire on (it requires an open bracket), so
the parser nests them. Handshake request to a future `directive-split`
round; reproduced on trunk grammar alone.
- [ ] **Skipped, `SimDTM.sv`**: a net delay written *after* the type
(`wire [31:0] #0.1 x = y;`), which is where the LRM puts it — lucisv
parses it only before. One `DataDecl` field has one print position, so
accepting both spellings needs a positional field or the safety net
rightly refuses the reordered tokens. One vendor file in `tb/unused/`.
- [ ] **Skipped, `kmac_reduced_tb.sv`**: a trailing comma in a *named*
parameter override list. Not legal SystemVerilog; rejecting it is
correct.
- [ ] **Recommended instead of grammar work**, for the sweep's non-SystemVerilog
files: exclude patterns `**/*.tpl.sv`,
`**/vendor/google_riscv-dv/**`, `**/pulp_riscv_dbg/tb/unused/**`.
+39 -8
View File
@@ -1679,7 +1679,7 @@ impl<'a> Fmt<'a> {
fn cont_assign(&self, a: &ContAssign) -> Doc {
let mut docs = vec![text("assign ")];
if let Some(s) = &a.strength {
docs.push(text(format!("({}, {}) ", s.first, s.second)));
docs.push(text(format!("{} ", drive_strength(s))));
}
if let Some(delay) = &a.delay {
docs.push(text("#"));
@@ -1950,6 +1950,9 @@ impl<'a> Fmt<'a> {
fn gate_instantiation(&self, g: &GateInstantiation) -> Doc {
let mut docs = vec![text(g.gate.clone())];
if let Some(s) = &g.strength {
docs.push(text(format!(" {}", drive_strength(s))));
}
if let [delay] = g.delay.as_slice() {
// One value prints itself, brackets and all (`#5`, `#(5)`).
docs.push(text(" #"));
@@ -2250,6 +2253,10 @@ impl<'a> Fmt<'a> {
concat(docs)
}
/// One clocking-block item. A `= expression` binding
/// (`output tms = _tms_internal;`) prints on the item's own line: the
/// bound expression is a signal name, never long enough to be worth a
/// breakable group.
fn clocking_item(&self, kind: &ClockingItemKind) -> Doc {
match kind {
ClockingItemKind::Default { input, output } => {
@@ -2264,15 +2271,25 @@ impl<'a> Fmt<'a> {
}
text(s)
}
ClockingItemKind::Signals { dir, skew, names } => {
let mut s = dir.clone();
ClockingItemKind::Signals { dir, skew, signals } => {
let mut head = dir.clone();
if let Some(skew) = skew {
s.push(' ');
s.push_str(skew);
head.push(' ');
head.push_str(skew);
}
s.push(' ');
s.push_str(&join_names(names));
text(s)
head.push(' ');
let mut docs = vec![text(head)];
for (i, sig) in signals.iter().enumerate() {
if i > 0 {
docs.push(text(", "));
}
docs.push(text(sig.name.text.clone()));
if let Some(value) = &sig.value {
docs.push(text(" = "));
docs.push(self.expr(value));
}
}
concat(docs)
}
}
}
@@ -2519,6 +2536,12 @@ impl<'a> Fmt<'a> {
parts.push(text(format!("{e} ")));
}
parts.push(self.expr(&i.expr));
// `posedge clk iff enable` — the gate belongs to this
// term, so it prints before the separator, not after it.
if let Some(iff) = &i.iff {
parts.push(text(" iff "));
parts.push(self.expr(iff));
}
if self.inline_comments(&i.meta.before_sep, &mut parts) {
parts.push(Doc::HardLine);
}
@@ -3160,6 +3183,14 @@ impl<'a> Fmt<'a> {
}
}
/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write.
fn drive_strength(s: &DriveStrength) -> String {
match &s.second {
Some(second) => format!("({}, {})", s.first, second),
None => format!("({})", s.first),
}
}
/// A comma-separated list of names, as the source wrote them. The parser
/// keeps each name's byte range alongside its text, so the joined spelling is
/// rebuilt here rather than stored.
@@ -0,0 +1,241 @@
# Round 2 of the testbench wave: clocking-block signal bindings, the standing
# `default disable iff`, `iff` on an event-control term, a bare event control
# naming an indexed hierarchical path, a gate's drive strength, and `program`.
# See docs/features/clocking-wave/README.md. Every case here is a shape the
# OpenTitan sweep contains.
# --- clocking_decl_assign: `output tms = _tms_internal;` (IEEE 1800 §14.4) ---
# The binding prints on the item's own line. Nothing here is breakable: the
# bound expression is a signal name, and the body was already one item per line.
interface jtag_if;
clocking host_cb @(negedge tck);
default output #1ns;
output tms = _tms_internal;
output tdi = _tdi_internal;
input tdo;
endclocking
endinterface
----
interface jtag_if;
clocking host_cb @(negedge tck);
default output #1ns;
output tms = _tms_internal;
output tdi = _tdi_internal;
input tdo;
endclocking
endinterface
====
# a direction group may bind several signals, and the value is a real expression
interface i;
clocking cb @(posedge clk_i);
input pwrmgr_data = pwrmgr_data_o_i, keymgr_data = keymgr_data_o_i;
output #2 h2d = h2d_int[1], d2h;
inout x = a.b.c;
endclocking
endinterface
----
interface i;
clocking cb @(posedge clk_i);
input pwrmgr_data = pwrmgr_data_o_i, keymgr_data = keymgr_data_o_i;
output #2 h2d = h2d_int[1], d2h;
inout x = a.b.c;
endclocking
endinterface
====
# a clocking block in a module, with comments around the bindings
module tb;
clocking cb @(posedge clk);
// driven by the sequence
output req = req_int; // through the internal net
input rsp;
endclocking
endmodule
----
module tb;
clocking cb @(posedge clk);
// driven by the sequence
output req = req_int; // through the internal net
input rsp;
endclocking
endmodule
====
# --- `default disable iff expr;` (IEEE 1800 §16.12), kept verbatim ---
# It governs the concurrent assertions in its scope, which are verbatim too, so
# it is copied out by span: the bytes are reproduced, the indent is the item's.
module m;
bit disable_sva;
default disable iff disable_sva || !rst_ni;
default disable iff !rst_n;
endmodule
----
module m;
bit disable_sva;
default disable iff disable_sva || !rst_ni;
default disable iff !rst_n;
endmodule
====
# it stands inside a generate block next to a `default clocking` and assertions
module m;
if (1) begin : gen_checks
default disable iff !rst_n || en != On;
default clocking @(posedge clk); endclocking
CheckA: assert property (a |=> b) else `uvm_error("CheckA", "no")
end
endmodule
----
module m;
if (1) begin : gen_checks
default disable iff !rst_n || en != On;
default clocking @(posedge clk);
endclocking
CheckA: assert property (a |=> b) else `uvm_error("CheckA", "no")
end
endmodule
====
# --- `iff` on an event-control term (IEEE 1800 §9.4.2) ---
module m;
initial begin
@(posedge clk iff rvalid);
@(negedge clk_i iff (write ? sram_we : sram_req));
@(posedge cfg.vif.enable iff cfg.vif.rst_n);
end
endmodule
----
module m;
initial begin
@(posedge clk iff rvalid);
@(negedge clk_i iff (write ? sram_we : sram_req));
@(posedge cfg.vif.enable iff cfg.vif.rst_n);
end
endmodule
====
# the gate belongs to its own term: both separators keep working around it
module m;
always @(posedge a iff en or negedge b) x <= 1;
always @(posedge a iff en, negedge b iff en2) y <= 1;
always @(a iff b) z <= 1;
endmodule
----
module m;
always @(posedge a iff en or negedge b) x <= 1;
always @(posedge a iff en, negedge b iff en2) y <= 1;
always @(a iff b) z <= 1;
endmodule
====
# --- a bare event control naming an indexed hierarchical path ---
# `@name` is printed back without parens; the bit-selects on the path are part
# of the name (IEEE 1800 §A.9.3), so nothing about the shape changes.
class c;
task wait_for_ready();
forever @cfg.m_alert_agent_cfgs["fatal_cnsty_fault"].vif.sender_cb begin
if (done) return;
end
endtask
endclass
----
class c;
task wait_for_ready();
forever @cfg.m_alert_agent_cfgs["fatal_cnsty_fault"].vif.sender_cb begin
if (done) return;
end
endtask
endclass
====
# --- a gate's drive strength, single and paired (IEEE 1800 §28.3) ---
module m;
for (genvar i = 0; i < 4; i++) begin : gen_tri_state
pullup (weak1) pd_in_i (si_pulldown[i]);
pulldown (supply0, supply1) pd_out_i (so_pulldown[i]);
end
and (strong0, strong1) g1 (o, a, b), g2 (o2, c, d);
assign (weak0, pull1) w = 1'b1;
endmodule
----
module m;
for (genvar i = 0; i < 4; i++) begin : gen_tri_state
pullup (weak1) pd_in_i (si_pulldown[i]);
pulldown (supply0, supply1) pd_out_i (so_pulldown[i]);
end
and (strong0, strong1) g1 (o, a, b), g2 (o2, c, d);
assign (weak0, pull1) w = 1'b1;
endmodule
====
# a gate whose first argument is parenthesized is still an argument, not a
# strength: only a strength keyword after the `(` opens one.
module m;
buf b1 ((a & b), c);
not (o, (x | y));
endmodule
----
module m;
buf b1 ((a & b), c);
not (o, (x | y));
endmodule
====
# --- `program ... endprogram` (IEEE 1800 §24.3): a module header, a module
# body, a different closer.
program spiflash #(
parameter int unsigned FlashSize = 1024,
parameter bit EnFastSim = 1'b1
) (
input logic csb,
input logic sck
);
logic [7:0] cmd;
initial begin
cmd = 8'h0;
end
task automatic step();
@(posedge sck iff !csb);
endtask
endprogram : spiflash
----
program spiflash #(
parameter int unsigned FlashSize = 1024,
parameter bit EnFastSim = 1'b1
) (input logic csb, input logic sck);
logic [7:0] cmd;
initial begin
cmd = 8'h0;
end
task automatic step();
@(posedge sck iff !csb);
endtask
endprogram : spiflash
====
# --- a macro invocation as a concurrent assertion's action statement ---
# `else `ASSERT_ERROR(A)` ends with the macro; there is no `;` to scan to.
module m;
FsmStateSwReset_A:
assert property (rst |=> state == Reset)
else `ASSERT_ERROR(FsmStateSwReset_A)
assign x = 1;
Other_A: assert property (c) else `uvm_error("a", "b");
endmodule
----
module m;
FsmStateSwReset_A:
assert property (rst |=> state == Reset)
else `ASSERT_ERROR(FsmStateSwReset_A)
assign x = 1;
Other_A: assert property (c) else `uvm_error("a", "b");
endmodule
====
# ... and the other side of that decision: when the macro expands to a signal
# name, the statement runs on past it and ends at its own `;`. All four shapes
# round-trip byte-for-byte, exactly as they did before the macro case existed.
module m;
A_A: assert property (a) else `SOME_SIGNAL = 1'b1;
B_B: assert property (b) else `MSG(x) + 1;
C_C: assert property (c) else `CNT <= `CNT + 1;
D_D: assert property (d) else `CNT++;
assign y = 1;
endmodule
----
module m;
A_A: assert property (a) else `SOME_SIGNAL = 1'b1;
B_B: assert property (b) else `MSG(x) + 1;
C_C: assert property (c) else `CNT <= `CNT + 1;
D_D: assert property (d) else `CNT++;
assign y = 1;
endmodule
+21 -4
View File
@@ -9,10 +9,10 @@
use vlog_formatter::{format_source, Config, FormatError};
use vlog_parser::parser::{MAX_CHAIN_LENGTH, MAX_NESTING_DEPTH, PARSE_STACK_SIZE};
/// Formatting the deepest legal tree peaks around 5.9 MiB of stack in an
/// unoptimized build, more than a default test thread's 2 MiB. The size is
/// Formatting the deepest legal tree peaks around 9.7 MiB of stack in an
/// unoptimized build, far more than a default test thread's 2 MiB. The size is
/// the one every production parse site is given, so these tests fail if the
/// guarantee is ever cut below what the depth limit needs.
/// guarantee is ever cut below what the two limits need.
fn format_deep(source: String) -> Result<String, FormatError> {
std::thread::Builder::new()
.stack_size(PARSE_STACK_SIZE)
@@ -70,12 +70,29 @@ fn longest_legal_chain_formats() {
assert_eq!(out, again, "formatting a maximal chain is a fixed point");
}
/// The stack worst case: a maximal chain inside statement nesting. The two
/// peak in different phases — nesting while parsing, chains while formatting —
/// so this is the input `PARSE_STACK_SIZE` is measured against.
#[test]
fn a_maximal_chain_inside_deep_nesting_formats() {
let depth = MAX_NESTING_DEPTH as usize / 2 - 4;
let src = format!(
"module m;\ninitial\n{}x <= a{};\n{}\nendmodule\n",
"begin\n".repeat(depth),
".b".repeat(MAX_CHAIN_LENGTH as usize),
"end\n".repeat(depth)
);
let out = format_deep(src).expect("a maximal chain inside deep nesting must format");
let again = format_deep(out.clone()).expect("reformat");
assert_eq!(out, again, "the combined worst case is a fixed point");
}
#[test]
fn nesting_past_the_limit_never_reaches_the_formatter() {
let cases = [
(nested_begins(400), "nesting too deep"),
(nested_parens(400), "nesting too deep"),
(member_chain(1500), "expression chain too long"),
(member_chain(MAX_CHAIN_LENGTH as usize + 1), "expression chain too long"),
];
for (src, expected) in cases {
match format_deep(src) {
@@ -1405,3 +1405,84 @@ fn a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refu
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end /* a */ // b\n else if (c) begin\n x = 2;\n end\n end\nendmodule\n",
);
}
// ----------------------------------------------------------------------
// The clocking wave's new verbatim capture: `default disable iff expr;`
// (`docs/features/clocking-wave/README.md`).
//
// It is copied out of the source by span and re-indented, exactly like
// `constraint` and a concurrent assertion, so the net must still see every
// token inside it. Per CLAUDE.md hard invariant #4 these are the attack
// pairs for that capture: **no normalization was added or widened for it**,
// and each pair below is a real change inside the captured bytes that the
// existing forgiveness could plausibly have masked (indentation, a moved
// line break, a dropped comment) — asserted rejected.
// ----------------------------------------------------------------------
#[test]
fn a_default_disable_iff_may_be_reindented() {
let input = "module m;\n default disable iff !rst_ni;\nendmodule\n";
let output = "module m;\n default disable iff !rst_ni;\nendmodule\n";
verify_equivalence(input, output).expect("only per-line indentation changed");
}
#[test]
fn a_changed_default_disable_condition_is_rejected() {
// The polarity of a disable condition is the difference between an
// assertion that runs in reset and one that does not.
expect_divergence(
"module m;\n default disable iff !rst_ni;\nendmodule\n",
"module m;\n default disable iff rst_ni;\nendmodule\n",
);
expect_divergence(
"module m;\n default disable iff a || !b;\nendmodule\n",
"module m;\n default disable iff a && !b;\nendmodule\n",
);
}
#[test]
fn a_dropped_default_disable_operand_is_rejected() {
expect_divergence(
"module m;\n default disable iff disable_sva || !rst_ni;\nendmodule\n",
"module m;\n default disable iff !rst_ni;\nendmodule\n",
);
}
#[test]
fn a_dropped_default_disable_item_is_rejected() {
expect_divergence(
"module m;\n default disable iff !rst_ni;\n wire w;\nendmodule\n",
"module m;\n wire w;\nendmodule\n",
);
}
#[test]
fn a_comment_inside_a_default_disable_may_not_be_dropped() {
expect_divergence(
"module m;\n default disable iff /* why */ !rst_ni;\nendmodule\n",
"module m;\n default disable iff !rst_ni;\nendmodule\n",
);
}
#[test]
fn a_default_disable_split_over_lines_may_not_lose_a_token() {
// The capture spans several source lines, so the line-break normalization
// is exactly what a masked corruption here would ride on.
expect_divergence(
"module m;\n default disable iff\n !rst_ni ||\n !en;\nendmodule\n",
"module m;\n default disable iff !rst_ni || en;\nendmodule\n",
);
}
#[test]
fn a_default_disable_carrying_a_dist_set_keeps_every_byte() {
// A `;` inside the set does not end the item, so the whole set is in the
// captured bytes — and a changed weight there must still be refused.
let input = "module m;\n default disable iff x dist {1 := 1, 2 := 2};\nendmodule\n";
let output = format_source(input, &Config::default()).expect("must format");
assert!(output.contains("dist {1 := 1, 2 := 2}"), "the set's bytes changed:\n{output}");
expect_divergence(
input,
"module m;\n default disable iff x dist {1 := 1, 2 := 9};\nendmodule\n",
);
}
@@ -23,3 +23,21 @@ endmodule
module foo_bar; // lucisv: waive module-name-style
//^ 17 unused-waiver
endmodule
====
# a `program` reuses `ItemKind::Module`, so every rule that matches a module
# matches it — deliberately, and pinned here so the decision is not silently
# reversed. The rule's *message* still says "module"; that wording is
# pre-existing for `interface` and filed, not fixed, in
# docs/features/clocking-wave/README.md's Handshakes.
#select module-name-style,unused-waiver
program FooBar;
//^ 9 module-name-style
endprogram
====
# ... and the body of a program is descended into like a module's
#select module-name-style,unused-waiver
program top;
module Inner;
//^ 10 module-name-style
endmodule
endprogram
@@ -116,3 +116,33 @@ module m (input logic c, output logic q);
assign a = c;
assign q = a;
endmodule
====
# a clocking block is opaque: the signals it names — and the expressions its
# items bind them to — are taken out through the token-level guard, so neither
# the clocking signal nor what it drives is ever reported.
# See docs/features/clocking-wave/README.md.
#select unused-signal,unused-waiver
module m;
wire tms_int;
wire tdo;
clocking cb @(posedge clk);
output tms = tms_int;
input tdo;
endclocking
endmodule
====
# a `default disable iff` is a verbatim item, so it is opaque the same way a
# concurrent assertion is: it neither reports nor rescues the names it mentions
#select unused-signal,unused-waiver
module m;
wire rst_n;
default disable iff !rst_n;
endmodule
====
# an `iff` gate on an event-control term is an ordinary read, so the signal it
# names is not reported unused
#select unused-signal,unused-waiver
module m (input logic clk, output logic q);
wire enable;
always @(posedge clk iff enable) q <= 1;
endmodule
+29 -9
View File
@@ -300,12 +300,13 @@ pub struct Module {
}
impl Module {
/// The keyword that closes this declaration: `endmodule` or `endinterface`.
/// The keyword that closes this declaration: `endmodule`, `endinterface`
/// or `endprogram`.
pub fn end_kw(&self) -> &'static str {
if self.kw == "interface" {
"endinterface"
} else {
"endmodule"
match self.kw.as_str() {
"interface" => "endinterface",
"program" => "endprogram",
_ => "endmodule",
}
}
}
@@ -629,13 +630,15 @@ pub struct ContAssign {
pub assigns: Vec<AssignPair>,
}
/// The `( strength0 , strength1 )` pair of a continuous assignment. The two
/// strengths are stored in the order the source wrote them — the language
/// The `( strength0 , strength1 )` of a continuous assignment or a gate. The
/// two strengths are stored in the order the source wrote them — the language
/// allows either order and lucisv is not a legality checker.
#[derive(Debug)]
pub struct DriveStrength {
pub first: String,
pub second: String,
/// `None` for the single-strength spelling `pullup (weak1) p (x);`
/// (IEEE 1800 §28.3's `pullup_strength`), which only a pull gate takes.
pub second: Option<String>,
}
#[derive(Debug)]
@@ -677,6 +680,9 @@ pub struct SensItem {
pub sep: Option<SensSep>,
pub edge: Option<String>,
pub expr: Expr,
/// The gating condition of `@(posedge clk iff enable)` — IEEE 1800
/// §9.4.2's optional `iff expression` on one event expression term.
pub iff: Option<Expr>,
}
/// How two event-list items were separated in the source. Both spellings are
@@ -801,6 +807,9 @@ pub struct BindDirective {
pub struct GateInstantiation {
/// `and`, `or`, `not`, ...
pub gate: String,
/// The `(weak1)` in `pullup (weak1) p (x);` (IEEE 1800 §28.3), or the
/// `(strong0, strong1)` pair every driving gate also accepts.
pub strength: Option<DriveStrength>,
/// The delay written after `#`: empty when there is none, one element for
/// every spelling a net or a continuous assignment also accepts, and two
/// or three for the `(rise, fall[, turn-off])` list that only a gate
@@ -1009,7 +1018,18 @@ pub enum ClockingItemKind {
Default { input: Option<String>, output: Option<String> },
/// `input #2 a, b;`, `output negedge c;`, `inout d;`. `skew` is the delay
/// or edge as written (`#2`, `negedge`), or `None` when omitted.
Signals { dir: String, skew: Option<String>, names: Vec<Name> },
Signals { dir: String, skew: Option<String>, signals: Vec<ClockingSignal> },
}
/// One `signal [= expression]` of a clocking direction group — IEEE 1800
/// §14.4's `clocking_decl_assign`. The expression binds the clocking signal to
/// something other than the same-named signal in the enclosing scope:
/// `output tms = _tms_internal;`.
#[derive(Debug)]
pub struct ClockingSignal {
pub name: Name,
/// `None` for the plain `input tdo;` spelling.
pub value: Option<Expr>,
}
#[derive(Debug)]
+547 -38
View File
@@ -100,6 +100,7 @@ const SYNC_CLOSERS: &[&str] = &[
"end",
"endmodule",
"endinterface",
"endprogram",
"endpackage",
"endgenerate",
"endfunction",
@@ -117,7 +118,7 @@ const SYNC_CLOSERS: &[&str] = &[
/// `class` is deliberately absent: unlike a module or a package it nests
/// (inside a package, and inside another class), so stopping recovery before
/// one would end the enclosing body at the wrong place.
const SYNC_OPENERS: &[&str] = &["module", "macromodule", "interface", "package"];
const SYNC_OPENERS: &[&str] = &["module", "macromodule", "interface", "program", "package"];
/// Keywords that may stand *before* the one that names a class member:
/// `virtual function`, `pure virtual task`, `extern function`,
@@ -178,13 +179,17 @@ pub const MAX_NESTING_DEPTH: u32 = 64;
/// abort, not a `Result` — the whole process dies. So the stack has to fit
/// the limit; the limit is not lowered to fit some thread's stack.
///
/// [`MAX_CHAIN_LENGTH`] is the other half of what has to fit: it bounds AST
/// depth the same way, and since 2026-08-29 it, not nesting, sets the peak.
///
/// Measured worst case for the full pipeline (tokenize → parse → analyze →
/// format → verify) over every nesting family, on input sized to trip the
/// limit: **~5.9 MiB unoptimized, ~0.8 MiB optimized** (nested `case`, the
/// fattest family). 16 MiB is that with 2.7× to spare, which is the margin
/// this wants: unoptimized frame sizes drift upward with the compiler — the
/// same worst case measured ~3.9 MiB in 2026-08 and ~5.9 MiB in 2026-08-28
/// on rustc 1.97 — and there is no recoverable failure mode to fall back to.
/// format → verify) over every nesting and chain family, on input sized to
/// trip a limit or to sit exactly at it: **~9.7 MiB unoptimized, ~0.8 MiB
/// optimized** — a maximal postfix chain inside statement nesting. 32 MiB is
/// that with 3.3× to spare, which is the margin this wants: unoptimized frame
/// sizes drift upward with the compiler — the nesting worst case measured
/// ~3.9 MiB in 2026-08 and ~5.9 MiB in 2026-08-28 on rustc 1.97 — and there
/// is no recoverable failure mode to fall back to.
///
/// Every thread that may reach a parse is spawned with at least this:
/// `std::thread::Builder::new().stack_size(PARSE_STACK_SIZE)`, or
@@ -192,7 +197,7 @@ pub const MAX_NESTING_DEPTH: u32 = 64;
/// stacks are committed by the OS a page at a time, so an unused one costs
/// address space rather than memory. `docs/features/recursion-limit/README.md`
/// lists every site.
pub const PARSE_STACK_SIZE: usize = 16 * 1024 * 1024;
pub const PARSE_STACK_SIZE: usize = 32 * 1024 * 1024;
/// How many links a left-nested chain may add to the tree on one path.
///
@@ -204,14 +209,22 @@ pub const PARSE_STACK_SIZE: usize = 16 * 1024 * 1024;
/// same way [`MAX_NESTING_DEPTH`] is, so total AST depth stays bounded by
/// the two limits together no matter how chains and nesting are combined.
///
/// It is larger than [`MAX_NESTING_DEPTH`] because a chain link is cheap —
/// ~9 KiB of stack per link in an unoptimized build against ~94 KiB for a
/// nested statement, so a maximal chain peaks near 2.4 MiB, well under the
/// ~5.9 MiB that maximal statement nesting already costs — and because long
/// flat chains are the one shape real RTL does produce (a 256-term generated
/// sum, a 64-bit parity XOR). Raising it, unlike raising
/// [`MAX_NESTING_DEPTH`], does not move the worst case.
pub const MAX_CHAIN_LENGTH: u32 = 256;
/// It is much larger than [`MAX_NESTING_DEPTH`] because a chain link is cheap
/// — ~9.2 KiB of stack per link in an unoptimized build against ~94 KiB for a
/// nested statement — and because long flat chains are the one deep shape real
/// RTL genuinely produces. 256 was not enough for real code: OpenTitan's
/// generated register files build one `|` chain per register file, and the
/// largest (`pinmux_reg_top.sv`) needs **567** links, so seven real files were
/// rejected. 1024 is 1.8× the largest chain the whole 3,943-file tree
/// contains, where only two files pass 512 and only seven pass 256.
///
/// Unlike raising [`MAX_NESTING_DEPTH`], raising this does not change which
/// *nesting* a file may use — but it is no longer free on the stack: at 1024
/// a maximal postfix chain peaks at ~9.4 MiB unoptimized, past the ~5.9 MiB
/// maximal nesting costs, so this limit now sets the worst case
/// [`PARSE_STACK_SIZE`] is measured against. See
/// `docs/features/recursion-limit/README.md`.
pub const MAX_CHAIN_LENGTH: u32 = 1024;
/// The three pieces a `#( parameter ... )` port list yields, so module and
/// class headers can share one parse.
@@ -1434,12 +1447,21 @@ impl<'a> Parser<'a> {
"interface" if !self.nth(1).is_kw("class") => {
self.parse_module("endinterface").map(ItemKind::Module)
}
// A `program` block is a module header over a module body with a
// different closer (IEEE 1800 §24.3) — the same node, the way an
// `interface` already is. Its stricter *legality* rules (no
// `always`, no instantiation of anything but interfaces) are a
// checker's business, not a formatter's.
"program" => self.parse_module("endprogram").map(ItemKind::Module),
"modport" => self.parse_modport().map(ItemKind::Modport),
"clocking" => self.parse_clocking(false).map(ItemKind::Clocking),
"default" if self.nth(1).is_kw("clocking") => {
self.bump();
self.parse_clocking(true).map(ItemKind::Clocking)
}
"default" if self.nth(1).is_kw("disable") => {
self.parse_default_disable().map(ItemKind::Verbatim)
}
"package" => self.parse_package(),
"import" => {
// A string right after `import` is a DPI linkage spec, not a
@@ -1983,10 +2005,41 @@ impl<'a> Parser<'a> {
// How many block keywords are open. Zero means the scan is looking for
// the statement's own terminator.
let mut depth = 0usize;
// True while the next token would be the *first* of a statement — at
// the start, and again after an `else` continues one.
let mut at_stmt_start = true;
loop {
if self.at_eof() {
return self.error("expected `;`");
}
// A statement that *is* a macro invocation ends with the
// invocation, whether or not a `;` follows it:
// `assert property (p) else `ASSERT_ERROR(A)` (OpenTitan
// `adc_ctrl/dv/sva/adc_ctrl_fsm_sva_if.sv:35`).
//
// Whether it is the whole statement is decided by what *follows*
// the call, never by the macro standing first — a macro's
// expansion is just as often a signal name that the rest of the
// statement goes on to assign to or read (`` `SIG = 1'b1; ``,
// `` `CNT <= `CNT + 1; ``, `` `MSG(x) + 1; ``). When anything
// that could continue a statement follows, this falls through to
// the ordinary token-by-token scan, which is what ran before this
// case existed (QA finding, `docs/features/clocking-wave`).
if depth == 0 && at_stmt_start && self.cur().is_macro() {
let call = self.parse_macro_call()?;
if call.semi || !self.at_statement_tail() {
// Its own `;`, or nothing that could continue it: done,
// unless an `else` chains a second action onto it.
if !self.eat_kw("else") {
return Ok(());
}
continue;
}
// The macro was a name, not a statement. Scan on.
at_stmt_start = false;
continue;
}
at_stmt_start = false;
let t = self.cur();
if t.is_sym("(") {
self.bump();
@@ -2019,6 +2072,7 @@ impl<'a> Parser<'a> {
if !self.eat_kw("else") {
return Ok(());
}
at_stmt_start = true;
}
} else if depth == 0 && self.eat_sym(";") {
return Ok(());
@@ -2028,6 +2082,25 @@ impl<'a> Parser<'a> {
}
}
/// True when the token at the cursor could *continue* a statement whose
/// first token has already been consumed — an assignment, an operator, a
/// postfix segment. Used to tell `` else `ASSERT_ERROR(A) `` (the macro is
/// the whole action) from `` else `SIG = 1'b1; `` (the macro was a name).
///
/// Every such continuation is spelled with a symbol: `=`, `<=`, `+`,
/// `++`, `.`, `[`, `::`. What can stand after a *complete* action instead
/// is a keyword (`assign`, `end`, `endmodule`), an identifier or another
/// macro (the next item or label), a directive, or the end of the file —
/// none of which continue an expression.
///
/// Deliberately generous in one direction: guessing "continues" when the
/// statement was in fact complete only falls back to the brute-force scan
/// that ran before the macro case existed, while guessing "complete" when
/// it was not is the regression this predicate exists to prevent.
fn at_statement_tail(&self) -> bool {
self.cur().kind == TokenKind::Symbol
}
/// `property name [( ... )]; ... endproperty [: name]`, and its
/// `sequence` / `endsequence` twin, kept as verbatim source for the reason
/// [`Parser::parse_concurrent_assertion`] gives — the body is written in
@@ -2045,6 +2118,45 @@ impl<'a> Parser<'a> {
Ok(self.verbatim_since(start, col))
}
/// `default disable iff <expression_or_dist>;` (IEEE 1800 §16.12), kept as
/// verbatim source.
///
/// It is the standing `disable iff` clause of every concurrent assertion
/// in the scope, so what it holds is a property-grammar operand — `dist`
/// included — and the assertions it governs are already verbatim. Copying
/// it out by span keeps the whole assertion story in one bucket instead of
/// modelling half of it. Only the item spelling exists; there is no
/// statement form.
fn parse_default_disable(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
self.bump(); // default
self.expect_kw("disable")?;
self.expect_kw("iff")?;
// Scan to the terminating `;`, skipping bracketed runs whole so a `;`
// written inside a `dist { ... }` set does not end the item early.
loop {
if self.at_eof() {
return self.error("expected `;`");
}
let t = self.cur();
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
let (open, close) = match t.text.as_str() {
"(" => ("(", ")"),
"[" => ("[", "]"),
_ => ("{", "}"),
};
self.bump();
self.skip_balanced(open, close)?;
} else if self.eat_sym(";") {
break;
} else {
self.bump();
}
}
Ok(self.verbatim_since(start, col))
}
// ------------------------------------------------------------------
// Conditional-directive split recovery
//
@@ -2660,11 +2772,11 @@ impl<'a> Parser<'a> {
let dir = self.bump().text;
let skew =
if self.at_clocking_skew() { Some(self.parse_clocking_skew()?) } else { None };
let mut names = vec![self.expect_name()?];
let mut signals = vec![self.parse_clocking_signal()?];
while self.eat_sym(",") {
names.push(self.expect_name()?);
signals.push(self.parse_clocking_signal()?);
}
ClockingItemKind::Signals { dir, skew, names }
ClockingItemKind::Signals { dir, skew, signals }
};
let span = self.span_from(start);
self.expect_sym(";")?;
@@ -2674,6 +2786,16 @@ impl<'a> Parser<'a> {
Ok(ClockingItem { meta, kind, span })
}
/// One `signal [= expression]` of a clocking direction group — IEEE 1800
/// §14.4's `clocking_decl_assign`. The expression names what the clocking
/// signal is really bound to (`output tms = _tms_internal;`), and it is an
/// ordinary expression rather than a second grammar.
fn parse_clocking_signal(&mut self) -> PResult<ClockingSignal> {
let name = self.expect_name()?;
let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
Ok(ClockingSignal { name, value })
}
/// True when the cursor is on a clocking skew rather than on the first
/// signal name: `#2`, `#1step`, `posedge`, `negedge`, `edge`.
fn at_clocking_skew(&self) -> bool {
@@ -3306,22 +3428,28 @@ impl<'a> Parser<'a> {
/// The optional `( strength0 , strength1 )` of a continuous assignment
/// (IEEE 1800 §10.3.1), e.g. `assign (weak0, pull1) x = y;` (corpus
/// `ibex/vendor/lowrisc_ip/ip/prim_generic/rtl/prim_usb_diff_rx.sv:39`).
/// `ibex/vendor/lowrisc_ip/ip/prim_generic/rtl/prim_usb_diff_rx.sv:39`),
/// or of a gate — where a pull gate may also write one strength on its
/// own, `pullup (weak1) p (x);` (§28.3's `pullup_strength`).
///
/// Both orders are accepted, as the grammar allows; the `(` only opens a
/// strength when a strength keyword follows it, so a parenthesized
/// left-hand side is untouched.
/// left-hand side — and a gate whose first argument is an expression — is
/// untouched.
fn parse_opt_drive_strength(&mut self) -> PResult<Option<DriveStrength>> {
if !self.cur().is_sym("(") || !is_drive_strength(self.nth(1)) {
return Ok(None);
}
self.bump(); // (
let first = self.bump().text;
if self.eat_sym(")") {
return Ok(Some(DriveStrength { first, second: None }));
}
self.expect_sym(",")?;
if !is_drive_strength(self.cur()) {
return self.error("expected a drive strength");
}
let second = self.bump().text;
let second = Some(self.bump().text);
self.expect_sym(")")?;
Ok(Some(DriveStrength { first, second }))
}
@@ -3731,6 +3859,10 @@ impl<'a> Parser<'a> {
fn parse_gate_instantiation(&mut self) -> PResult<GateInstantiation> {
let gate = self.bump().text;
// `pullup (weak1) p (x);` — the strength stands where an unnamed
// instance's argument list would, and only a strength keyword after
// the `(` tells the two apart.
let strength = self.parse_opt_drive_strength()?;
let delay = if self.cur().is_sym("#") {
self.bump();
self.parse_delay_values()?
@@ -3763,7 +3895,7 @@ impl<'a> Parser<'a> {
}
}
self.expect_sym(";")?;
Ok(GateInstantiation { gate, delay, instances })
Ok(GateInstantiation { gate, strength, delay, instances })
}
// ------------------------------------------------------------------
@@ -4657,6 +4789,40 @@ impl<'a> Parser<'a> {
}
}
/// The `hierarchical_identifier` of a paren-less event control:
/// `.`-separated names, each with an optional bit-select
/// (IEEE 1800 §A.9.3) — `@cfg.agents["ping"].vif.sender_cb`. Both segment
/// openers are safe to take greedily, because the statement that follows
/// an event control cannot begin with `.` or `[`.
///
/// One link per segment: the loop wraps what it has already built, which
/// is the shape `docs/features/recursion-limit/README.md` requires the
/// chain budget for. The caller restores the count it started from.
fn parse_bare_event_name(&mut self) -> PResult<Expr> {
let start = self.here();
let name = self.expect_ident()?;
let mut expr = self.expr_at(start, ExprKind::Ident(name));
loop {
if self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident {
self.link()?;
self.bump();
let member = self.expect_ident()?;
expr = self.expr_at(start, ExprKind::Member { base: Box::new(expr), name: member });
} else if self.cur().is_sym("[") {
self.link()?;
self.bump();
let index = self.parse_expr()?;
self.expect_sym("]")?;
expr = self.expr_at(
start,
ExprKind::Index { base: Box::new(expr), index: Box::new(index) },
);
} else {
return Ok(expr);
}
}
}
fn parse_sens_list(&mut self) -> PResult<SensList> {
if self.cur().is_sym("*") {
// `@*` without parens.
@@ -4668,15 +4834,12 @@ impl<'a> Parser<'a> {
// `@ident` / `@a.b` without parens; recorded as `Bare` so the
// formatter prints no parens back — inventing them is a
// token-stream change the safety net refuses.
let start = self.here();
let name = self.expect_ident()?;
let mut expr = self.expr_at(start, ExprKind::Ident(name));
while self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident {
self.bump();
let member = self.expect_ident()?;
expr = self.expr_at(start, ExprKind::Member { base: Box::new(expr), name: member });
}
return Ok(SensList::Bare(expr));
// A chain, so it carries the chain budget and releases it the way
// `parse_postfix` does — by restoring the count it started from.
let outer_links = self.links;
let out = self.parse_bare_event_name();
self.links = outer_links;
return out.map(SensList::Bare);
}
if self.cur().is_sym("(") && self.nth(1).is_sym("*") {
// `@( /* c */ * /* d */ )`: the comments belong to the star, not
@@ -4704,12 +4867,16 @@ impl<'a> Parser<'a> {
}
};
let expr = self.parse_expr()?;
// `@(posedge clk iff enable)` — IEEE 1800 §9.4.2 lets each term
// carry its own gating condition. `iff` is a keyword, so the
// expression above stops in front of it on its own.
let iff = if self.eat_kw("iff") { Some(self.parse_expr()?) } else { None };
// Comments written before the separator — either spelling — or
// before the closing `)` stay on this item's side of it.
if self.cur().is_sym(",") || self.cur().is_kw("or") || self.cur().is_sym(")") {
self.take_before(&mut meta);
}
items.push(SensItem { meta, sep, edge, expr });
items.push(SensItem { meta, sep, edge, expr, iff });
// Both separators are legal in the same list; each is kept as
// written so the formatter never rewrites one as the other.
sep = if self.eat_sym(",") {
@@ -5661,9 +5828,10 @@ mod tests {
#[test]
fn chains_nested_inside_chains_stay_bounded() {
// The budget accumulates along a path, so nesting cannot multiply it:
// 7 call levels each carrying a 40-segment chain is over the limit
// even though no single chain is.
let level = format!("a{}(", ".b".repeat(40));
// 7 call levels each carrying a chain of a fifth of the budget is over
// the limit even though no single chain is.
let per_level = MAX_CHAIN_LENGTH as usize / 5;
let level = format!("a{}(", ".b".repeat(per_level));
assert_chain_too_long(format!(
"module m;\nassign x = {}z{};\nendmodule\n",
level.repeat(7),
@@ -7485,7 +7653,7 @@ mod tests {
));
assert!(matches!(
&c.items[1].kind,
ClockingItemKind::Signals { dir, skew: None, names } if dir == "input" && names.len() == 2
ClockingItemKind::Signals { dir, skew: None, signals } if dir == "input" && signals.len() == 2
));
assert!(matches!(
&c.items[2].kind,
@@ -7506,6 +7674,347 @@ mod tests {
assert!(sel.is_default && sel.event.is_none() && !sel.has_end);
}
// ------------------------------------------------------------------
// The clocking wave (`docs/features/clocking-wave/README.md`)
// ------------------------------------------------------------------
#[test]
fn a_clocking_signal_may_be_bound_to_an_expression() {
// OpenTitan hw/dv/sv/jtag_agent/jtag_if.sv:51 — IEEE 1800 §14.4's
// `clocking_decl_assign`.
let f = parse_ok(
"interface i;\n clocking cb @(negedge tck);\n output tms = _tms_internal, tdi = _tdi[0];\n input tdo;\n endclocking\nendinterface\n",
);
let ItemKind::Clocking(c) = &module_of(&f).items[0].kind else {
panic!("expected a clocking block")
};
let ClockingItemKind::Signals { signals, .. } = &c.items[0].kind else {
panic!("expected a signal group")
};
assert_eq!(signals.len(), 2);
assert_eq!(signals[0].name.text, "tms");
assert!(matches!(
signals[0].value.as_ref().map(|e| &e.kind),
Some(ExprKind::Ident(n)) if n == "_tms_internal"
));
assert_eq!(signals[1].name.text, "tdi");
assert!(matches!(signals[1].value.as_ref().map(|e| &e.kind), Some(ExprKind::Index { .. })));
let ClockingItemKind::Signals { signals, .. } = &c.items[1].kind else {
panic!("expected a signal group")
};
assert!(signals[0].value.is_none(), "a plain signal binds nothing");
}
#[test]
fn a_clocking_item_still_needs_a_signal_name() {
assert_eq!(
parse_err(
"interface i;\n clocking cb @(a);\n output = x;\n endclocking\nendinterface\n"
),
"expected identifier (found \"=\")"
);
}
#[test]
fn a_default_disable_iff_is_captured_verbatim() {
// OpenTitan hw/ip/tlul/rtl/tlul_assert.sv:36 — IEEE 1800 §16.12.
let f = parse_ok(
"module m;\n default disable iff disable_sva || !rst_ni;\n wire w;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "default disable iff disable_sva || !rst_ni;");
// The item after it is still read normally.
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)), "{:?}", items[1].kind);
}
#[test]
fn a_default_disable_iff_stops_at_its_own_semicolon() {
// A `;` inside a bracketed run does not end the item; a missing one
// is still an error rather than a swallowed rest-of-file.
let f = parse_ok(
"module m;\n default disable iff x dist {1 := 1, 2 := 2};\n wire w;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "default disable iff x dist {1 := 1, 2 := 2};");
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)));
assert!(parse_err("module m;\n default disable iff a\nendmodule\n")
.starts_with("expected `;`"));
// `default disable` without `iff` is not the item: the dispatch is on
// the two keywords, and the third is required.
assert!(
parse_err("module m;\n default disable a;\nendmodule\n").starts_with("expected `iff`")
);
}
// QA (2026-08-29, `docs/features/clocking-wave/README.md`): a `;` inside a
// string literal or a comment must not end the item early, and two
// `default disable iff`s in a row must not merge into one capture. The
// scan only special-cases `(`/`[`/`{`, so both rely on the lexer already
// treating strings as one token and comments as trivia rather than tokens
// — verified directly rather than assumed.
#[test]
fn a_default_disable_iff_is_not_ended_by_a_semicolon_inside_a_string() {
let f = parse_ok("module m;\n default disable iff x == \"a;b\";\n wire w;\nendmodule\n");
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "default disable iff x == \"a;b\";");
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)));
}
#[test]
fn a_default_disable_iff_is_not_ended_by_a_semicolon_inside_a_comment() {
let f = parse_ok("module m;\n default disable iff /* ; */ x;\n wire w;\nendmodule\n");
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "default disable iff /* ; */ x;");
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)));
}
#[test]
fn two_default_disable_iffs_in_a_row_are_captured_separately() {
let f = parse_ok(
"module m;\n default disable iff a;\n default disable iff b;\n wire w;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(first) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(first.text, "default disable iff a;");
let ItemKind::Verbatim(second) = &items[1].kind else {
panic!("expected a verbatim block")
};
assert_eq!(second.text, "default disable iff b;");
assert!(matches!(items[2].kind, ItemKind::DataDecl(_)));
}
#[test]
fn an_event_control_term_may_carry_an_iff_condition() {
// OpenTitan hw/ip/spi_device/pre_dv/tb/spid_common.sv:1042 —
// IEEE 1800 §9.4.2.
let f = parse_ok(
"module m;\n always @(posedge clk iff rvalid or negedge rst_n) x <= 1;\nendmodule\n",
);
let ItemKind::Always { stmt, .. } = &module_of(&f).items[0].kind else {
panic!("expected an always block")
};
let StmtKind::Timing { control: TimingControl::Event(SensList::List(items)), .. } =
&stmt.kind
else {
panic!("expected an event control")
};
assert_eq!(items.len(), 2);
assert!(matches!(
items[0].iff.as_ref().map(|e| &e.kind),
Some(ExprKind::Ident(n)) if n == "rvalid"
));
assert!(items[1].iff.is_none(), "the gate belongs to one term, not to the list");
}
#[test]
fn a_bare_event_control_may_name_an_indexed_hierarchical_path() {
// OpenTitan .../rstmgr/dv/env/seq_lib/rstmgr_leaf_rst_cnsty_vseq.sv:200.
let f = parse_ok(
"module m;\n initial forever @cfg.cfgs[\"a\"].vif.sender_cb x <= 1;\nendmodule\n",
);
let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else {
panic!("expected an initial block")
};
let StmtKind::Forever { body } = &stmt.kind else { panic!("expected a forever loop") };
let StmtKind::Timing { control: TimingControl::Event(SensList::Bare(e)), .. } = &body.kind
else {
panic!("expected a bare event control")
};
let ExprKind::Member { base, name } = &e.kind else { panic!("expected a member access") };
assert_eq!(name, "sender_cb");
let ExprKind::Member { base, .. } = &base.kind else { panic!("expected a member access") };
assert!(matches!(base.kind, ExprKind::Index { .. }), "the bit-select is part of the path");
}
#[test]
fn a_bare_event_control_charges_the_chain_budget() {
// The loop wraps what it has built, so it must charge `link()` — the
// standing requirement in `docs/features/recursion-limit/README.md`.
let long = format!(
"module m;\n initial @a{} x <= 1;\nendmodule\n",
".b".repeat(MAX_CHAIN_LENGTH as usize + 10)
);
assert_chain_too_long(long);
}
#[test]
fn a_gate_may_carry_a_drive_strength() {
// OpenTitan hw/ip/spi_host/dv/tb.sv:101 — IEEE 1800 §28.3's
// single-strength `pullup_strength`, beside the ordinary pair.
let f = parse_ok(
"module m;\n pullup (weak1) pd (x);\n and (strong0, strong1) g (o, a, b);\n buf b1 ((a & b), c);\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::GateInstantiation(pull) = &items[0].kind else { panic!("expected a gate") };
let s = pull.strength.as_ref().expect("the single strength was parsed");
assert_eq!((s.first.as_str(), s.second.as_deref()), ("weak1", None));
let ItemKind::GateInstantiation(and) = &items[1].kind else { panic!("expected a gate") };
let s = and.strength.as_ref().expect("the strength pair was parsed");
assert_eq!((s.first.as_str(), s.second.as_deref()), ("strong0", Some("strong1")));
// A `(` that does not open a strength still opens an argument list.
let ItemKind::GateInstantiation(buf) = &items[2].kind else { panic!("expected a gate") };
assert!(buf.strength.is_none());
assert_eq!(buf.instances[0].args.len(), 2);
}
#[test]
fn a_program_is_a_module_with_a_different_closer() {
// OpenTitan hw/ip/spi_device/pre_dv/program/spiflash.sv:7 —
// IEEE 1800 §24.3.
let f = parse_ok(
"program p #(parameter int W = 1) (input logic csb);\n logic [7:0] cmd;\nendprogram : p\n",
);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a program") };
assert_eq!(m.kw, "program");
assert_eq!(m.end_kw(), "endprogram");
assert_eq!(m.name, "p");
assert_eq!(m.end_label.as_deref(), Some("p"));
assert_eq!(m.items.len(), 1);
assert!(parse_err("program p;\n wire w;\nendinterface\n")
.starts_with("unsupported construct starting with keyword `endinterface`"));
}
#[test]
fn a_macro_may_be_a_concurrent_assertions_whole_action_statement() {
// OpenTitan hw/ip/adc_ctrl/dv/sva/adc_ctrl_fsm_sva_if.sv:35 — the
// `else` arm is a macro invocation with no `;` after it.
let f = parse_ok(
"module m;\n A_A: assert property (a |=> b)\n else `ASSERT_ERROR(A_A)\n assign x = 1;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("`ASSERT_ERROR(A_A)"), "{:?}", raw.text);
assert!(matches!(items[1].kind, ItemKind::ContAssign(_)), "{:?}", items[1].kind);
}
#[test]
fn a_macro_inside_an_action_statement_is_an_operand_not_a_terminator() {
// Only a macro *starting* a statement ends it; one standing mid-way
// through an expression is a value, and the `;` still terminates.
let f = parse_ok(
"module m;\n A_A: assert property (a) else x = `VAL + 1;\n assign y = 1;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("`VAL + 1;"), "{:?}", raw.text);
assert!(matches!(items[1].kind, ItemKind::ContAssign(_)), "{:?}", items[1].kind);
}
// QA (2026-08-29, `docs/features/clocking-wave/README.md` round 2) —
// QA round-2 finding, fixed by the rework (`docs/features/clocking-wave/
// README.md`, work log 2026-08-29 rework): `skip_action_stmt` used to
// treat a macro standing first in an action as *always* the whole action.
// That is false whenever the macro's expansion is a signal name and the
// statement goes on to assign to, read or increment it — ordinary
// RTL/testbench idiom, and a parse error on input trunk accepts. The scan
// now decides by what *follows* the call (`Parser::at_statement_tail`),
// so all four shapes below parse exactly as they do on trunk while
// `` else `ASSERT_ERROR(A) `` still ends where it ends.
#[test]
fn a_macro_used_as_an_lvalue_is_not_the_whole_action_statement() {
// A macro standing for a signal name, assigned to from an `else` arm.
let f = parse_ok(
"module m;\n A_A: assert property (a) else `SOME_SIGNAL = 1'b1;\n assign y = 1;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("`SOME_SIGNAL = 1'b1;"), "{:?}", raw.text);
assert!(matches!(items[1].kind, ItemKind::ContAssign(_)), "{:?}", items[1].kind);
}
#[test]
fn a_macro_used_as_an_operand_before_an_operator_is_not_the_whole_action_statement() {
// `` `MSG(x) + 1; `` — the macro is an operand, and the `+ 1;` that
// follows it is the rest of the same statement.
let f = parse_ok(
"module m;\n A_A: assert property (a) else `MSG(x) + 1;\n assign y = 1;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("`MSG(x) + 1;"), "{:?}", raw.text);
assert!(matches!(items[1].kind, ItemKind::ContAssign(_)), "{:?}", items[1].kind);
}
#[test]
fn a_macro_counter_increment_is_not_the_whole_action_statement() {
// A common RTL/testbench idiom: a macro standing for a counter
// register, incremented from the `else` arm.
let f = parse_ok(
"module m;\n A_A: assert property (a) else `CNT <= `CNT + 1;\n assign y = 1;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("`CNT <= `CNT + 1;"), "{:?}", raw.text);
assert!(matches!(items[1].kind, ItemKind::ContAssign(_)), "{:?}", items[1].kind);
}
#[test]
fn a_macro_postfix_increment_is_not_the_whole_action_statement() {
// The fourth shape of the same finding: the macro is the operand of a
// postfix `++`, so the statement runs on past the call.
let f = parse_ok(
"module m;\n A_A: assert property (a) else `CNT++;\n assign y = 1;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("`CNT++;"), "{:?}", raw.text);
assert!(matches!(items[1].kind, ItemKind::ContAssign(_)), "{:?}", items[1].kind);
}
#[test]
fn a_macro_action_still_ends_where_no_statement_tail_follows() {
// The other side of the same decision, in each shape that can stand
// after a complete macro action: the next item's keyword, an
// identifier opening a label, another macro, and a directive.
for next in ["assign y = 1;", "B_B: assert property (b);", "`ASSERT_INIT(C, 1)", "`endif"] {
let src = format!(
"module m;\n A_A: assert property (a)\n else `ASSERT_ERROR(A_A)\n {next}\nendmodule\n"
);
let f = parse_ok(&src);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else {
panic!("expected a verbatim block for {next:?}")
};
assert!(raw.text.ends_with("`ASSERT_ERROR(A_A)"), "{next:?}: {:?}", raw.text);
assert_eq!(items.len(), 2, "{next:?}: {:?}", items.len());
}
}
#[test]
fn the_clocking_waves_shapes_survive_tolerant_recovery() {
// The language server parses every buffer tolerantly, so each new
// shape has to stay addressable next to a genuine error rather than
// swallowing the rest of the file.
let src = "interface i;\n clocking cb @(posedge clk);\n output tms = _tms;\n endclocking\n default disable iff !rst_n;\n wire ] broken;\n wire w;\nendinterface\n";
let (file, diags) = crate::parse_source_tolerant(src);
assert!(!diags.is_empty(), "the broken declaration is still an error");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected an interface") };
let kinds: Vec<&str> = m
.items
.iter()
.map(|i| match &i.kind {
ItemKind::Clocking(_) => "clocking",
ItemKind::Verbatim(_) => "verbatim",
ItemKind::DataDecl(_) => "decl",
ItemKind::Error(_) => "error",
_ => "other",
})
.collect();
assert!(
kinds.contains(&"clocking") && kinds.contains(&"verbatim") && kinds.contains(&"error"),
"the good items on either side of the broken one survive: {kinds:?}"
);
// An unterminated `default disable iff` does not eat the file either.
let (file, diags) =
crate::parse_source_tolerant("module m;\n default disable iff a\nendmodule\n");
assert!(!diags.is_empty());
assert!(!file.items.is_empty(), "and the file is still addressable");
}
#[test]
fn a_virtual_interface_type_stands_in_every_type_position() {
// corpus/ibex/dv/uvm/icache/dv/env/ibex_icache_env_pkg.sv:28 (typedef)
@@ -7744,7 +8253,7 @@ mod tests {
let items = &module_of(&f).items;
let ItemKind::ContAssign(a) = &items[0].kind else { panic!("expected an assign") };
let s = a.strength.as_ref().expect("the strength was parsed");
assert_eq!((s.first.as_str(), s.second.as_str()), ("weak0", "pull1"));
assert_eq!((s.first.as_str(), s.second.as_deref()), ("weak0", Some("pull1")));
let ItemKind::ContAssign(b) = &items[1].kind else { panic!("expected an assign") };
assert!(b.strength.is_none());
}
+3 -2
View File
@@ -19,6 +19,7 @@
use std::path::{Path, PathBuf};
use vlog_parser::ast::*;
use vlog_parser::parser::PARSE_STACK_SIZE;
use vlog_parser::{parse_source, parse_source_tolerant, ParseDiagnostic};
// ----------------------------------------------------------------------
@@ -543,7 +544,7 @@ fn the_depth_limit_still_fires_and_is_recovered_from() {
")".repeat(400)
);
let (file, diags) = std::thread::Builder::new()
.stack_size(16 * 1024 * 1024)
.stack_size(PARSE_STACK_SIZE)
.spawn(move || {
let (f, d) = parse_source_tolerant(&src);
(format!("{:?}", f.items.iter().map(kind_name).collect::<Vec<_>>()), d)
@@ -572,7 +573,7 @@ fn recovery_does_not_reset_the_nesting_budget() {
"end\n".repeat(outer),
);
let diags = std::thread::Builder::new()
.stack_size(16 * 1024 * 1024)
.stack_size(PARSE_STACK_SIZE)
.spawn(move || parse_source_tolerant(&src).1)
.expect("spawn parser thread")
.join()
+11 -2
View File
@@ -92,6 +92,13 @@ const SOURCES: &[&str] = &[
"class c;\n task t();\n if (!req.randomize() with {\n a == 1;\n b dist { 0 :/ 1 };\n }) $fatal(1, \"no\");\n endtask : t;\nendclass\n",
// DPI imports and exports, plus package re-exports.
"package p;\n import \"DPI-C\"\n function void env_final();\n import \"DPI-C\" context function chandle mk(int unsigned k, bit [7:0] v);\n import \"DPI-C\" function chandle get;\n import \"DPI-C\" pure c_name = task tick(input int n);\n export \"DPI-C\" function f;\n export \"DPI-C\" ex_name = task t;\n export q::*;\n export r::a, s::b;\n export *::*;\nendpackage\n",
// The clocking wave: clocking signals bound to an expression, the
// verbatim `default disable iff`, an `iff` on an event-control term, a
// bare event control over an indexed hierarchical path, a gate's single
// and paired drive strengths, and a `program` block.
"interface i;\n clocking cb @(negedge tck);\n default output #1ns;\n output tms = _tms_internal, tdi = _tdi[0]; // bound\n input tdo;\n endclocking\n modport host_mp(clocking cb, output trst_n);\nendinterface\n",
"module m;\n default disable iff disable_sva || !rst_ni;\n default clocking @(posedge clk_i); endclocking\n always @(posedge clk iff en or negedge rst_n) x <= 1;\n pullup (weak1) pd (x);\n pulldown (supply0, supply1) pd2 (y);\n initial forever @cfg.cfgs[\"a\"].vif.cb z <= 1;\nendmodule\n",
"program p #(parameter int W = 1) (input logic csb);\n logic [7:0] cmd;\n initial cmd = 8'h0;\nendprogram : p\n",
];
/// A token or a comment, in source order.
@@ -588,8 +595,10 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
check_opt_name(src, "endclocking label", c.end_label.as_ref(), c.end_label_span, here);
for item in &c.items {
assert_inside(src, "clocking item", item.span, here);
if let ClockingItemKind::Signals { names, .. } = &item.kind {
check_names(src, "clocking signal", names, item.span);
if let ClockingItemKind::Signals { signals, .. } = &item.kind {
for s in signals {
check_name(src, "clocking signal", &s.name.text, s.name.span, item.span);
}
}
}
}
+5
View File
@@ -1084,6 +1084,11 @@ impl<'a> Binder<'a> {
TimingControl::Event(SensList::List(items)) => {
for i in items {
self.bind_expr(&i.expr, scope);
// `@(posedge clk iff enable)` reads `enable` as ordinarily
// as it reads `clk`.
if let Some(iff) = &i.iff {
self.bind_expr(iff, scope);
}
}
}
TimingControl::Event(SensList::Star { .. }) => {}
+831
View File
@@ -0,0 +1,831 @@
# clocking-wave
## Goal
Round 2 of the testbench-syntax wave: close every remaining bucket of the
OpenTitan sweep that is a *grammar* gap rather than a preprocessing one, in one
round. Six shapes — clocking-block signal bindings (`output tms = _tms;`), the
standing `default disable iff`, an `iff` gate on an event-control term, a bare
event control naming an indexed hierarchical path, a gate's drive strength, and
`program … endprogram` — plus one engineering measurement: the chain-length
limit, which real generated register files had outgrown. The sweep goes
**43 → 11 failures**, and the eleven that remain are the two OUT rows the brief
named (macro fragments that need preprocessing, and vendor files that are not
SystemVerilog).
## Assumptions
- **Clocking blocks are already modelled, not verbatim.** The brief expected
the house verbatim-capture precedent to apply here (`constraint`,
`covergroup`, concurrent assertions). It does not: `ClockingDecl` /
`ClockingItem` have been real AST since the `interfaces` feature, with a
printer arm, span coverage and a linter guard. Converting a working modelled
construct into opaque bytes to close a one-field gap would have *lost*
information, so the fix is the one field the grammar was missing. See the
work log for the deviation.
- **The 14-file "clocking" bucket is two shapes, not one.** Reading all
fourteen sites showed seven failing on a clocking item's `= expression` and
seven on `default disable iff` — which is not a clocking construct at all
(IEEE 1800 §16.12, assertion control). The bucket label was a guess from the
error text (`unsupported construct starting with keyword 'default'`); every
site was read before a line was written.
- **A clocking block stays opaque to the semantic layer.** `analyze` treats
`ItemKind::Clocking` as a leaf and the linter takes the whole clocking item's
span out through `opaque_spans`. The `= expression` a binding adds sits
*inside* that span, so it neither declares, reads nor drives anything as far
as the lints are concerned. That is deliberate — a clocking block's signals
are driven and sampled by whatever testbench drives the block, which lucisv
does not see — and it is pinned by a lint case rather than left implicit.
- **`default disable iff` belongs in the verbatim bucket.** It holds
`expression_or_dist` (a `dist { … }` set is legal there) and it exists to
govern the concurrent assertions in its scope, which are already verbatim. A
modelled node would have been half of a grammar lucisv deliberately does not
model. It is the round's only new capture, and it ships with attack pairs.
- **A `program` block is a module.** IEEE 1800 §24.3's `program_declaration` is
the module header over the module body list with a different closer, so it
reuses `Module` the way `interface` already does. The stricter *legality*
rules a program has (no `always`, only interface instantiations) are a
checker's business; lucisv is not a legality checker.
- **Chain links, not source terms.** `MAX_CHAIN_LENGTH` counts AST layers on a
path. A generated `|` chain of *N* registers costs *N* links for the
operators plus whatever its deepest operand adds, so the number measured
below is the budget, not the register count.
- **Trailing commas are not SystemVerilog.** `named_parameter_assignment` has
no empty alternative, so `#(.A(1), .B(2),)` is invalid input that some
simulators tolerate. Skipped deliberately; see Status.
## Handshakes
**Consumed from `vlog_parser`:** nothing new.
**Promised to `vlog_formatter` / `vlog_semantic` / `vlog_linter` — AST changes
this round makes.** Every one is additive except the two marked *changed*,
which are source-incompatible and were fixed up at each site:
| node | change | consumers touched |
|---|---|---|
| `ClockingItemKind::Signals` | *changed*: `names: Vec<Name>` → `signals: Vec<ClockingSignal>` | `format.rs::clocking_item`, `vlog_parser/tests/spans.rs`; `vlog_linter/src/signals.rs` matches `{ .. }` and is unaffected |
| `ClockingSignal` | new: `{ name: Name, value: Option<Expr> }` | as above |
| `SensItem::iff` | new: `Option<Expr>` | `format.rs::sens_list`, `vlog_semantic/src/bind.rs::bind_timing` |
| `GateInstantiation::strength` | new: `Option<DriveStrength>` | `format.rs::gate_instantiation` |
| `DriveStrength::second` | *changed*: `String` → `Option<String>` | `format.rs` (one new helper, `drive_strength`) |
| `Module::end_kw()` | now answers `endprogram` for `kw == "program"` | every `Module` consumer, transparently |
**Promised to `vlog_semantic`:** an `iff` gate on an event-control term is
bound as an ordinary read (`bind_timing`). A clocking block — bindings included
— stays a leaf, and `ItemKind::Verbatim` (which `default disable iff` now also
produces at module scope) keeps its existing "mentions nothing" contract.
**Promised to `vlog_linter`:** unchanged for the verbatim capture —
`ItemKind::Verbatim` already routes to `opaque_spans`, so it inherits the right
behaviour by doing nothing, the property
`docs/features/directive-split/README.md` calls "not item scope, does not
count" as the default.
**Widened for `vlog_linter`, deliberately: a `program` is a module to every
rule.** Because `program` reuses `ItemKind::Module`, every generic
`ItemKind::Module(_)` match now picks it up for free (QA, 2026-08-29) — so
`vlog_linter::visit::items` descends into program bodies and `module-filename`
holds a one-program file to the same name-matches-file convention as a module
or an interface. That is the intended consequence of "a program is a module",
not an accident: a program block is a compilation unit with a name, a header
and a body, and every one of these rules is about exactly that. It is the same
widening `interface` already made, and it is now pinned by two cases in
`module_name_style.lint` so it cannot be reversed silently. **Filed, not fixed
here:** `rules/module_name_style.rs` hardcodes the word "module" in its
violation message regardless of `Module::kw`, so a badly-named program is
reported as ``module `FooBar` is not lower_snake_case``. That inaccuracy is
pre-existing — it has said the same thing about `interface` since before this
round — and correcting it changes a message shared with `interface` and its own
tests, which is outside this round's file set. One-line fix for whoever owns
that rule next; the cases above pin today's behaviour either way.
**Requirement met, from `docs/features/recursion-limit/README.md`:** the bare
event control's segment loop wraps what it has already built
(`Box::new(previous)` per `.name` / `[expr]`), so it charges `link()` and
restores the count it started from, the way `parse_postfix` does. It did *not*
charge before this round — a pre-existing hole in the same shape that README's
Handshakes warns about, closed here and pinned by a test.
**Changed for every consumer: `PARSE_STACK_SIZE` is now 32 MiB** (was 16). The
rule is unchanged — any thread that can reach a parse is spawned with the
constant — but the number moved, because `MAX_CHAIN_LENGTH` moved with it. See
the recursion-limit README's round 4 for the measurement.
## The chain limit — measured, not guessed
`MAX_CHAIN_LENGTH = 256` rejected seven real files. The question is not "is 256
too small" but "how long is the longest chain real code actually contains", and
then "what does that cost on the stack".
**What is needed.** A high-water-mark probe (a scratchpad copy of the
workspace, `links` recorded per file, limit raised out of the way; never built
inside the repo) over all **3,943** OpenTitan files:
| file | links needed |
|---|---|
| `top_earlgrey/ip_autogen/pinmux/rtl/pinmux_reg_top.sv` | **567** |
| `top_englishbreakfast/…/pinmux_reg_top.sv` | 519 |
| `top_darjeeling/…/pinmux_reg_top.sv` | 502 |
| `top_darjeeling/…/alert_handler_reg_top.sv` | 397 |
| `top_earlgrey/…/alert_handler_reg_top.sv` | 353 |
| `rv_dm/rtl/rv_dm_mem_reg_top.sv` | 280 |
| `top_darjeeling/…/rv_core_ibex_cfg_reg_top.sv` | 266 |
Distribution over the whole tree: 3,932 files under 128, four in 129–256, five
in 257–512, two over 512. The shape is one `|` chain per generated register
file — `(addr_hit[N] & (|(PERMIT[N] & ~reg_be))) | …` — so the number tracks
the register count and grows with the design.
**What it costs.** Minimum surviving thread stack for the whole
`format_source` pipeline, bisected one trial per subprocess (house method, same
probe style as the recursion-limit rounds), rustc 1.97.1:
| shape | debug | release |
|---|---|---|
| nested `case` at the depth limit — the old global worst case | 5 959 KiB | 775 KiB |
| `+` chain, 2048 terms | 567 KiB | 183 KiB |
| the real `or_chain` shape, 2048 terms | 567 KiB | 183 KiB |
| postfix chain (`a.b…`), 640 links | 5 911 KiB | 375 KiB |
| postfix chain, 768 | 7 079 KiB | 455 KiB |
| postfix chain, **1024** | **9 430 KiB** | 615 KiB |
| postfix chain, 1280 | 11 798 KiB | 775 KiB |
| 28 nested `case` **+** a 1024-link postfix chain inside | **9 894 KiB** | 727 KiB |
| 64 nested `case` (trips depth) + a 1024-link chain inside | 5 959 KiB | 775 KiB |
Per link: (11 798 − 5 911) / 640 = **9.20 KiB debug**, 0.63 KiB release. The
binary-operator chains that actually appear in the generated files are ~40×
cheaper than that (the formatter's `binary_chain` flattens the left spine); the
*postfix* chain is the worst case the limit has to be safe for, and it is what
the numbers above are chosen from.
**The choice: 1024, and `PARSE_STACK_SIZE` 32 MiB.**
- 1024 is 1.8× the largest chain the real tree contains, on a number that grows
with design size. 640 would have cleared today's files by 13 %, which is a
fit, not a margin — and this limit has now been outgrown once.
- At 1024 the debug worst case moves from 5 959 KiB (nesting) to **9 894 KiB**
(a maximal chain inside nesting). So, for the first time, *the chain budget
sets the global peak* — the "chains do not move the worst case" line in the
recursion-limit README stops being true and is corrected there.
- 16 MiB against 9.9 MiB is 1.65×, below the 2.7× the stack round settled on
for a failure mode that is an abort rather than a diagnostic. 32 MiB is
**3.3×**, and a thread stack costs address space rather than resident memory.
- The two peaks still compose additively rather than multiplicatively, and the
measurement shows why: 64 nested `case` *with* a 1024-link chain inside
bisects to exactly the same byte as without it (5 959 KiB), because tripping
the depth limit peaks in the parser and the chain peaks in the formatter.
The invariant becomes **64 + 1024 = 1088 layers**.
## Status / TODO
- [x] **Clocking signal bindings** — `ClockingItemKind::Signals` carries
`Vec<ClockingSignal>`; one new parse function, one printer arm. 7 files.
- [x] **`default disable iff expr;`** — verbatim item, one dispatch arm, one
scanner. 7 files (4 of them behind a second blocker, below).
- [x] **A macro as a concurrent assertion's action statement** — not in the
brief, but the next blocker on 4 of the 7 `default disable iff` files and
on 2 more. `skip_action_stmt` ends the statement at a macro invocation
when — and only when — nothing that could continue a statement follows
it (`Parser::at_statement_tail`). **This is the one change with a
whole-tree output effect; see the work log.** *Reworked after QA:* the
first shipping shape decided from the macro *starting* a statement,
which regressed four idioms where the macro is a name the statement goes
on to use.
- [x] **`iff` on an event-control term** — `SensItem::iff`, IEEE 1800 §9.4.2.
5 files. LRM scope checked: `iff` gates one *event expression term*, so
the parenthesized list is the only place it can appear — the bare
`@name` form is a `hierarchical_event_identifier` with no `iff`
alternative, and `wait`/`wait_order` take an expression, not an event
expression. Both `,` and `or` separators still work around it.
- [x] **Bare event control over an indexed path** — `.name` and `[expr]`
segments, chain-budget charged. 3 files.
- [x] **A gate's drive strength** — `GateInstantiation::strength`,
`DriveStrength::second: Option<String>`; the mop-up's documented skip.
1 file.
- [x] **`program … endprogram`** — one dispatch arm reusing `parse_module`,
one `end_kw` arm, `endprogram` added to `SYNC_CLOSERS` and `program` to
`SYNC_OPENERS`. 3 files.
- [x] **Chain limit 256 → 1024, `PARSE_STACK_SIZE` 16 → 32 MiB**, measured
above; the recursion-limit README's invariant, tables and Status updated.
7 files.
- [x] OpenTitan sweep **43 → 11**, set difference: **0 newly failing**.
- [x] Whole-tree superset check over all 3,943 files: exactly **one**
previously-passing file's output moves, and it moves because 55 lines
that used to be swallowed into an opaque verbatim blob are now parsed —
see the work log.
- [x] Corpus gate byte-identical: 813/820, and all **860** corpus files hash
identically to trunk's output.
- [x] `verify.rs` untouched; attack pairs for the one new capture.
- [x] 12 parser unit tests (negatives and a tolerant regression included), 7
`verification.rs` tests (1 re-indent + **6 attack pairs**), 3 new
`spans.rs` `SOURCES` entries, 12 formatter cases in a new
`clocking_wave.cases`, 3 lint cases pinning the opacity, 1 new
`deep_nesting` test at the combined worst case. Workspace total
2 425 → **2 625**.
- [x] **QA rework (2026-08-29):** the macro-action decision moved onto what
*follows* the call; QA's three `#[ignore]`d pins un-ignored and passing,
plus the fourth shape and both sides of the decision. Tests now
2 425 → **2 633**; the `program`-as-`Module` lint widening documented in
Handshakes and pinned by two `module_name_style.lint` cases.
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`.
**Skipped, deliberately, with reasons:**
- [ ] **`hw/dv/sv/jtag_agent/jtag_if.sv`** — its clocking blocker *is* fixed;
a second, independent, **pre-existing** blocker sits behind it. The file
opens with two rival interface headers in an `` `ifdef ``/`` `else ``
region (lines 6–12). Both are bracket-balanced complete headers, so
`at_split_conditional` — which requires the arm to have left a bracket
open — does not fire, and the parser nests the second header inside the
first and runs out of `endinterface`s. Reproduced on trunk grammar
alone (`` `ifdef G / module i #(…)(); / `else / module i #(…)(); /
`endif / wire w; / endmodule ``), so it is not a regression of this
round. Closing it means teaching `directive-split` about rival
*declaration heads that are complete*, which is a design change to the
safety-sensitive recovery, not a bucket fix. **Handshake request to a
future `directive-split` round.**
- [ ] **`SimDTM.sv`** — `wire [31:0] #0.1 x = y;`: a net delay written *after*
the type, which is where IEEE 1800 A.2.1.3 puts it. lucisv parses a net
delay only *before* the type, and `DataDecl` has one `delay` field with
one print position — so accepting the other spelling and printing it back
where it was written needs a positional field, or the safety net rightly
refuses the reordered token stream. Two AST changes for one vendor file
in `tb/unused/`. Bounded follow-up whenever a second file wants it.
- [ ] **`kmac_reduced_tb.sv`** — a trailing comma in a *named* parameter
override list (`.EntropyWidth(EntropyWidth),\n)`). Not legal
SystemVerilog: `list_of_parameter_assignments` has no empty alternative
(the empty-element allowance is for *ordered* port connections only).
lucisv rejects invalid input on purpose, and nothing else in the tree
writes it.
- [ ] **`edn_env_cfg.sv`, `compare_helper.sv`** — a `for` loop standing where a
class item goes, inside `` `uvm_object_utils_begin/end ``; and
`assign x = `X_EACH_CSR 1;` where the macro expands to a run of
`a == b &&`. Both are macro fragments: they are only grammatical after
expansion. OUT per the brief.
**Out of scope, unchanged (the 11 remaining sweep failures):**
| file | why |
|---|---|
| `cip_base_vseq__tl_errors.svh` | `include fragment — a class body with no class |
| `keccak_2share_fpv.sv`, `spi_device_scoreboard.sv` | case-arm macros |
| `riscv_custom_instr_enum.sv` | `include fragment — enum members with no enum |
| `riscv_instr_cover_group.sv` | covergroup fragment behind a macro |
| `edn_env_cfg.sv`, `compare_helper.sv` | macro fragments (above) |
| `riscv_core_setting.tpl.sv` | a Mako template, not SystemVerilog |
| `SimDTM.sv`, `kmac_reduced_tb.sv`, `jtag_if.sv` | the three skips above |
**Recommended exclude patterns** rather than grammar work, for the files that
are not SystemVerilog at all: `**/*.tpl.sv` (Mako templates),
`**/vendor/google_riscv-dv/**` and `**/pulp_riscv_dbg/tb/unused/**`. Two of the
eleven fall under these; the rest are real SystemVerilog that needs a
preprocessor.
## Work log
### 2026-08-29 — dev (round 2, the clocking wave)
**Method, and the hard rule.** Every sweep against
`/Users/guoliangchen/repo/opentitan` used `--check` or `--stdout` only, with
`git -C … status --porcelain` after every one; the checkout's single legitimate
modification (`hw/ip/aes/dv/tb/tb.sv`) was the only thing it ever reported, on
all five sweeps and both hash passes. Every bucket was read at its real
`file:line` before a line was written — which is what caught the bucket
mis-label below.
**Baseline: 43 failures over 3,943 files at trunk `5ad0772`** (the brief said
44; the difference is the brief's own count, not a moved file). Recorded
per-file with its message so every later claim is a set operation.
**The bucket table was wrong in one place, and reading the sites is what
found it.** All seven "unsupported construct starting with keyword `default`"
failures are `default disable iff <expr>;` — assertion control (§16.12), not a
clocking construct. `default clocking @(posedge clk); endclocking` already
parsed on trunk; I checked before assuming. So the 14-file bucket is 7 + 7.
**Deviation from the brief: no verbatim capture for clocking.** The brief asked
for `clocking … endclocking` captured byte-exact as a leaf, on the house
precedent. Clocking is already a modelled node with a printer, spans and a
linter guard, and the seven failures are one missing production —
`clocking_decl_assign`, §14.4's optional `= expression` on a signal. Replacing
a working model with opaque bytes to fix a one-field gap would lose the
structure the LSP and the linter already use, so the fix is the field. The
brief's *opacity* requirement still applies and is honoured where it actually
lives: `analyze` keeps `ItemKind::Clocking` a leaf and the linter takes the
clocking item's whole span — the new binding expression included — out through
`opaque_spans`, now pinned by a lint case instead of being implicit.
**The one new verbatim capture, and its attack pairs.** `default disable iff`
scans to its own `;`, skipping bracketed runs whole so a `;` inside a
`dist { … }` set does not end it early, then copies the bytes by span exactly
as `parse_concurrent_assertion` does. `verify.rs` was **not touched** and **no
normalization was added or widened**; the six attack pairs in
`tests/verification.rs` are the ones the *existing* forgiveness (indentation,
line breaks, comment re-indentation) could plausibly have masked — a flipped
polarity, a dropped operand, a dropped comment, a dropped item, a re-joined
multi-line condition, a changed `dist` weight — each asserted rejected.
**The macro action block: a bucket the brief did not have, and the round's only
output move.** Fixing `default disable iff` moved four of its seven files onto
a *new* first error, and two clocking files (`jtag_if`, `kmac_app_if`) onto one
too. All six were the same shape: `assert property (p) else `ASSERT_ERROR(A)`
with no `;`. `skip_action_stmt` scanned for a `;` and, not finding one, ran
through whatever followed. So `skip_action_stmt` now ends the statement at a
macro invocation — but **only one that starts a statement**, tracked with an
`at_stmt_start` flag reset after an `else` continues one, because a macro
standing mid-expression (`x = `VAL + 1;`) is an operand and the `;` still
terminates. Both readings have a test.
That fix is what moves `hw/ip/prim/rtl/prim_sync_reqack.sv`, the **only** one
of 3,943 files whose output changed. Before it, the `else `ASSERT_ERROR(…)` at
line 364 ran the scan through the `` `endif ``, through
`if (EnRstChks) begin : gen_assert_en_rst_chks`, and out at that block's `end`
— so ~55 lines of ordinary generate-block code were absorbed into the
assertion's opaque bytes and printed back unformatted. Now they are parsed and
laid out. Verified: the new output is a fixed point, and a whitespace-insensitive
token comparison against the source shows only line joins. This is a
correctness improvement, not a regression, and it is the reason the round's
superset check reports one move rather than zero.
**`iff`, and the LRM scope the brief asked about.** §9.4.2's
`event_expression ::= [edge_identifier] expression [iff expression]` gates one
*term*, and terms only exist inside `@( … )`. The paren-less form is
`@ hierarchical_event_identifier`, which has no `iff` alternative; `wait` takes
an expression, not an event expression. So one field on `SensItem` and one
parse line covers every position, and `iff` being a keyword means
`parse_expr` already stops in front of it. The formatter prints the gate before
the separator so it stays attached to its own term.
**The bare event control, and a pre-existing chain hole.** The `@name` path
grew `[expr]` segments beside the `.name` ones it already had (§A.9.3's
`hierarchical_identifier` is exactly names with optional bit-selects), which is
what the three rstmgr copies need. Taking both greedily is safe because no
statement begins with `.` or `[`. Lifting the loop into
`parse_bare_event_name` also closed a hole: the *existing* `.name` loop boxed
one layer per iteration without charging `link()`, which is precisely the shape
`docs/features/recursion-limit/README.md` makes a standing requirement. It now
charges, and the caller restores the count it started from the way
`parse_postfix` does.
**The gate strength, at the amortized cost the mop-up predicted.**
`DriveStrength::second` becomes `Option<String>` (one new formatter helper,
`drive_strength`, so `assign` and gates share one spelling) and
`GateInstantiation` gains `strength`. The `(` still only opens a strength when
a strength *keyword* follows it, so `buf b1 ((a & b), c);` is untouched — a
case in the table pins that.
**`program`, not in the brief's table.** Three files, and it is IEEE 1800
§24.3's "module header, module body, different closer". One dispatch arm
reusing `parse_module`, one `Module::end_kw` arm, and the two sync lists.
Taking it brings the sweep to exactly the brief's ~11 target.
**The chain limit, measured in three stages** (all in a scratchpad copy;
nothing built inside the repo, and the probes' `unsafe` static and
million-link limit never leave it): what the files need (567, whole-tree
distribution), what a link costs (9.20 KiB debug per postfix link, bisected
across four lengths so the slope is measured and not assumed), and what the
combined worst case is (9 894 KiB at 1024). Full tables and the choice above.
The one thing worth flagging is that the previous rounds' "chains do not move
the worst case" no longer holds at this budget — it did at 256, where a
maximal chain cost 2.4 MiB against nesting's 5.9 — so `PARSE_STACK_SIZE` is now
measured against the chain, and moved to 32 MiB to keep the 2.7×-or-better
margin the stack round argued for. `MAX_NESTING_DEPTH` is untouched: nothing
about this round changes which nesting a file may use.
**Deliberately not done: making the chain non-recursive in the AST.** The
brief allows that consideration only if the needed limit were absurd (>10k).
567 is not; it is a limit that was set for a smaller tree.
**Verification, in this order.** Sweep 43 → 19 → 14 → 11, `git status` clean
after each. Set difference over the failing file names: **0 newly failing**.
Whole-tree superset: `--stdout` hashed for all 3,943 files under trunk's binary
(built in a temporary detached worktree, removed afterwards) and under this
one — 0 newly failing, 32 newly passing, 1 moved (analysed above). Corpus: all
860 files hash identically to trunk, and the gate reports 813/820 unchanged.
**Files touched.** `crates/vlog_parser/src/ast.rs`,
`crates/vlog_parser/src/parser.rs`, `crates/vlog_parser/tests/spans.rs`,
`crates/vlog_formatter/src/format.rs`,
`crates/vlog_formatter/tests/cases/clocking_wave.cases` (new),
`crates/vlog_formatter/tests/verification.rs`,
`crates/vlog_formatter/tests/deep_nesting.rs`,
`crates/vlog_semantic/src/bind.rs`,
`crates/vlog_linter/tests/cases/unused_signal.lint`,
`docs/features/recursion-limit/README.md`, `TODO.md`, this README.
`crates/vlog_formatter/src/verify.rs` is **not** among them.
### 2026-08-29 (later) — dev, QA-driven rework
**QA's finding is correct, and the fix was the wrong shape rather than a
missing guard.** The first version asked *"does a macro start this
statement?"* — a question about the token before, when the information needed
is entirely in the tokens after. A macro's expansion is a piece of text: it can
be a whole statement (`` `ASSERT_ERROR(A) ``) or a signal name the statement
goes on to assign to, read or increment (`` `SIG = 1'b1; ``, `` `CNT <= `CNT +
1; ``, `` `MSG(x) + 1; ``, `` `CNT++; ``). The macro itself cannot tell those
apart; the next token can. So the decision moved:
```rust
let call = self.parse_macro_call()?;
if call.semi || !self.at_statement_tail() { … return/chain … }
// The macro was a name, not a statement. Scan on.
```
`at_statement_tail` is one line — *the cursor is a `Symbol`* — because every
way a statement continues past a name is spelled with one (`=`, `<=`, `+`,
`++`, `.`, `[`, `::`), while everything that can stand after a complete action
is a keyword, an identifier, another macro, a directive or EOF. Its doc comment
records the asymmetry that makes the one-liner safe: guessing "continues" when
the statement was in fact complete only falls back to the brute-force scan that
ran before this case existed, i.e. to trunk; guessing "complete" when it was
not is the regression, and non-symbols cannot continue an expression.
**Why not QA's literal suggestion** ("fall through to the ordinary scan
whenever `;`/`else` does not follow"): that is the *old* over-scan for the case
this round exists to fix — `` else `ASSERT_ERROR(A) `` has neither, and falling
through is exactly what swallowed 55 lines of `prim_sync_reqack.sv`. The
predicate is the missing third answer between "ends" and "scan on".
**Verified both directions against the real trunk binary**, not just the suite.
All four QA shapes now produce **byte-identical** output to `5ad0772`
(`--stdout`, diffed per shape). The six OpenTitan files this case unblocked
still parse, `prim_sync_reqack.sv` still moves exactly as documented, and the
sweep and whole-tree superset re-ran with the same numbers.
**Tests.** QA's three `#[ignore]`d pins are now active and green (their
`#[ignore]` attributes removed and the "not fixed here" comment above them
replaced with what the fix does). Added
`a_macro_postfix_increment_is_not_the_whole_action_statement` (QA's fourth
shape) and `a_macro_action_still_ends_where_no_statement_tail_follows`, which
walks the four token kinds that can stand after a complete macro action — a
keyword, a label identifier, another macro, a directive — so the *other* side
of the decision is pinned too, not just the regression side. One more
`clocking_wave.cases` entry round-trips all four shapes through the formatter.
**QA's LOW note folded in.** The `program`-as-`ItemKind::Module` lint widening
is documented in Handshakes as deliberate, with the `module-name-style` message
wording filed rather than fixed (pre-existing for `interface`, shared rule,
outside this round's file set), and pinned by two new cases in
`module_name_style.lint`.
**Files touched by the rework:** `crates/vlog_parser/src/parser.rs`,
`crates/vlog_formatter/tests/cases/clocking_wave.cases`,
`crates/vlog_linter/tests/cases/module_name_style.lint`, this README.
## QA log
### 2026-08-29 — QA agent (round 2 verification)
**Verdict: REWORK (medium-high severity, one finding), everything else
confirmed.** One real bug in the round's own charter-flagged risk area
(the `skip_action_stmt` macro heuristic); every other claim in the work
log reproduced exactly, including the chain-limit margin math with a
sabotage check that genuinely aborts.
**Method.** Read CLAUDE.md, the work log above (all three premise
corrections, all three skips), `docs/features/recursion-limit/README.md`
round 4, and the dev brief. Built the round-2 tree and a detached
`5ad0772` worktree, both `--release`, so every comparison below is
binary-vs-binary, not test-suite-vs-claim. Every OpenTitan sweep used
`--check`/`--stdout` only; `git -C .../opentitan status --porcelain`
after every pass showed only `hw/ip/aes/dv/tb/tb.sv`, never anything else.
**BLOCKING — `skip_action_stmt`'s macro-at-statement-start check ends the
scan too early when the macro is an operand or an lvalue, not a whole
statement** (`crates/vlog_parser/src/parser.rs`, the `at_stmt_start` branch
added this round, ~line 2021). The check assumes any macro token standing
first in an action is *the entire action*, terminated by its own `;` or by
chaining another one via `else`. That assumption is false whenever the
macro's expansion is only the first sub-token of a larger statement — it
stands for a signal name, not a full statement — and this happens for
completely ordinary RTL/testbench idioms:
```
A_A: assert property (a) else `SOME_SIGNAL = 1'b1; // macro as an lvalue
A_A: assert property (a) else `MSG(x) + 1; // macro as an operand (the charter's own example)
A_A: assert property (a) else `CNT <= `CNT + 1; // macro standing for a counter register
A_A: assert property (a) else `CNT++;
```
In each case `parse_macro_call` fails to eat a `;` (the next token is `=`,
`+`, `<=`, `++`), `eat_kw("else")` then also fails, and the function
returns `Ok(())` immediately — leaving the rest of the statement
(`= 1'b1;`, `+ 1;`, …) on the token stream to be misread as the start of a
new module item, which is a parse error (`expected item (found "=")`,
etc.). **Confirmed on the real debug binary, both directions:**
```
$ ./target/debug/lucisv --stdout a1_macro_lvalue.sv # round 2
error: ...: parse error: 2:46: expected item (found "=")
$ git stash && cargo build -p lucisv && ./target/debug/lucisv --stdout a1_macro_lvalue.sv # trunk 5ad0772
module m;
A_A: assert property (a) else `SOME_SIGNAL = 1'b1;
assign y = 1;
endmodule
```
All four shapes above parse cleanly on trunk (no macro special-case at all
— the old brute-force scan just runs to the real `;`) and fail to parse on
round 2. This is exactly the charter's sin #1 ("an action scan that ends
too early") and exactly the shape the charter's own example
(`` `MSG(x) + 1; ``) named as worth checking. It does **not** corrupt
output — invariant #1 holds, because the failure is an outright parse
error, not a silently-wrong reformat — but it is a genuine, reproducible
regression in *acceptance*: files with this pattern that parsed
successfully on trunk now fail to format at all. It happens not to appear
anywhere in the swept 3,943-file OpenTitan tree or the 860-file corpus
today (both reproduced clean below), which is why the round's own
sweep/superset checks did not catch it — but that is a statement about
today's two trees, not about the fix's correctness.
The macro-terminates-the-action case the round actually needed
(`` else `ASSERT_ERROR(A_A) `` with nothing after it, or chained with
`else`) is real and correctly fixed; the bug is only in how the code tells
that case apart from "a macro starts a larger statement". A plausible fix:
before committing to the short return, check that `;` or `else` *actually*
follows the macro (which the code already does, via `eat_sym`/`eat_kw`);
on failure it currently just returns anyway. It needs to instead fall back
to the ordinary token-by-token scan from wherever the macro call left the
cursor, the same way it would have if the macro check didn't exist. Left
to the dev — this changes control flow in a checked capture, not a
one-line fix.
**Permanent regression tests added**, `crates/vlog_parser/src/parser.rs`
(`mod tests`), marked `#[ignore]` (not left red — see below) with the
finding quoted in the doc comment:
`a_macro_used_as_an_lvalue_is_not_the_whole_action_statement`,
`a_macro_used_as_an_operand_before_an_operator_is_not_the_whole_action_statement`,
`a_macro_counter_increment_is_not_the_whole_action_statement`. Verified
each one currently **fails** when run explicitly
(`cargo test -p vlog_parser -- --ignored <name>`, 3 failed / 0 passed),
confirming they pin the real bug rather than being vacuous; un-ignore once
fixed. Also added three passing tests for edges that *did* hold up (below).
**Everything else in the charter, confirmed:**
1. **`default disable iff` bracket scan — solid.** Attacked with the real
binary: a `;` inside a string (`x == "a;b"`), a `;` inside a block
comment (`/* ; */`), two `default disable iff` items back to back, and
EOF before the terminating `;`. All four behave correctly (string/
comment cases parse through unaffected because the lexer already
tokenizes strings whole and comments as trivia, not because the scanner
does anything special; two-in-a-row capture separately; EOF is a clean
`expected \`;\`` error, not a swallowed rest-of-file). Added as permanent
tests: `a_default_disable_iff_is_not_ended_by_a_semicolon_inside_a_string`,
`a_default_disable_iff_is_not_ended_by_a_semicolon_inside_a_comment`,
`two_default_disable_iffs_in_a_row_are_captured_separately`. The six
`verification.rs` attack pairs are legitimate: `verify.rs` was not
touched, and none of the six rely on a normalization the capture
introduced — they exercise the *pre-existing* generic net (byte-exact
comparison outside `Directive`/`Attribute`/backtick-`Ident` tokens,
line-trim only for comments) against a new *source* of `RawText`, which
is the correct, minimal thing to test per CLAUDE.md rule 4 (no
normalization was added, so there is nothing new to attack beyond
proving the generic net still sees every token inside this capture —
which the six pairs do).
2. **Chain math — reproduced, and the margin is real, not overstated.**
`cargo test -p vlog_formatter --test deep_nesting`: 5/5 pass, including
`a_maximal_chain_inside_deep_nesting_formats` (the 9.9 MiB combined
worst case) at the shipped `PARSE_STACK_SIZE = 32 MiB`. **Sabotage
check, as the charter asked**: set `MAX_CHAIN_LENGTH = 4096` with the
stack left at 32 MiB, rebuilt — `a_maximal_chain_inside_deep_nesting_formats`
(spelled generically off the constant) now dies with a genuine
`SIGABRT` / "stack overflow" (not a graceful test failure), confirming
the chosen 1024 actually needs the 32 MiB and the margin claim is not
inflated. Reverted immediately; `cargo test -p vlog_formatter --test
deep_nesting` back to 5/5 green.
`pinmux_reg_top.sv` (567 links, the file that started the round) parses
with the release binary — `--check` reports "would reformat", not a
parse error.
3. **New-field audit.** `ClockingSignal.value`: only consumed in
`format.rs::clocking_item` and matched by `signals.rs:366`'s
`ClockingItemKind::Signals { .. }` wildcard (correctly opaque — pinned
by the three new `unused_signal.lint` cases, which I re-ran directly and
confirm: the clocking-bound signal, the `default disable iff` name, and
the `iff`-gated `enable` behave exactly as documented — opaque, opaque,
read respectively). `SensItem::iff` is bound as an ordinary read in
`bind.rs:1084-1090` (`bind_expr`), matching the lint case. `DriveStrength
::second`/`GateInstantiation::strength`: the one non-test consumer,
`format.rs::gate_instantiation`/`drive_strength`, handles `None`
correctly (prints the single-strength form). **`program`-as-`Module`
wildcard side effect (not a bug, but undocumented):** because `program`
reuses `ItemKind::Module`, every generic `ItemKind::Module(_)` match
picks it up for free — including `vlog_linter::visit::items` (so every
lint rule now descends into program bodies) and
`rules/module_filename.rs` (a one-program file is now held to the same
"file name matches the construct's name" convention as a module or
interface). Both are reasonable, consistent with the "a program is a
module" design decision, and neither is exercised by a program-specific
linter test in this round. `rules/module_name_style.rs` hardcodes the
word "module" in its violation message regardless of `.kw` — a
pre-existing cosmetic inaccuracy for `interface` from before this round
(not introduced here), now also reachable for `program`. Low severity,
not blocking; worth a one-line doc/message fix and a program lint case
whenever this area is touched again.
4. **Reproduce, all exact:**
- Sweep: **43 → 11** (trunk / round 2 release binaries, `--check` over
all 3,943 real `.sv`/`.svh` files, 32 excluded symlinks). Set
difference (round-2-fail minus trunk-fail): **empty** — zero newly
failing. The 11 match the README's table exactly (the 3 skips +
the 8 OUT files), by name.
- Whole-tree superset: hashed `--stdout` output over the 3,900
trunk-passing files under both binaries — **exactly 1** moves,
`hw/ip/prim/rtl/prim_sync_reqack.sv`. Diffed it: the moved lines are
precisely the ~55-line generate block the old scan used to swallow
into the assertion's opaque bytes (re-indented from 2-space to
4-space now that it is a real nested `if`/`always_ff`, `else if(` →
`else if (`, nothing else). Re-formatted the round-2 output a second
time: byte-identical — idempotent.
- Corpus: `scripts/corpus_gate.sh` → `813/820` passing, gate exits 0.
All **860** `.sv`/`.v`/`.svh`/`.vh` corpus files hash identical
between trunk and round 2.
- The three skips: `kmac_reduced_tb.sv` and `SimDTM.sv` fail with
byte-identical messages on both binaries. `jtag_if.sv`'s message
*does* change (trunk: `51:17 expected \`;\` (found "=")` — the
clocking blocker; round 2: `163:1 expected \`endinterface\` (found
"<eof>")` — the rival-`ifdef`-headers blocker) — this is the
documented, correct behavior, not a violation: the first blocker is
genuinely fixed, and the second is independent and pre-existing.
Verified pre-existence directly: fed the work log's own minimal
repro (`` `ifdef G / module i #(...)() / `else / module i #(...)()
/ `endif / wire w; / endmodule ``) to **both** binaries — identical
`8:1 expected \`endmodule\` (found "<eof>")` on trunk and round 2, so
the second blocker is provably not something this round introduced.
5. **Gates.** `cargo fmt --check`: clean. `cargo clippy --all-targets`:
silent. `cargo test --workspace`: green (0 failed) both before and
after my additions; my 3 new active tests pass, my 3 `#[ignore]`d
regression tests are excluded from the default run so the gate stays
green while still pinning the bug for whoever reworks it.
**Files touched by this QA pass:** `crates/vlog_parser/src/parser.rs`
(6 new tests only — 3 active, 3 `#[ignore]`d), this README's QA log.
Nothing else in the tree was modified; the `MAX_CHAIN_LENGTH` sabotage
edit was reverted before any test run that could persist it, and confirmed
reverted (`git diff 5ad0772 --stat` unchanged from the dev's own file
list). No commits made.
### 2026-08-29 (later) — QA agent, rework verification
**Verdict: SHIP.** The rework fixes the blocking finding correctly and the
fix shape (deciding by what *follows* the macro, not by what precedes it)
is the right one — my own suggested "fall through whenever `;`/`else`
doesn't follow" would have reintroduced the exact over-scan
`prim_sync_reqack.sv` needed fixed, and the dev's writeup says so
explicitly. Two new informational findings surfaced while attacking the
asymmetry claim, neither blocking; everything else reproduces.
**Charter 1 — attacking the asymmetry claim ("wrongly continues ⇒
trunk-identical").** Confirmed the mechanism first: no lexer changes this
round (`ast.rs`/`parser.rs`/tests only in the diff), `BLOCK_OPENERS`/
`BLOCK_CLOSERS` byte-identical to trunk, and the fallback loop body after
the new macro branch is textually unchanged from trunk's
`skip_action_stmt`. So *when the predicate is correct*, the fallback walks
the identical token stream through identical code from the identical
cursor position trunk would reach — the claim holds by construction, not
just by observation. Tested it anyway, real binary, both directions, per
shape:
| shape | round 2 vs trunk |
|---|---|
| `;` immediately following the macro, written on the **next source line** | byte-identical (`eat_sym` is whitespace/line-blind, so `call.semi` is `true` here regardless of the line break — the charter's premised "call.semi false" doesn't arise for a directly-adjacent `;`) |
| macro call's close paren followed by `::` (`` `GET_TYPE(x)::CONST = 1; ``) | byte-identical — `::` is a `Symbol`, correctly reads "continues," falls through, matches trunk |
| macro-only action immediately followed by `{p, q} = c;` | byte-identical — `{` is a `Symbol`, "continues," and trunk's own brute scan already swallowed the same statement (this is the *pre-existing* over-swallow class, not a new one) |
| macro-only action immediately followed by `#5 x <= 1;` | byte-identical, same reasoning |
**Two informational findings, not blocking, from pushing on the *other*
side of the same question — cases where the predicate correctly says
"complete" and *that* is what moves output away from trunk:**
- `` else `ASSERT_ERROR(A_A) `` directly followed by `(* foo *) wire w;`:
`(* ... *)` lexes as `TokenKind::Attribute`, not `Symbol`, so
`at_statement_tail` correctly says "complete." Trunk's un-special-cased
scan swallowed the attribute *and* the declaration into the assertion's
opaque bytes (same class as `prim_sync_reqack.sv`), so it printed
`(* foo *) wire w;` on one line, byte-for-byte as written. Round 2
correctly cuts the action off before the attribute, so `wire w;` is
reparsed as its own item and the formatter's ordinary
attribute-before-item rule puts `(* foo *)` on its own line — a second,
undocumented, correct output-moving case of exactly the same species as
the one the work log calls out. It does not show up in either swept
corpus today (both re-verified below at zero newly-failing / exactly one
move), so the round's specific count is accurate for the trees it was
measured against — but the "exactly one move" framing describes today's
corpora, not a ceiling on how many files this class of shape could ever
move. Worth a one-line note in the Handshakes section next time this
area is touched; not a defect.
- `` else `ASSERT_ERROR(A_A) `` directly followed by `B_LBL: assign x =
1;` (a labelled *procedural continuous assignment*, IEEE 1800 §10.6):
round 2 correctly separates the two statements (the label is an
`Ident`, not a `Symbol`), but the parser has no support for `assign` as
a *statement* inside a procedural block at all — confirmed pre-existing
and identical on trunk with the construct in isolation, no macro
involved (`initial begin assign x = 1; end` errors identically,
byte-for-byte same message and column, on both binaries). On trunk the
gap was invisible because the whole labelled statement was swallowed as
opaque verbatim bytes next to the macro; round 2's correct boundary
detection now *reaches* the gap and reports a clean parse error instead
of silently accepting unparsed text. This does not corrupt anything
(invariant #1 holds — a clean error, not partial output) and the shape
does not occur in either swept tree, so it is not a regression against
either corpus today. It is a real (if obscure) residual: any future file
combining a bare-macro assertion action with a procedural `assign`
statement immediately after it would newly report an error rather than
silently mis-swallow. Filing rather than fixing — supporting procedural
`assign`/`deassign` as statements is unrelated grammar work, out of this
round's scope.
**Charter 2 — attacking `at_statement_tail`'s `Symbol` test from the other
side.** Both named traps checked directly with the real binary: a `;` on
the line after the macro (covered in the table above — resolves via
`call.semi`, not via the predicate, so the "symbol ⇒ continues" path never
even gets exercised for this shape) and `::` after the macro's close paren
(covered above — correctly "continues," matches trunk). No case found
where the `Symbol` test itself picks the wrong side for a real construct.
**Charter 3 — pins, then sabotage.** `cargo test -p vlog_parser --lib`
filtered to the seven relevant tests (my four un-ignored pins, the dev's
new `a_macro_action_still_ends_where_no_statement_tail_follows`, and the
two originals `a_macro_may_be_a_concurrent_assertions_whole_action_statement`
/ `a_macro_inside_an_action_statement_is_an_operand_not_a_terminator`):
7/7 green, none `#[ignore]`d anymore. Inverted `at_statement_tail`
(`==` → `!=`) and reran the same seven: **6 of 7 failed** — all four of my
"continues" pins, the dev's new "complete" pin, and the original
whole-action test all broke; only the pre-existing mid-expression test
survived (it never reaches the predicate — the macro isn't at
`at_stmt_start` there). This is a stronger result than a single-direction
check: inverting the boolean breaks tests on *both* sides of the decision,
so the suite is not merely pinned to one branch. Reverted; reran clean
(7/7).
**Charter 4 — spot-re-verification, all against fresh binaries (release,
rebuilt from the reworked source; a fresh detached `5ad0772` worktree for
trunk, removed after use).** `--check`/`--stdout` only throughout;
`git -C .../opentitan status --porcelain` after every sweep showed only
`hw/ip/aes/dv/tb/tb.sv`, on every pass below.
- Sweep: **43 → 11**, identical to the pre-rework run — diffed the two
11-line failure lists directly, byte-identical set. Zero newly-failing
against trunk's 43, reconfirmed by `comm`.
- The four attack-pair table shapes above are the dev's own claim,
independently reproduced: byte-identical `--stdout` output between
trunk and round 2 for all four, diffed directly rather than taken on
the work log's word.
- Whole-tree superset: re-hashed all 3,900 trunk-passing files —
**exactly 1** moves (`prim_sync_reqack.sv`), same file as before the
rework.
- The six previously-blocked files individually re-checked: `adc_ctrl_
fsm_sva_if.sv`, `kmac_app_if.sv`, `prim_sync_reqack.sv` all "would
reformat" (no error); `jtag_if.sv` still fails at its documented,
independent second blocker (`163:1 expected endinterface`), unchanged
from the pre-rework check.
- Corpus: `scripts/corpus_gate.sh` → `813/820`, gate exits 0. All 860
`.sv`/`.v`/`.svh`/`.vh` corpus files hash identical to trunk.
**Charter 5 — gates.** `cargo fmt --check`: clean. `cargo clippy
--all-targets`: silent. `cargo test --workspace`: **2633 passed, 0
failed, 36 ignored** — up from my pre-rework count of 2628/0/39, consistent
with my three `#[ignore]`d pins now being active and green (+3 passed, -3
ignored) plus the dev's new `#[test]` additions; the `.cases`/`.lint`
additions are new cases inside existing fixture-driver tests, not new
`#[test]` functions, so they don't add to the raw count directly but are
covered by `cargo test -p vlog_formatter --test fixtures` (2/2) and
`cargo test -p vlog_linter --test lint_cases` (14/14), both green. The
number that matters — **0 failed** — is unambiguous either way.
**Files touched by this pass:** none in the tracked tree (the
`at_statement_tail` sabotage was reverted immediately after the two test
runs that bracket it, confirmed by `git diff 5ad0772 --stat` matching the
dev's rework file list exactly); this README's QA log only. No commits
made.
## Review
**2026-08-29 — lead.** Reviewed across dev, QA REWORK (a real
regression in four macro-action shapes trunk parses — latent on both
swept corpora, found only by crafted idiom), the rework, and QA's SHIP
on re-verification; gates re-run by the lead. Three things distinguish
this round. First, it corrected its own brief twice by reading real
sites — the 14-file "clocking" bucket was two seven-file families, and
clocking itself was already modelled, needing one production rather
than the capture the brief presumed. Second, the chain-limit change is
what a limit change should be: measured need (567), measured per-link
cost, a stack resized to restore the house margin, a sabotage probe
proving the margin real, one of the feature's own published claims
("chains do not move the worst case") retired on the numbers, and a
pre-existing uncharged loop closed in passing. Third, the rework's
predicate decides on the token after the macro with the failure
direction argued and then attacked: QA verified "wrongly continues
degrades to trunk-identical" by construction against the diff, not by
trust. The dev's rejection of QA's literal fix suggestion, with
reasons, is the loop working as peers rather than as a pipeline. The
two informational finds (the attribute-after-action instance of the
explained output-move class; a pre-existing procedural-assign gap now
surfacing as a clean error) are filed. Accepted; committed by the
lead. OpenTitan sweep: 151 at the wave's start, 11 now — the remainder
being macro fragments awaiting a preprocessing decision, vendor
non-SV recommended for exclusion, and three written-up skips.
+156 -21
View File
@@ -18,7 +18,7 @@ the parser's limit and needs no counter of its own.
## The invariant
> **No input can make AST depth exceed `MAX_NESTING_DEPTH + MAX_CHAIN_LENGTH`
> (64 + 256 = 320 layers) on any root-to-leaf path**, so every recursive walk
> (64 + 1024 = 1088 layers) on any root-to-leaf path**, so every recursive walk
> over the tree — the formatter's, the `Doc` tree's, and the implicit
> recursive `Drop` — is bounded too.
@@ -29,7 +29,7 @@ finishes:
| | counter | limit | charged by |
|---|---|---|---|
| **Nesting** — one parser recursion per layer | `depth` | `MAX_NESTING_DEPTH` = 64 | the 5 gated `parse_*` functions |
| **Chains** — a loop that wraps what it already built | `links` | `MAX_CHAIN_LENGTH` = 256 | postfix segments, binary/`inside` operator chains |
| **Chains** — a loop that wraps what it already built | `links` | `MAX_CHAIN_LENGTH` = 1024 | postfix segments, binary/`inside` operator chains, a bare event control's path |
The chain counter exists because a loop can deepen the AST without deepening
the parser: `a.b.b.b…` costs `parse_postfix` a single frame but builds one
@@ -39,8 +39,8 @@ landed (QA finding, 2026-08-19).
Because both counters accumulate along a path rather than per construct,
nesting and chains cannot multiply: a chain inside another chain's operand
stacks on top of it, so `f(a.b…)(a.b…)…` is bounded by the same 320 layers,
not by 64 × 256.
stacks on top of it, so `f(a.b…)(a.b…)…` is bounded by the same 1088 layers,
not by 64 × 1024.
## Assumptions
@@ -86,8 +86,8 @@ not by 64 × 256.
```
MAX_NESTING_DEPTH = 64 (crates/vlog_parser/src/parser.rs)
MAX_CHAIN_LENGTH = 256
PARSE_STACK_SIZE = 16 MiB
MAX_CHAIN_LENGTH = 1024 (was 256 until 2026-08-29)
PARSE_STACK_SIZE = 32 MiB (was 16 MiB until 2026-08-29)
```
The first two bound the input. The third bounds nothing — it is what the
@@ -100,7 +100,7 @@ Going one past either limit produces an ordinary parse error:
```
error: rtl/deep.sv: parse error: 32:5: nesting too deep (limit 64) (found "clk")
error: rtl/chain.sv: parse error: 2:525: expression chain too long (limit 256) (found ".")
error: rtl/chain.sv: parse error: 2:525: expression chain too long (limit 1024) (found ".")
```
### Why 64 — measured, not guessed
@@ -165,7 +165,7 @@ costs three more levels (the statement plus `parse_ternary`/`parse_unary` for
its expression). The parser's own boundary unit tests use the empty-block
construction (62/63); `vlog_formatter`'s use the ones with content.
### Why 256 for chains
### Why 256 for chains — superseded 2026-08-29, see "Why 1024" below
Same method, measuring inputs sized to sit exactly *at* the limits so the
formatter really walks them (min surviving thread stack, debug / release):
@@ -190,7 +190,67 @@ fits). Charging chain links against `MAX_NESTING_DEPTH` instead would have
capped those at ~60 terms and rejected real code; that is why chains get
their own, larger budget rather than sharing the nesting one.
### The stack the limit needs — re-measured 2026-08-28
### Why 1024 for chains — 2026-08-29
**256 was not enough for real code.** OpenTitan's generated register files
build one `|` chain per register file, `(addr_hit[N] & (|(PERMIT[N] &
~reg_be))) | …`, so the chain length tracks the register count. A high-water
probe over all 3,943 files (a scratchpad copy with the limit raised out of the
way and `links` recorded; never built inside the repo) says what they need:
| file | links |
|---|---|
| `top_earlgrey/ip_autogen/pinmux/rtl/pinmux_reg_top.sv` | **567** |
| `top_englishbreakfast/…/pinmux_reg_top.sv` | 519 |
| `top_darjeeling/…/pinmux_reg_top.sv` | 502 |
| `top_darjeeling/…/alert_handler_reg_top.sv` | 397 |
| `top_earlgrey/…/alert_handler_reg_top.sv` | 353 |
| `rv_dm/rtl/rv_dm_mem_reg_top.sv` | 280 |
| `top_darjeeling/…/rv_core_ibex_cfg_reg_top.sv` | 266 |
3,932 of the 3,943 files stay under 128; five sit in 257–512 and two pass 512.
Seven files were rejected outright at 256, which is the acceptance failure this
budget exists to avoid.
**What a link costs, re-measured at the new sizes** (same method: one trial per
subprocess, bisect the smallest surviving thread stack, whole `format_source`;
rustc 1.97.1):
| shape | debug | release |
|---|---|---|
| postfix chain (`a.b…`), 640 links | 5 911 KiB | 375 KiB |
| postfix chain, 768 | 7 079 KiB | 455 KiB |
| postfix chain, **1024** | **9 430 KiB** | 615 KiB |
| postfix chain, 1280 | 11 798 KiB | 775 KiB |
| `+` chain / the real `or_chain` shape, 2048 terms | 567 KiB | 183 KiB |
| 28 nested `case` + a 1024-link postfix chain inside | **9 894 KiB** | 727 KiB |
| 64 nested `case` (trips depth) + a 1024-link chain inside | 5 959 KiB | 775 KiB |
Per link, from the slope: **9.20 KiB debug**, 0.63 KiB release — consistent
with the ~9 KiB the 2026-08-19 round measured at 256. Binary-operator chains,
which is what the generated files actually contain, are ~40× cheaper because
`binary_chain` flattens the left spine; the *postfix* chain is what the budget
has to be safe for.
**Two things this changes.**
1. **Chains now set the global worst case.** At 256 a maximal chain peaked at
~2.4 MiB against nesting's ~5.9, which is why both earlier rounds could say
"the chain budget does not move the worst case". At 1024 it peaks at
~9.4 MiB alone and **9 894 KiB** inside nesting, so that sentence is retired:
`PARSE_STACK_SIZE` is now measured against the chain.
2. **The additive-composition argument is unchanged, and the measurement shows
it directly.** 64 nested `case` *with* a 1024-link chain inside bisects to
exactly the same byte as without it (5 959 KiB), because tripping the depth
limit peaks in the parser while a chain peaks in the formatter. Nothing
multiplies.
**Why 1024 and not 640.** 640 would clear today's largest file by 13 % — a fit,
not a margin, on a number that grows with design size, and this limit has now
been outgrown once. 1024 is 1.8× the measured maximum and costs 3.5 MiB of
debug stack over 640, which the constant below absorbs.
### The stack the limit needs — re-measured 2026-08-28, and again 2026-08-29
Same method as above (subprocess per trial, bisect the smallest thread stack
that survives), but over the *whole* consumer pipeline this time —
@@ -234,17 +294,21 @@ Three things the same sweep settles:
its own; it is two orders of magnitude under the walk that produced the
tree. Same for the tolerant recovery: strict and tolerant parses of the
same limit-tripping input bisect to the same byte.
- **Chains still do not move the worst case.** A 256-link chain alone peaks
at 2487 KiB debug (~9 KiB per link); the same chain inside 58 nested `case`
measures 5895 KiB — identical to that nesting without any chain, because
the two peak in different phases. The additive-composition argument above
is unchanged.
- **16 MiB is the constant, and it is margin rather than a fit.** 8 MiB —
what the CLI's pool used and what a stock main thread happens to have —
is 1.33× the debug worst case, and the last two years of this number moving
(3.9 → 5.9 MiB, no parser change) say that is not enough room. 16 MiB is
2.7×, costs address space rather than memory (thread stacks are committed a
page at a time), and is the size the feature's tests already spawned.
- ~~**Chains still do not move the worst case.**~~ **Retired 2026-08-29.** It
was true at `MAX_CHAIN_LENGTH = 256`: a 256-link chain alone peaked at
2487 KiB debug (~9 KiB per link), and the same chain inside 58 nested `case`
measured 5895 KiB — identical to that nesting without any chain, because the
two peak in different phases. At 1024 the chain peaks at ~9.4 MiB and *is*
the worst case. The phase argument still holds; only the ranking changed.
- ~~**16 MiB is the constant.**~~ **Superseded 2026-08-29 by 32 MiB**, for the
same reason 16 replaced 8: the margin, not the fit, is the point. The
measured worst case is now **~9.7 MiB debug** (a maximal chain inside
nesting, 9 894 KiB) rather than ~5.9; 16 MiB would be 1.65× of that, below
the 2.7× this feature settled on for a failure mode that aborts instead of
returning. 32 MiB is **3.3×**, costs address space rather than memory (thread
stacks are committed a page at a time), and is what the feature's tests now
spawn. The full 2026-08-29 measurement is under "Why 1024 for chains" above
and in `docs/features/clocking-wave/README.md`.
## Where the counters sit
@@ -294,6 +358,7 @@ missed):
|---|---|
| `parse_postfix` | `a.b`, `a::b`, `a[i]`, `a[m:l]`, `a(args)`, `a'(x)`, `a++`/`a--` — one link per segment |
| `parse_binary` | `a + b + c…` (one link per operator, any precedence) and `a inside {…} inside {…}` |
| `parse_bare_event_name` | `@a.b.c`, `@a["k"].b` — the `.name` / `[expr]` segments of a paren-less event control's hierarchical path (added 2026-08-29; the `.name` half of this loop existed un-charged before, which was the last instance of the hole below) |
Not charged at all, and why:
@@ -357,7 +422,7 @@ not inflate depth — the output of a max-depth file re-parses inside
- **Promised to `vlog_formatter`:** AST depth on any path is bounded by
`vlog_parser::parser::MAX_NESTING_DEPTH + MAX_CHAIN_LENGTH` (both public,
so tests and any future consumer can reference them instead of hard-coding
64 and 256). The formatter may keep its recursive walk as long as every
64 and 1024). The formatter may keep its recursive walk as long as every
path is a structural descent and no public API accepts an externally built
AST.
- **Requirement on future `vlog_parser` work:** any new loop that wraps the
@@ -464,6 +529,34 @@ Round 3 — the stack the limit needs (2026-08-28, from a QA finding on
- [x] `cargo test --workspace` (2425), `cargo clippy --all-targets`,
`cargo fmt --check` all clean.
Round 4 — the chain budget real code outgrew (2026-08-29, from the
testbench-syntax wave's round 2; see `docs/features/clocking-wave/README.md`):
- [x] Measured what real code needs before choosing anything: a per-file
high-water probe over all 3,943 OpenTitan files. Longest chain **567**
(`pinmux_reg_top.sv`); seven files were rejected at 256.
- [x] Re-measured the per-link stack cost across four lengths so the slope is
measured rather than assumed: **9.20 KiB per postfix link** in a debug
build, 0.63 KiB in release.
- [x] `MAX_CHAIN_LENGTH` 256 → **1024** (1.8× the measured maximum), and the
invariant restated: 64 + 1024 = **1088 layers**.
- [x] `PARSE_STACK_SIZE` 16 → **32 MiB**, from the re-measured worst case
(**9 894 KiB** debug: a maximal chain inside statement nesting) at the
same 2.7×-or-better margin the 2026-08-28 round argued for.
- [x] The "chains do not move the worst case" claim retired with the
measurement that retires it; the phase argument that makes the two
counters additive re-verified at the new size (64 nested `case` with and
without a 1024-link chain bisect to the same byte).
- [x] The last un-charged chain loop found and closed:
`parse_sens_list`'s paren-less `@a.b.c` path boxed a layer per `.name`
without charging `link()`. Now `parse_bare_event_name`, charging both
segment kinds and restoring the count it started from, with a test.
- [x] `deep_nesting.rs` gained the combined worst case
(`a_maximal_chain_inside_deep_nesting_formats`), and its past-the-limit
case now spells `MAX_CHAIN_LENGTH + 1` instead of a hard-coded 1500.
- [x] `MAX_NESTING_DEPTH` left at 64: nothing in this round changes which
nesting a file may use.
## Work log
### 2026-08-19 — dev agent
@@ -696,6 +789,48 @@ two pre-existing helpers re-pointed at the constant). `cargo clippy
`crates/vlog_semantic/tests/deep_nesting.rs` (new),
`docs/features/parallel-files/README.md`, `TODO.md`, this README.
### 2026-08-29 — dev, the chain budget real code outgrew
Written as part of the testbench wave's round 2; the full narrative, the
whole-tree distribution and the probe method are in
`docs/features/clocking-wave/README.md`. What matters here:
- **The trigger was acceptance, not a crash.** Seven real OpenTitan files —
generated register tops — were being *rejected* with `expression chain too
long (limit 256)`. The 2026-08-19 round chose 256 for exactly this reason
("256 covers a 256-term generated sum") against a smaller tree; the tree
grew. Measured the whole 3,943-file distribution rather than the seven, so
the new number is chosen against the shape of real generated code (max 567,
five files in 257–512, two over 512) instead of against the failures.
- **Re-measured the slope, did not extrapolate the old number.** Four chain
lengths (640/768/1024/1280), debug and release, bisected one trial per
subprocess. 9.20 KiB per postfix link debug — close to the ~9 KiB measured at
256, so the cost is genuinely linear and 1024 lands where arithmetic says.
- **The honest finding: this round breaks one of the feature's own claims.**
Both earlier rounds concluded that raising the chain budget is free on the
stack, because chains peaked at 2.4 MiB against nesting's 5.9. At 1024 a
maximal chain peaks at 9.4 MiB alone and 9.9 MiB inside nesting, so the chain
is now the global worst case and the claim is retired above rather than
quietly left standing. What survives — and was re-verified, not assumed — is
the *reason* it was ever true: the two peak in different phases, so they
compose additively. 64 nested `case` with and without a 1024-link chain
inside bisect to the identical 5 959 KiB.
- **`PARSE_STACK_SIZE` follows the measurement, as designed.** 16 MiB is 1.65×
the new worst case; the constant's whole argument is margin over fit, so it
moves to 32 MiB (3.3×). No consumer changes: every parse site already spells
the constant, which is exactly what round 3 put it there for.
- **One un-charged chain loop found while working nearby.**
`parse_sens_list`'s paren-less `@a.b.c` path built one `Expr::Member` per
segment in a loop without charging `link()` — the `Box::new(previous)` shape
this README's Handshakes makes a standing requirement, missed because the
loop lives in the event-control code rather than in `parse_postfix`. Lifted
into `parse_bare_event_name`, charging both segment kinds and restoring the
count it started from; `a_bare_event_control_charges_the_chain_budget` pins
it.
- Files touched here: `crates/vlog_parser/src/parser.rs` (three doc comments,
the two constants, the new chain site),
`crates/vlog_formatter/tests/deep_nesting.rs`, this README.
## QA log
### 2026-08-19 — QA agent