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

+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());
}