Files
lucisv/crates/vlog_parser/src/parser.rs
T
lucioandClaude Fable 5 7881cc869c Directives may open inside a statement, and comments keep their owners
Bucket 7: the mirror image of directive-split — an `ifdef opening
INSIDE an assign RHS, expression or instantiation head, where all
three existing directive features trigger on a closing directive and
could not fire. The construct is captured verbatim by two mirror
recoveries sharing one capture step (statement-level first, item-level
behind it), construct_end classifying the head (Semi /
endfunction+label / Unknown -> refuse rather than guess), and
terminated_in_arm honoring both real terminator placements. Both
flagship tb.sv files needed only take_list_directives to stop
harvesting an outer region's `else as a list element. OpenTitan sweep
107 -> 100, exactly the 7 targets (chip_if.sv x2, chip_earlgrey
asic/cw340, jtag_dtm_reg_block, both top_* tb.sv), zero regressions,
corpus per-file byte-identical to baseline.

Also delivers Lane B's Handshake: take_before_open's queue drain was
necessary-but-not-sufficient — CallComments::dangling drained the
same way — both now behind Parser::take_gap (comments kept only when
span.start >= last_end()), verified by composing with Lane B's tree:
keymgr_scoreboard.sv formats, closing the last bucket-2 file.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 13:38:02 -07:00

8463 lines
365 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Recursive-descent parser producing the AST in [`crate::ast`].
//!
//! Comment plumbing: [`Parser::bump`] moves any leading comments of a
//! consumed token into `pending_leading` and its trailing comment into
//! `pending_trailing`. Statements/items/list elements harvest those at
//! well-defined points; anything left over is folded into the next node's
//! leading comments so no comment is ever dropped.
//!
//! Depth limiting: recursive descent means input nesting becomes call
//! nesting, and a stack overflow aborts the process (it is not a catchable
//! panic). Every parse function that can recurse without consuming a bounded
//! number of tokens per level brackets itself with [`Parser::enter`] /
//! [`Parser::leave`], turning nesting past [`MAX_NESTING_DEPTH`] into an
//! ordinary [`ParseError`].
//!
//! Error tolerance: [`parse`] stops at the first error, which is what the
//! formatter needs. [`parse_tolerant`] shares this same grammar code but
//! recovers instead — see `docs/features/error-recovery/README.md`.
use crate::ast::*;
use crate::span::TextRange;
use crate::token::{Comment, Token, TokenKind};
#[derive(Debug, Clone)]
pub struct ParseError {
pub line: u32,
pub col: u32,
pub message: String,
}
impl std::fmt::Display for ParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}: {}", self.line, self.col, self.message)
}
}
impl std::error::Error for ParseError {}
/// An error [`parse_tolerant`] recovered from, in the same words a
/// [`ParseError`] would have used plus the byte range it points at.
#[derive(Debug, Clone)]
pub struct ParseDiagnostic {
/// What went wrong, e.g. ``expected `;` (found "endmodule")``.
pub message: String,
/// 1-based line of the token the parser gave up on.
pub line: u32,
/// 1-based column (in bytes) of that token.
pub col: u32,
/// Byte extent of that token; empty at end of file.
pub span: TextRange,
}
impl std::fmt::Display for ParseDiagnostic {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}: {}", self.line, self.col, self.message)
}
}
type PResult<T> = Result<T, ParseError>;
const TYPE_KEYWORDS: &[&str] = &[
"logic",
"reg",
"bit",
"byte",
"shortint",
"int",
"longint",
"integer",
"time",
"realtime",
"real",
"shortreal",
"string",
"chandle",
"event",
"void",
];
const NET_KEYWORDS: &[&str] =
&["wire", "tri", "tri0", "tri1", "wand", "wor", "trireg", "supply0", "supply1", "uwire"];
const GATE_KEYWORDS: &[&str] = &[
"and", "or", "nand", "nor", "xor", "xnor", "not", "buf", "bufif0", "bufif1", "notif0",
"notif1", "pullup", "pulldown", "cmos", "rcmos", "nmos", "pmos", "rnmos", "rpmos", "tran",
"rtran", "tranif0", "tranif1", "rtranif0", "rtranif1",
];
/// The elaboration system tasks: the only `$...` calls that may stand where a
/// module or generate item belongs (IEEE 1800 §20.11). The list is closed —
/// `$display(...)` at module scope is still an error, because it is only legal
/// inside a procedural block.
const ELAB_TASKS: &[&str] = &["$fatal", "$error", "$warning", "$info"];
/// Keywords that close a construct an enclosing parse loop is waiting for.
/// Recovery stops *before* them without consuming, so the loop that opened the
/// construct still gets to close it — that is what keeps an error inside a
/// generate block from eating the `endgenerate`.
const SYNC_CLOSERS: &[&str] = &[
"end",
"endmodule",
"endinterface",
"endpackage",
"endgenerate",
"endfunction",
"endtask",
"endcase",
"endclass",
"endclocking",
"join",
"join_any",
"join_none",
];
/// Keywords that can only *begin* a construct at file scope. Recovery stops
/// before them too, so garbage written in front of a module cannot swallow it.
/// `class` is deliberately absent: unlike a module or a package it nests
/// (inside a package, and inside another class), so stopping recovery before
/// one would end the enclosing body at the wrong place.
const SYNC_OPENERS: &[&str] = &["module", "macromodule", "interface", "package"];
/// Keywords that may stand *before* the one that names a class member:
/// `virtual function`, `pure virtual task`, `extern function`,
/// `local rand int x`, `protected static function`. They are looked at
/// without being consumed (see [`Parser::member_head`]) so the construct they
/// belong to keeps ownership of them.
const MEMBER_QUALIFIERS: &[&str] = &[
"virtual",
"pure",
"extern",
"local",
"protected",
"rand",
"randc",
"static",
"automatic",
"const",
"var",
];
/// Keywords that open a statement block [`Parser::skip_action_stmt`] skips as
/// one unit. `fork` counts only where it opens a block: `disable fork` and
/// `wait fork` name the enclosing one.
const BLOCK_OPENERS: &[&str] = &["begin", "fork", "case", "casex", "casez", "randcase"];
/// Keywords that close one of [`BLOCK_OPENERS`]. Which opener a closer belongs
/// to is not checked — the scan only counts — so unbalanced input runs to the
/// end of the file and reports a clean error there.
const BLOCK_CLOSERS: &[&str] = &["end", "join", "join_any", "join_none", "endcase"];
const ASSIGN_OPS: &[&str] =
&["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<<=", ">>>="];
/// The strength keywords a drive strength is written from (IEEE 1800 §28.11).
const DRIVE_STRENGTHS: &[&str] = &[
"supply0", "supply1", "strong0", "strong1", "pull0", "pull1", "weak0", "weak1", "highz0",
"highz1",
];
/// How deeply constructs may nest before the parser gives up.
///
/// Chosen from measured stack use, not from taste: nested statements are the
/// most expensive family at ~94 KiB of stack per level in an unoptimized
/// build, so the whole pipeline on an input that trips the limit peaks at
/// ~5.9 MiB there and ~0.8 MiB in an optimized build. That budget is only
/// safe on a thread big enough to hold it, which is what
/// [`PARSE_STACK_SIZE`] names — this limit bounds how *many* levels run, not
/// what one costs. Real RTL nests roughly an order of magnitude less than
/// this; see `docs/features/recursion-limit/README.md`.
pub const MAX_NESTING_DEPTH: u32 = 64;
/// How much stack a thread that parses must be given.
///
/// [`MAX_NESTING_DEPTH`] turns over-deep input into a parse error instead of
/// a stack overflow, but only on a thread that can hold the levels it *does*
/// allow: the guard fires at level 64, and reaching level 64 costs stack. On
/// a smaller thread the overflow happens first, and a stack overflow is an
/// 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.
///
/// 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.
///
/// Every thread that may reach a parse is spawned with at least this:
/// `std::thread::Builder::new().stack_size(PARSE_STACK_SIZE)`, or
/// `rayon::ThreadPoolBuilder::new().stack_size(PARSE_STACK_SIZE)`. Thread
/// 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;
/// How many links a left-nested chain may add to the tree on one path.
///
/// Some constructs are parsed by a loop rather than by recursion — postfix
/// segments (`a.b`, `a::b`, `a[i]`, `a(x)`, `a++`) and binary/`inside`
/// operator chains (`a + b + c`) — but each iteration still wraps what came
/// before in another AST layer, which the *formatter* then recurses over.
/// They therefore get their own budget: it is accumulated along a path the
/// 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;
/// The three pieces a `#( parameter ... )` port list yields, so module and
/// class headers can share one parse.
#[derive(Default)]
struct ParamPortList {
/// `None` when no `#( ... )` was written at all.
ports: Option<Vec<ParamPort>>,
directives: Vec<ListDirective>,
dangling: Vec<Comment>,
}
/// What [`Parser::take_list_directives`] found between two list elements.
#[derive(Default)]
struct Harvested {
/// At least one directive stood here.
any: bool,
/// One of them carried the `,` that separates the surrounding elements,
/// so the list continues even though the previous element wrote no comma.
carried_comma: bool,
}
pub struct Parser<'a> {
tokens: Vec<Token>,
pos: usize,
pending_leading: Vec<Comment>,
pending_trailing: Vec<Comment>,
/// Currently open nested constructs; see [`MAX_NESTING_DEPTH`].
depth: u32,
/// Chain links open on the current path; see [`MAX_CHAIN_LENGTH`].
links: u32,
/// Conditional-compilation regions open **at item scope** at the cursor:
/// one per `` `ifdef `` / `` `ifndef `` that stood as an item and has not
/// been closed by an `` `endif `` standing as an item.
///
/// Kept as running state because the split-conditional recovery must know
/// whether a closing directive closes anything at all — a stray
/// `` `endif `` is broken input, not a split. Maintained by exactly two
/// places, [`Parser::note_item_conditional`] and
/// [`Parser::split_conditional_item`]; see the former's doc for why it is
/// *not* maintained in [`Parser::bump`].
open_conds: u32,
/// Recover from errors instead of returning them; see [`parse_tolerant`].
tolerant: bool,
/// The text the tokens were lexed from, in both modes: recovery copies a
/// skipped range into an error node out of it, and so do the verbatim
/// class-scope blocks.
source: &'a str,
/// Errors recovered from, in source order. Always empty in strict mode.
diagnostics: Vec<ParseDiagnostic>,
}
/// Parse a token stream, stopping at the first error.
///
/// `source` must be the exact text `tokens` were lexed from: the constructs
/// lucisv keeps verbatim (`constraint`, `covergroup` — see
/// `docs/features/classes/README.md`) copy their bytes out of it by span.
///
/// Recurses with input nesting: call this only on a thread with at least
/// [`PARSE_STACK_SIZE`] of stack, or over-deep input aborts the process
/// instead of returning `Err`.
pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
Parser::new(tokens, source, false).parse_source_file()
}
/// Parse a token stream that may be broken, recording errors instead of
/// failing.
///
/// The unparsable parts of the file become [`ItemKind::Error`] /
/// [`StmtKind::Error`] leaves holding the source text they cover, so the tree
/// still spans the whole file. `source` must be the exact text `tokens` were
/// lexed from. On a well-formed file the tree is identical to [`parse`]'s and
/// the diagnostics are empty.
///
/// Same stack requirement as [`parse`]: needs a thread with at least
/// [`PARSE_STACK_SIZE`] of stack, recovery included — tolerant and strict
/// parses of the same over-deep input overflow at the same depth.
pub fn parse_tolerant(tokens: Vec<Token>, source: &str) -> (SourceFile, Vec<ParseDiagnostic>) {
let mut p = Parser::new(tokens, source, true);
match p.parse_source_file() {
Ok(file) => (file, p.diagnostics),
// Unreachable in practice: every error path inside a file body is
// recovered. Rather than assert that, fall back to one error item
// covering the file, which is what a lex-level failure gets too.
Err(e) => {
let span = TextRange::new(0, source.len() as u32);
let diag = ParseDiagnostic { message: e.message, line: e.line, col: e.col, span };
let mut diagnostics = p.diagnostics;
diagnostics.push(diag);
(error_file(source), diagnostics)
}
}
}
/// A `SourceFile` that is one error item covering the whole text — what a
/// caller gets when the text cannot even be tokenized.
pub(crate) fn error_file(source: &str) -> SourceFile {
let span = TextRange::new(0, source.len() as u32);
let raw = RawText { text: source.to_string(), col: 1, span };
let item = Item { meta: Meta::default(), kind: ItemKind::Error(raw), span };
SourceFile { items: vec![item], dangling: Vec::new(), span }
}
/// True when `t` is one of the strength keywords a drive strength names.
fn is_drive_strength(t: &Token) -> bool {
t.kind == TokenKind::Keyword && DRIVE_STRENGTHS.contains(&t.text.as_str())
}
/// Where an item — or a statement — started, for the recovery that may have to
/// replace it whole.
struct ItemMark {
/// Index of the construct's first token, past its attributes.
pos: usize,
/// Conditional regions open at that token.
conds: u32,
/// Diagnostics recorded before the item ran; a replaced parse's notes are
/// dropped back to this length (tolerant mode only — strict has none).
diags: usize,
}
/// The word a compiler-directive token spells, without its backtick and
/// without its argument: `` `ifndef FOO `` is `"ifndef"`. The empty string for
/// anything that is not a directive token.
fn directive_word(t: &Token) -> &str {
if t.kind != TokenKind::Directive {
return "";
}
directive_word_of(&t.text)
}
/// Keywords that open a body, so that the first `;` after them closes a
/// *header* — or a statement inside the body — rather than the construct.
///
/// `function` and `task` are handled separately, by [`ConstructEnd::Keyword`];
/// these are the ones the opening-split recovery refuses outright, because
/// nothing in the corpus asks for them and capturing at a `;` would leave a
/// truncated head with its body orphaned behind it.
const BODY_KEYWORDS: &[&str] = &[
"module",
"macromodule",
"interface",
"program",
"package",
"class",
"checker",
"config",
"primitive",
"specify",
"generate",
"covergroup",
"property",
"sequence",
"clocking",
"constraint",
"begin",
"fork",
"case",
"casex",
"casez",
"randcase",
"for",
"foreach",
"while",
"repeat",
"forever",
"do",
"if",
"initial",
"final",
"always",
"always_comb",
"always_ff",
"always_latch",
];
/// Keywords that may stand in front of a `function` / `task` without changing
/// what closes it. `extern` and `pure` are deliberately absent: those spell a
/// prototype, which really does end at its `;`.
const TF_QUALIFIERS: &[&str] = &["virtual", "static", "automatic", "local", "protected"];
/// What the opening-split extent scan must look for to know a construct ended.
#[derive(Clone, Copy, PartialEq)]
enum ConstructEnd {
/// Its own `;` — every declaration, every instantiation, every simple
/// statement, and what `directive-split` has always assumed.
Semi,
/// The closing keyword named, which the header's `;` only precedes.
Keyword(&'static str),
/// Not modeled: refuse rather than capture a truncated head.
Unknown,
}
/// How the construct starting at `head` ends.
///
/// Read from the head alone, because that is all the recovery knows: the parse
/// already failed, so there is no node to ask. `jtag_dtm_reg_block.sv` is why
/// this exists — its split `function new(` header stopped the scan at the
/// header's own `;` and left `super.new(...)` behind as an item.
fn construct_end(head: &[Token]) -> ConstructEnd {
let mut i = 0;
while let Some(t) = head.get(i) {
if t.kind != TokenKind::Keyword {
// An identifier head: an instantiation, a call statement, an
// assignment. All of them end at a `;`.
return ConstructEnd::Semi;
}
match t.text.as_str() {
w if TF_QUALIFIERS.contains(&w) => i += 1,
"function" => return ConstructEnd::Keyword("endfunction"),
"task" => return ConstructEnd::Keyword("endtask"),
w if BODY_KEYWORDS.contains(&w) => return ConstructEnd::Unknown,
_ => return ConstructEnd::Semi,
}
}
ConstructEnd::Unknown
}
/// [`directive_word`] over the source text of a directive already captured as
/// a [`RawText`], for the harvested lines a list keeps rather than a token.
fn directive_word_of(text: &str) -> &str {
let rest = text.strip_prefix('`').unwrap_or("");
let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len());
rest.get(..end).unwrap_or("")
}
/// `` `ifdef `` / `` `ifndef ``: opens a conditional-compilation region.
fn opens_conditional(t: &Token) -> bool {
matches!(directive_word(t), "ifdef" | "ifndef")
}
/// `` `else `` / `` `elsif ``: starts the next arm of the region already open.
fn continues_conditional(t: &Token) -> bool {
matches!(directive_word(t), "else" | "elsif")
}
/// `` `endif ``: closes the region already open.
fn closes_conditional(t: &Token) -> bool {
directive_word(t) == "endif"
}
/// Move the comments written at or after byte `gap` out of `queue` and onto
/// `out`, in source order, leaving the earlier ones queued where they were.
fn take_since(queue: &mut Vec<Comment>, gap: u32, out: &mut Vec<Comment>) {
for c in std::mem::take(queue) {
if c.span.start >= gap {
out.push(c);
} else {
queue.push(c);
}
}
}
/// Split an optional [`Name`] into the `(text, span)` pair the nodes that keep
/// a name in a `String` field store it as.
fn split_label(name: Option<Name>) -> (Option<String>, Option<TextRange>) {
match name {
Some(n) => (Some(n.text), Some(n.span)),
None => (None, None),
}
}
impl<'a> Parser<'a> {
fn new(tokens: Vec<Token>, source: &'a str, tolerant: bool) -> Self {
Parser {
tokens,
pos: 0,
pending_leading: Vec::new(),
pending_trailing: Vec::new(),
depth: 0,
links: 0,
open_conds: 0,
tolerant,
source,
diagnostics: Vec::new(),
}
}
fn cur(&self) -> &Token {
&self.tokens[self.pos]
}
fn nth(&self, n: usize) -> &Token {
let i = (self.pos + n).min(self.tokens.len() - 1);
&self.tokens[i]
}
fn at_eof(&self) -> bool {
self.cur().kind == TokenKind::Eof
}
fn bump(&mut self) -> Token {
let mut t = self.tokens[self.pos].clone();
if self.pos + 1 < self.tokens.len() {
self.pos += 1;
}
if !t.leading.is_empty() {
self.pending_leading.append(&mut t.leading);
}
if let Some(tr) = t.trailing.take() {
self.pending_trailing.push(tr);
}
t
}
/// Open one level of nesting, refusing to recurse past
/// [`MAX_NESTING_DEPTH`]. Callers that succeed must pair this with
/// [`Parser::leave`] on every path out, including the error paths.
fn enter(&mut self) -> PResult<()> {
if self.depth >= MAX_NESTING_DEPTH {
return self.error(format!("nesting too deep (limit {MAX_NESTING_DEPTH})"));
}
self.depth += 1;
Ok(())
}
/// Close the level opened by [`Parser::enter`].
fn leave(&mut self) {
self.depth -= 1;
}
/// Add one link to a left-nested chain, refusing past
/// [`MAX_CHAIN_LENGTH`]. Links are released by restoring the count a
/// chain started from (see the `parse_binary` / `parse_postfix`
/// wrappers), so a chain built inside another chain's operand stacks on
/// top of it instead of resetting it.
fn link(&mut self) -> PResult<()> {
if self.links >= MAX_CHAIN_LENGTH {
return self.error(format!("expression chain too long (limit {MAX_CHAIN_LENGTH})"));
}
self.links += 1;
Ok(())
}
// ------------------------------------------------------------------
// Error recovery
//
// Only ever reached when `tolerant` is set. The strategy is deliberately
// one paragraph long: record the error, skip to a sync token, wrap the
// skipped text in an error leaf, continue with the next item/statement.
// Neither `depth` nor `links` is touched here — the gated frames released
// their own levels on the way out, so recovery resumes at exactly the
// budget the loop it happened in was running at.
// ------------------------------------------------------------------
/// True when the cursor sits on a token recovery must not consume: it
/// closes, or opens, a construct an enclosing loop is responsible for.
fn at_sync_stop(&self) -> bool {
let t = self.cur();
t.kind == TokenKind::Keyword
&& (SYNC_CLOSERS.contains(&t.text.as_str()) || SYNC_OPENERS.contains(&t.text.as_str()))
}
/// True on any of the `join` keywords that close a `fork`.
fn at_join_kw(&self) -> bool {
let t = self.cur();
t.is_kw("join") || t.is_kw("join_any") || t.is_kw("join_none")
}
/// Loop condition for a body that ends at `end_kw`. In tolerant mode any
/// sync stop ends it too, so an unclosed block stops where the next
/// construct begins instead of eating the rest of the file.
fn at_body_end(&self, end_kw: &str) -> bool {
self.at_eof() || self.cur().is_kw(end_kw) || (self.tolerant && self.at_sync_stop())
}
/// Consume a construct's closing keyword. In tolerant mode a missing one
/// is a diagnostic and the construct is treated as closed where the parser
/// stopped: mid-edit code has unclosed blocks all the time, and the items
/// already parsed inside are worth more than the whole file being one
/// error node.
fn expect_closer(&mut self, kw: &str) -> PResult<()> {
if self.cur().is_kw(kw) {
self.bump();
return Ok(());
}
if self.tolerant {
self.record(format!("expected `{kw}`"));
return Ok(());
}
self.error(format!("expected `{kw}`"))
}
/// Record a diagnostic at the cursor without failing.
fn record(&mut self, message: impl Into<String>) {
let e = self.make_error(message);
self.push_diag(e);
}
/// File `err` as a diagnostic. Called while the cursor still sits on the
/// token the error was raised at, which is where its span comes from.
fn push_diag(&mut self, err: ParseError) {
let span = self.cur().span;
self.diagnostics.push(ParseDiagnostic {
message: err.message,
line: err.line,
col: err.col,
span,
});
}
/// Skip tokens up to the next sync point: a `;` (consumed — it terminated
/// the broken construct), a sync-stop keyword (left in place for the
/// construct it belongs to), or end of file.
///
/// Brackets opened while skipping are skipped as a unit, so the `;`s of a
/// broken `for (i = 0; ...)` header do not end the skip early. A closing
/// bracket with nothing open is skipped like any other token: recovery
/// only ever runs in an item or statement list, and no such list sits
/// inside brackets, so a stray `)` is garbage rather than someone else's
/// terminator — treating it as one made every leftover `)` of a broken
/// expression its own error node.
fn skip_to_sync(&mut self) {
let mut open = 0u32;
while !self.at_eof() {
let t = self.cur();
if open == 0 {
if self.at_sync_stop() {
return;
}
if t.is_sym(";") {
self.bump();
return;
}
}
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
open += 1;
} else if open > 0 && (t.is_sym(")") || t.is_sym("]") || t.is_sym("}")) {
open -= 1;
}
self.bump();
}
}
/// Record `err` and skip to a sync point, handing back the skipped source
/// as a verbatim leaf spanning from `start` (the byte offset of the token
/// at `start_pos`, where the failed construct began).
fn recover(&mut self, start_pos: usize, start: u32, err: ParseError) -> RawText {
self.push_diag(err);
if self.pos == start_pos {
// The failed construct consumed nothing, so skipping might not
// either; take one token to guarantee the enclosing loop advances.
self.bump();
}
self.skip_to_sync();
// Comments inside the skipped range are part of the raw text below.
// Dropping the trivia copies keeps them from reattaching themselves to
// whatever node comes next.
let _ = self.take_dangling();
let span = self.span_from(start);
let col = self.tokens.get(start_pos).map(|t| t.col).unwrap_or(1);
RawText { text: self.slice(span), col, span }
}
/// The source text `span` covers.
fn slice(&self, span: TextRange) -> String {
self.source.get(span.as_range()).unwrap_or_default().to_string()
}
/// Parse one item; in tolerant mode turn a failure into an error leaf.
fn item_or_recover(&mut self) -> PResult<Item> {
let start_pos = self.pos;
let start = self.here();
match self.parse_item() {
Err(e) if self.tolerant => {
let raw = self.recover(start_pos, start, e);
let span = raw.span;
Ok(Item { meta: Meta::default(), kind: ItemKind::Error(raw), span })
}
other => other,
}
}
/// Parse one statement; in tolerant mode turn a failure into an error leaf.
fn stmt_or_recover(&mut self) -> PResult<Stmt> {
let start_pos = self.pos;
let start = self.here();
match self.parse_stmt() {
Err(e) if self.tolerant => {
let raw = self.recover(start_pos, start, e);
let span = raw.span;
Ok(Stmt { meta: Meta::default(), kind: StmtKind::Error(raw), span })
}
other => other,
}
}
// ------------------------------------------------------------------
// Spans
//
// A node's span runs from the first token of the construct to the last
// one consumed for it. Comments are not in the token stream the parser
// walks — the lexer hung them off tokens as trivia — so they fall out of
// node spans for free, which is the convention documented in
// `docs/features/spans/README.md`.
// ------------------------------------------------------------------
/// Byte offset where the token at the cursor starts: the `start` of the
/// span of whatever construct is about to be parsed.
fn here(&self) -> u32 {
self.cur().span.start
}
/// Byte offset just past the last token consumed.
fn last_end(&self) -> u32 {
match self.pos.checked_sub(1) {
Some(i) => self.tokens[i].span.end,
None => 0,
}
}
/// Span from `start` through the last token consumed. A construct that
/// consumed nothing gets the empty span at `start`.
fn span_from(&self, start: u32) -> TextRange {
TextRange::new(start, self.last_end())
}
/// An expression node spanning from `start` through the last token
/// consumed.
fn expr_at(&self, start: u32, kind: ExprKind) -> Expr {
Expr { kind, span: self.span_from(start) }
}
fn error<T>(&self, message: impl Into<String>) -> PResult<T> {
Err(self.make_error(message))
}
/// The error the parser would report at the cursor right now.
fn make_error(&self, message: impl Into<String>) -> ParseError {
let t = self.cur();
let shown = if t.kind == TokenKind::Eof { "<eof>" } else { t.text.as_str() };
ParseError {
line: t.line,
col: t.col,
message: format!("{} (found {:?})", message.into(), shown),
}
}
fn expect_sym(&mut self, sym: &str) -> PResult<Token> {
if self.cur().is_sym(sym) {
Ok(self.bump())
} else {
self.error(format!("expected `{sym}`"))
}
}
fn expect_kw(&mut self, kw: &str) -> PResult<Token> {
if self.cur().is_kw(kw) {
Ok(self.bump())
} else {
self.error(format!("expected `{kw}`"))
}
}
fn expect_ident(&mut self) -> PResult<String> {
Ok(self.expect_name()?.text)
}
/// The identifier at the cursor, with the byte range it occupies. The
/// parser sits on the token that spells the name, so this is where a
/// declared name's `name_span` comes from.
fn expect_name(&mut self) -> PResult<Name> {
if self.cur().kind == TokenKind::Ident {
let span = self.cur().span;
Ok(Name { text: self.bump().text, span })
} else {
self.error("expected identifier")
}
}
fn eat_sym(&mut self, sym: &str) -> bool {
if self.cur().is_sym(sym) {
self.bump();
true
} else {
false
}
}
fn eat_kw(&mut self, kw: &str) -> bool {
if self.cur().is_kw(kw) {
self.bump();
true
} else {
false
}
}
/// Start a new node: gather pending + current-token leading comments.
fn take_meta(&mut self) -> Meta {
let mut leading: Vec<Comment> = Vec::new();
// Unharvested trailing comments from earlier tokens become leading
// comments here so they are never lost.
leading.append(&mut self.pending_trailing);
leading.append(&mut self.pending_leading);
let tok = &mut self.tokens[self.pos];
leading.append(&mut tok.leading);
let blank_before =
leading.first().map(|c| c.blank_before).unwrap_or(self.tokens[self.pos].blank_before);
Meta { leading, blank_before, ..Meta::default() }
}
/// Harvest trailing comments accumulated since the last harvest.
///
/// Several comments merge into one, joined by a space, as they always
/// have; the result keeps the first one's line/column (what the formatter
/// re-indents a multi-line one by) and spans the whole run.
fn take_trailing(&mut self) -> Option<Comment> {
let mut drained = self.pending_trailing.drain(..);
let mut first = drained.next()?;
for rest in drained {
first.text.push(' ');
first.text.push_str(&rest.text);
first.span.end = rest.span.end;
}
Some(first)
}
/// Move the comments written before the separator at the cursor onto the
/// element just parsed, so they print on the element's side of it.
///
/// A no-op when the cursor is not on that separator: the comments then
/// belong to the enclosing list's dangling bucket (before its closing
/// bracket) or to the next construct, and stealing them here would move
/// them backwards across a token.
fn take_before_sep(&mut self, meta: &mut Meta, sep: &str) {
if !self.cur().is_sym(sep) {
return;
}
self.take_before(meta);
}
/// The unconditional half of [`Parser::take_before_sep`], for callers that
/// recognize their own separator: an event list separates with a `,` or
/// with the `or` keyword, and both spellings occur in one list.
fn take_before(&mut self, meta: &mut Meta) {
if let Some(c) = meta.trailing.take() {
meta.before_sep.push(c);
}
let mut around = self.take_dangling();
meta.before_sep.append(&mut around);
}
/// Comments written just before an opening bracket the caller is about to
/// consume (`module m` ⏎ `// why` ⏎ `#(`).
///
/// A no-op unless the cursor is on that bracket, for the same reason
/// [`Parser::take_before_sep`] is: a construct that wrote no such bracket
/// must leave the comments for whoever comes next, and stealing them here
/// would move them backwards across a token.
///
/// Only the comments written in the **gap that ends at this bracket** are
/// taken — see [`Parser::take_gap`].
fn take_before_open(&mut self, open: &str) -> Vec<Comment> {
if !self.cur().is_sym(open) {
return Vec::new();
}
self.take_gap()
}
/// The comments written in the gap that ends at the cursor: those starting
/// at or after the end of the last token consumed.
///
/// The narrow sibling of [`Parser::take_dangling`], for the sites that own
/// *one* gap rather than everything still queued. A comment queued from
/// further back was written somewhere else and belongs to whoever owns
/// that place — `if (` ⏎ `// why` ⏎ `!f()` queues the comment on the `(`
/// of the **condition**, and neither `f`'s own `(` nor the inside of its
/// empty `()` may print it. Nothing is dropped: what is left queued is
/// harvested by the next node that takes meta.
fn take_gap(&mut self) -> Vec<Comment> {
let gap = self.last_end();
let mut out = Vec::new();
take_since(&mut self.pending_trailing, gap, &mut out);
take_since(&mut self.pending_leading, gap, &mut out);
take_since(&mut self.tokens[self.pos].leading, gap, &mut out);
out
}
/// Consume the compiler directives — and the standalone macro invocations
/// [`Parser::at_macro_item`] recognizes — standing where a list element
/// would start, recording each one's place in the list and the `,` (if
/// any) written after it.
///
/// `before` is the number of elements parsed so far, which is the index
/// of the element the directives precede.
///
/// A directive runs to end of line, so it can only ever stand *between*
/// elements; one written inside an element is left where it is and
/// becomes an ordinary parse error, as it always was.
fn take_list_directives(&mut self, out: &mut Vec<ListDirective>, before: usize) -> Harvested {
let mut found = Harvested::default();
while self.cur().kind == TokenKind::Directive || self.at_macro_item() {
if self.at_outer_arm_split(out) {
break;
}
let mut meta = self.take_meta();
let raw = self.take_raw_text();
meta.trailing = self.take_trailing();
let comma = self.eat_sym(",");
found.any = true;
found.carried_comma |= comma;
out.push(ListDirective { raw, meta, before, comma });
}
found
}
/// True when the directive at the cursor continues or closes a conditional
/// region **this list did not open**, while a region opened at item scope
/// is still live.
///
/// Such a directive is not conditioning list *elements* — it is the seam
/// where the whole item splits into rival spellings that share one list:
///
/// ```verilog
/// `ifdef DISABLE_ROM_INTEGRITY_CHECK
/// chip_earlgrey_asic #(.SecRomCtrlDisableScrambling(1'b1)) dut (
/// `else
/// chip_earlgrey_asic dut (
/// `endif
/// .POR_N(...), ...
/// );
/// ```
///
/// Harvesting the `` `else `` here would leave the parser reading the next
/// arm's *head* (`chip_earlgrey_asic dut`) as connection elements, and it
/// fails two tokens later with a diagnostic three lines from the defect.
/// Refusing it lets the item fail on the directive itself, where
/// [`Parser::at_split_conditional`] recognizes the shape and captures the
/// whole instantiation verbatim — the treatment the arms of a split region
/// have had since `docs/features/directive-split/README.md`.
///
/// `taken` is what this list has harvested so far, which is the only
/// scope that can have opened a region the directive legitimately ends.
fn at_outer_arm_split(&self, taken: &[ListDirective]) -> bool {
let t = self.cur();
if !continues_conditional(t) && !closes_conditional(t) {
return false;
}
// The same "a region is live" guard the split recovery makes: with
// nothing open at item scope there is no outer arm to belong to, and
// the directive is ordinary conditional text inside the list.
if self.open_conds == 0 {
return false;
}
let mut open = 0i32;
for d in taken {
match directive_word_of(&d.raw.text) {
"ifdef" | "ifndef" => open += 1,
"endif" => open -= 1,
_ => {}
}
}
open <= 0
}
/// Comments sitting right before a closing keyword (`end`, `endmodule`,
/// ...) — they belong inside the enclosing construct.
fn take_dangling(&mut self) -> Vec<Comment> {
let mut out: Vec<Comment> = std::mem::take(&mut self.pending_trailing);
out.append(&mut self.pending_leading);
let tok = &mut self.tokens[self.pos];
out.append(&mut tok.leading);
out
}
/// One element of a bracketed expression list, with the comments written
/// before it. The caller harvests the trailing comment after the comma.
fn parse_expr_item(&mut self) -> PResult<ExprItem> {
let start = self.here();
let meta = self.take_meta();
// Two element-only shapes no expression can start with: a named call
// argument (`.value(x)`, `.name()`) and a `[lo:hi]` value range (a
// `case ... inside` label). Both are recognized here, in the shared
// element parse, because rejecting them in the lists that cannot
// legally hold them would gain nothing — lucisv checks legality
// nowhere else either, and a wrong guess emits the same tokens.
let expr = if self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident {
self.parse_named_arg()?
} else if self.cur().is_sym("[") {
self.parse_value_range()?
} else if self.at_omitted_element() {
// An omitted positional argument: `create("asm_gen", , `gfn)`
// (`riscv_instr_base_test.sv:88`) takes the parameter's default
// (IEEE 1800 §13.5.3). It is an element with no tokens at all,
// recognized here for the reason the two shapes above are.
self.expr_at(start, ExprKind::Empty(Vec::new()))
} else {
self.parse_expr()?
};
Ok(ExprItem { meta, expr, span: self.span_from(start) })
}
/// True when the cursor stands where a list element belongs but the
/// source wrote none: the next token already closes the element.
fn at_omitted_element(&self) -> bool {
let t = self.cur();
t.is_sym(",") || t.is_sym(")")
}
/// `.name(expr)` / `.name()` — a named call argument. The cursor is on
/// the `.` and the next token is an identifier.
fn parse_named_arg(&mut self) -> PResult<Expr> {
let start = self.here();
self.bump(); // .
let Name { text: name, span: name_span } = self.expect_name()?;
let mark = self.pending_trailing.len();
let paren_start = self.here();
self.expect_sym("(")?;
let (value, close_comments) = if self.cur().is_sym(")") {
// `.name()` — explicitly empty, keeping any comments written
// between the parens, exactly as an empty connection does. The
// span covers the `( )` pair.
let comments = self.take_around(mark);
self.bump();
(self.expr_at(paren_start, ExprKind::Empty(comments)), Vec::new())
} else {
let value = self.parse_expr()?;
// A comment before the closing `)` (`.src(5'd0 /* x0 */)`)
// stays inside the parens, as a connection's does.
let close = self.take_around(mark);
self.expect_sym(")")?;
(value, close)
};
Ok(self.expr_at(
start,
ExprKind::NamedArg { name, name_span, value: Box::new(value), close_comments },
))
}
/// `[lo:hi]` — a value range standing as a list element (a
/// `case ... inside` label). The cursor is on the `[`.
fn parse_value_range(&mut self) -> PResult<Expr> {
let start = self.here();
self.bump(); // [
let lo = self.parse_expr()?;
self.expect_sym(":")?;
let hi = self.parse_expr()?;
self.expect_sym("]")?;
Ok(self.expr_at(start, ExprKind::ValueRange { lo: Box::new(lo), hi: Box::new(hi) }))
}
/// Continue a comma-separated expression list whose first element is
/// already parsed, harvesting the comment written after each comma and
/// the ones before `close` — the token that ends the list, which the
/// caller consumes (`}`, `)`, or the `:` of a case label list).
fn parse_expr_list(&mut self, first: ExprItem, close: &str) -> PResult<Vec<ExprItem>> {
let mut items = vec![first];
loop {
if let Some(last) = items.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let more = self.eat_sym(",");
if let Some(last) = items.last_mut() {
if last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
if !more {
if let Some(last) = items.last_mut() {
self.take_before_sep(&mut last.meta, close);
}
return Ok(items);
}
items.push(self.parse_expr_item()?);
}
}
/// Consume the current token as verbatim text, keeping the column it
/// started in.
fn take_raw_text(&mut self) -> RawText {
let col = self.cur().col;
let span = self.cur().span;
RawText { text: self.bump().text, col, span }
}
/// True when the macro usage at the cursor stands on its own as an item or
/// a statement rather than opening a declaration, an instantiation or an
/// expression.
///
/// The lexer hands us the whole invocation as one token, so this is a
/// one-token lookahead:
///
/// * next token is `;` — always a standalone invocation;
/// * next token is on a **later line** than the one the invocation ends
/// on — a macro that ends its line is a finished macro item, and
/// whatever opens the next line opens a new construct
/// (`` `uvm_info(`gfn, "...", UVM_MEDIUM) `` ⏎
/// `@(posedge cfg.clk_rst_vif.rst_n);`, corpus
/// `ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv:160`);
/// * next token is any other symbol on the same line — an expression or
/// declaration continues (`` `MACRO(x) = y; ``, `` `MOD #(...) u(); ``,
/// `` `TYPE [3:0] x; ``);
/// * next token is a plain identifier on the same line — `` `TYPE x; `` /
/// `` `MOD u (...); ``, *unless* this invocation has an argument list,
/// which no type or module name in real RTL does, or the identifier is
/// itself followed by a `#(` — `` `uvm_component_new `` ⏎
/// `` uvm_analysis_port #(bit [31:0]) p; `` is a standalone macro and a
/// parameterized-type declaration, never one construct;
/// * anything else (a keyword, another macro, a directive, end of file) —
/// the invocation stands alone.
///
/// Guessing wrong cannot corrupt code: either reading emits the same
/// tokens in the same order, so the equivalence check still passes and
/// only the line breaks differ.
fn at_macro_item(&self) -> bool {
if !self.cur().is_macro() {
return false;
}
let next = self.nth(1);
if next.is_sym(";") {
return true;
}
// A line break between the invocation and the next token ends the
// macro, whatever kind that token is: `` `uvm_component_new `` ⏎ ⏎
// `uvm_report_server rs;` (corpus
// `ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv:19`) and
// `` `uvm_info(...) `` ⏎ `@(posedge clk);` are the same shape. A type
// and its declarator are written together (`` `MY_TYPE_T sig; ``), and
// so are a macro and the `[3:0]` / `= y` that continues it, so this
// never steals one.
if next.line != self.macro_end_line() {
return true;
}
match next.kind {
TokenKind::Symbol => false,
TokenKind::Ident if !next.is_macro() => {
self.cur().has_macro_args()
|| (self.nth(2).is_sym("#") && self.nth(3).is_sym("("))
// `` `WAIT_FOR_RESET `` ⏎ `cov.cg.sample(...);` — a
// declarator name is never followed by `.`, so the macro
// stands alone and the identifier opens a statement.
|| self.nth(2).is_sym(".")
}
_ => true,
}
}
/// The source line the macro invocation at the cursor *ends* on. The lexer
/// hands a whole invocation over as one token, so a call whose argument
/// list spans lines (`` `uvm_info(a, `` ⏎ `` b) ``) starts well before it
/// ends, and only the end line answers "did this macro end its line?".
fn macro_end_line(&self) -> u32 {
let cur = self.cur();
cur.line + cur.text.bytes().filter(|b| *b == b'\n').count() as u32
}
/// True when the cursor is a bare macro name whose argument list the lexer
/// did *not* attach because a space stands between them:
/// `` `uvm_field_int (fetch_addr, UVM_DEFAULT) `` (corpus
/// `ibex/dv/uvm/core_ibex/common/ibex_cosim_agent/ibex_ifetch_pmp_seq_item.sv:10`).
///
/// Deliberately *not* folded into [`Parser::at_macro_item`]: this reading
/// is only offered where an item or a statement belongs, never in an
/// expression or a port/parameter list. In an expression `` `A (b) `` may
/// well be `` `A `` applied to the parenthesized value `(b)` — the answer
/// depends on whether the macro was defined with formals, which lives in
/// a file lucisv does not read (IEEE 1800 §22.5.1, and the analysis in
/// `docs/features/lexer-cleanup/README.md`). At item position there is no
/// such ambiguity: neither reading is an item on its own.
///
/// The `(` must be on the macro's own line. A `(` opening the next line is
/// the far more likely start of a separate construct.
fn at_spaced_macro_call(&self) -> bool {
let cur = self.cur();
cur.is_macro()
&& !cur.has_macro_args()
&& self.nth(1).is_sym("(")
&& self.nth(1).line == cur.line
}
/// Consume a standalone macro invocation and its optional trailing `;`.
fn parse_macro_call(&mut self) -> PResult<MacroCall> {
let raw = if self.at_spaced_macro_call() {
let start = self.here();
let col = self.cur().col;
self.bump(); // `NAME
self.bump(); // (
self.skip_balanced("(", ")")?;
// Verbatim, space included: the argument text is preprocessor
// input lucisv does not model, and closing the gap would make the
// output's token text differ from the input's (`` `A (b) `` and
// `` `A(b) `` are one token each, of different text) — which the
// safety net rightly refuses.
self.verbatim_since(start, col)
} else {
self.take_raw_text()
};
let semi = self.eat_sym(";");
Ok(MacroCall { raw, semi })
}
/// Take the comments the lexer attached *before* the current token,
/// bypassing the usual pending-comment plumbing so a construct can keep
/// them itself. Must be called before the token is consumed.
fn take_leading_here(&mut self) -> Vec<Comment> {
std::mem::take(&mut self.tokens[self.pos].leading)
}
/// Every comment written in the gap that ends at the cursor: the ones
/// trailing the tokens consumed since `mark`, then the ones sitting on
/// their own lines before the current token. Used where a construct must
/// keep a comment on a specific side of an operator it is about to
/// consume.
///
/// `mark` is clamped: a nested construct may have harvested the pending
/// comments already, leaving fewer than there were when `mark` was taken.
fn take_around(&mut self, mark: usize) -> Vec<Comment> {
let at = mark.min(self.pending_trailing.len());
let mut out = self.pending_trailing.split_off(at);
out.append(&mut self.take_leading_here());
out
}
/// Same for the comment written *after* the current token on its line.
fn take_trailing_here(&mut self) -> Vec<Comment> {
match self.tokens[self.pos].trailing.take() {
Some(comment) => vec![comment],
None => Vec::new(),
}
}
/// The `: name` written after a `begin`/`fork`, or after a closing
/// keyword (`end`, `join`, `endfunction`, ...), if present. Kept on the
/// node so the formatter can print it back.
fn parse_label(&mut self) -> PResult<Option<Name>> {
if self.eat_sym(":") {
Ok(Some(self.expect_name()?))
} else {
Ok(None)
}
}
/// The first token past the run of [`MEMBER_QUALIFIERS`] at the cursor —
/// the one that says what is being declared. Consumes nothing.
fn member_head(&self) -> &Token {
let mut i = self.pos;
while self.tokens[i].kind == TokenKind::Keyword
&& MEMBER_QUALIFIERS.contains(&self.tokens[i].text.as_str())
&& i + 1 < self.tokens.len()
{
i += 1;
}
&self.tokens[i]
}
/// Consume the run of [`MEMBER_QUALIFIERS`] at the cursor, in source order.
fn take_member_prefix(&mut self) -> Vec<String> {
let mut out = Vec::new();
while self.cur().kind == TokenKind::Keyword
&& MEMBER_QUALIFIERS.contains(&self.cur().text.as_str())
{
out.push(self.bump().text);
}
out
}
/// A method name, with the `my_class::` scope of an out-of-body
/// definition split off so the returned [`Name`] is only the method's own.
fn parse_method_name(&mut self) -> PResult<(Option<String>, Name)> {
let mut name = self.expect_name()?;
let mut scope: Option<String> = None;
while self.cur().is_sym("::") {
self.bump();
let next = self.expect_name()?;
match &mut scope {
Some(s) => {
s.push_str("::");
s.push_str(&name.text);
}
None => scope = Some(name.text),
}
name = next;
}
Ok((scope, name))
}
/// A `pkg::name` chain, returned as the joined text plus the
/// range covering the whole chain.
fn parse_scoped_name(&mut self) -> PResult<(String, TextRange)> {
let start = self.here();
let mut name = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
name.push_str("::");
name.push_str(&self.expect_ident()?);
}
Ok((name, self.span_from(start)))
}
/// Given `self.tokens[i]` == an opening bracket, return the index just
/// past its matching close. Used for disambiguating lookahead only.
fn scan_matching(&self, mut i: usize, open: &str, close: &str) -> usize {
let mut depth = 0usize;
while i < self.tokens.len() {
let t = &self.tokens[i];
if t.kind == TokenKind::Eof {
return i;
}
if t.is_sym(open) {
depth += 1;
} else if t.is_sym(close) {
depth -= 1;
if depth == 0 {
return i + 1;
}
}
i += 1;
}
i
}
/// Does the identifier at the cursor open a declaration whose type is a
/// user-defined name? True when a declarator identifier still follows it
/// past the optional `pkg::` chain, `#( ... )` overrides and packed
/// dimensions: `my_t x`, `pkg::my_t x`, `item #(A, B) req`,
/// `payload_t [NumOut-1:0][NumInp-1:0] out_data` (stream_xbar.sv:98).
///
/// This is what keeps `x[i] = 1;` an assignment: what follows the
/// brackets there is `=`, not a name.
fn at_typed_declarator(&self) -> bool {
let mut p = self.pos;
while self.tokens.get(p + 1).is_some_and(|t| t.is_sym("::")) {
p += 2;
}
let mut next = p + 1;
// A parameterized type puts `#( ... )` between the name and the
// declarator (`uvm_analysis_port #(bit [31:0]) port;`).
if self.tokens.get(next).is_some_and(|t| t.is_sym("#"))
&& self.tokens.get(next + 1).is_some_and(|t| t.is_sym("("))
{
next = self.scan_matching(next + 1, "(", ")");
}
while self.tokens.get(next).is_some_and(|t| t.is_sym("[")) {
next = self.scan_matching(next, "[", "]");
}
self.tokens.get(next).is_some_and(|t| t.kind == TokenKind::Ident)
}
// ------------------------------------------------------------------
// Top level
// ------------------------------------------------------------------
fn parse_source_file(&mut self) -> PResult<SourceFile> {
let mut items = Vec::new();
while !self.at_eof() {
items.push(self.item_or_recover()?);
}
let dangling = self.take_dangling();
// The cursor is on the EOF token, whose empty span sits at the end of
// the source, so this covers the whole file.
let span = TextRange::new(0, self.cur().span.end);
Ok(SourceFile { items, dangling, span })
}
/// Items nest through generate blocks and package bodies. Gated.
fn parse_item(&mut self) -> PResult<Item> {
self.enter()?;
let out = self.parse_item_inner();
self.leave();
out
}
fn parse_item_inner(&mut self) -> PResult<Item> {
// Before the attribute loop: `(* keep *)` is code, not trivia, so it
// belongs inside the item's span.
let start = self.here();
let mut meta = self.take_meta();
while self.cur().kind == TokenKind::Attribute {
meta.attrs.push(self.take_raw_text());
let tok = &mut self.tokens[self.pos];
meta.leading.append(&mut tok.leading);
}
let mark =
ItemMark { pos: self.pos, conds: self.open_conds, diags: self.diagnostics.len() };
let kind = match self.parse_item_kind() {
Ok(kind) => kind,
Err(e) => self.split_conditional_item(&mark, e)?,
};
let span = self.span_from(start);
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(Item { meta, kind, span })
}
fn parse_item_kind(&mut self) -> PResult<ItemKind> {
if self.at_macro_item() || self.at_spaced_macro_call() {
return Ok(ItemKind::MacroItem(self.parse_macro_call()?));
}
let t = self.cur();
match t.kind {
TokenKind::Directive => {
self.note_item_conditional();
Ok(ItemKind::Directive(self.take_raw_text()))
}
TokenKind::Keyword => self.parse_keyword_item(),
TokenKind::Ident if self.at_bind_directive() => self.parse_bind().map(ItemKind::Bind),
// `NoNMI: assume property (...)` and `restrict property (...)`:
// a label, or the non-keyword `restrict`, in front of a
// concurrent assertion.
TokenKind::Ident if self.at_concurrent_assertion() => {
self.parse_concurrent_assertion().map(ItemKind::Verbatim)
}
TokenKind::Ident => self.parse_ident_item(),
TokenKind::SystemIdent if ELAB_TASKS.contains(&t.text.as_str()) => {
let call = self.parse_expr()?;
self.expect_sym(";")?;
Ok(ItemKind::ElabTask(call))
}
_ => self.error("expected item"),
}
}
fn parse_keyword_item(&mut self) -> PResult<ItemKind> {
let kw = self.cur().text.clone();
match kw.as_str() {
"module" | "macromodule" => self.parse_module("endmodule").map(ItemKind::Module),
// `interface class` is a class, not an interface (IEEE 1800
// §8.26): a different construct that lucisv does not model, so it
// falls through to the unsupported-construct error below.
"interface" if !self.nth(1).is_kw("class") => {
self.parse_module("endinterface").map(ItemKind::Module)
}
"modport" => self.parse_modport().map(ItemKind::Modport),
"clocking" => self.parse_clocking(false).map(ItemKind::Clocking),
"default" if self.nth(1).is_kw("clocking") => {
self.bump();
self.parse_clocking(true).map(ItemKind::Clocking)
}
"package" => self.parse_package(),
"import" => {
// A string right after `import` is a DPI linkage spec, not a
// package name: `import "DPI-C" function void f();`.
if self.nth(1).kind == TokenKind::String {
return self.parse_dpi_import();
}
let paths = self.parse_import_list()?;
Ok(ItemKind::Import(paths))
}
"export" => self.parse_export().map(ItemKind::Export),
"timeunit" | "timeprecision" => {
let mut parts: Vec<String> = Vec::new();
while !self.cur().is_sym(";") && !self.at_eof() {
parts.push(self.bump().text);
}
self.expect_sym(";")?;
Ok(ItemKind::Timeunit(parts.join(" ")))
}
"typedef" => self.parse_typedef().map(ItemKind::Typedef),
"parameter" | "localparam" => {
let d = self.parse_param_decl()?;
self.expect_sym(";")?;
Ok(ItemKind::ParamDecl(d))
}
"input" | "output" | "inout" => {
let d = self.parse_port_decl()?;
Ok(ItemKind::PortDecl(d))
}
"genvar" => {
self.bump();
let mut names = vec![self.expect_name()?];
while self.eat_sym(",") {
names.push(self.expect_name()?);
}
self.expect_sym(";")?;
Ok(ItemKind::Genvar(names))
}
"assign" => self.parse_cont_assign().map(ItemKind::ContAssign),
"always" | "always_comb" | "always_ff" | "always_latch" => {
let kw = self.bump().text;
let stmt = self.parse_stmt()?;
Ok(ItemKind::Always { kw, stmt })
}
"initial" => {
self.bump();
Ok(ItemKind::Initial(self.parse_stmt()?))
}
"final" => {
self.bump();
Ok(ItemKind::Final(self.parse_stmt()?))
}
"generate" => {
self.bump();
let mut items = Vec::new();
while !self.at_body_end("endgenerate") {
items.push(self.item_or_recover()?);
}
let dangling = self.take_dangling();
self.expect_closer("endgenerate")?;
Ok(ItemKind::GenerateRegion { items, dangling })
}
"if" => self.parse_gen_if().map(ItemKind::GenIf),
"for" => self.parse_gen_for().map(ItemKind::GenFor),
"case" => self.parse_gen_case().map(ItemKind::GenCase),
"function" => self.parse_function().map(ItemKind::Function),
"task" => self.parse_task().map(ItemKind::Task),
"class" => self.parse_class().map(ItemKind::Class),
"let" => self.parse_let().map(ItemKind::Let),
"constraint" => self.parse_constraint().map(ItemKind::Verbatim),
"covergroup" => self.parse_covergroup().map(ItemKind::Verbatim),
"assert" | "assume" | "cover" if self.at_concurrent_assertion() => {
self.parse_concurrent_assertion().map(ItemKind::Verbatim)
}
"property" | "sequence" => self.parse_property_decl().map(ItemKind::Verbatim),
// A run of member qualifiers (`virtual`, `local rand`, `static`,
// `pure virtual`, ...) does not say what it qualifies; the first
// keyword past the run does. Nothing is consumed here, so each
// branch parses its own construct from the first qualifier on.
_ if MEMBER_QUALIFIERS.contains(&kw.as_str()) => {
match self.member_head().text.as_str() {
"class" => self.parse_class().map(ItemKind::Class),
"function" => self.parse_function().map(ItemKind::Function),
"task" => self.parse_task().map(ItemKind::Task),
"constraint" => self.parse_constraint().map(ItemKind::Verbatim),
"covergroup" => self.parse_covergroup().map(ItemKind::Verbatim),
_ => self.parse_data_decl().map(ItemKind::DataDecl),
}
}
"defparam" => {
self.bump();
let mut pairs = Vec::new();
loop {
let lhs = self.parse_expr()?;
self.expect_sym("=")?;
let rhs = self.parse_expr()?;
pairs.push((lhs, rhs));
if !self.eat_sym(",") {
break;
}
}
self.expect_sym(";")?;
Ok(ItemKind::Defparam(pairs))
}
_ if GATE_KEYWORDS.contains(&kw.as_str()) => {
self.parse_gate_instantiation().map(ItemKind::GateInstantiation)
}
// `enum`/`struct`/`union` here is an anonymous aggregate type
// introducing a variable (`enum logic [1:0] {A, B} state;`) — the
// `typedef` spelling is taken by the arm above.
_ if NET_KEYWORDS.contains(&kw.as_str())
|| TYPE_KEYWORDS.contains(&kw.as_str())
|| matches!(kw.as_str(), "signed" | "unsigned" | "enum" | "struct" | "union") =>
{
let d = self.parse_data_decl()?;
Ok(ItemKind::DataDecl(d))
}
_ => self.error(format!("unsupported construct starting with keyword `{kw}`")),
}
}
/// Item starting with an identifier: either a module instantiation or a
/// declaration with a user-defined type.
fn parse_ident_item(&mut self) -> PResult<ItemKind> {
// Skip over a package scope chain for lookahead purposes.
let mut p = self.pos;
while self.tokens.get(p + 1).is_some_and(|t| t.is_sym("::")) {
p += 2;
}
let t1 = self.nth(p + 1 - self.pos);
if t1.is_sym("#") {
// `sub #(.W(8)) u (...);` and `port_t #(int) p;` open the same
// way. What follows the name after the overrides tells them
// apart: an instance has a connection list or an array range,
// a declaration goes straight to `;`, `,` or `=`.
if self.tokens.get(p + 2).is_some_and(|t| t.is_sym("(")) {
let name = self.scan_matching(p + 2, "(", ")");
let after = self.tokens.get(name + 1);
// `[` after the declarator is an instance array range only
// when a connection list follows it; `item #(A, B) q[$];`
// is a declaration whose declarator has an unpacked dim.
let is_instance = after.is_some_and(|t| t.is_sym("("))
|| (after.is_some_and(|t| t.is_sym("[")) && {
let end = self.scan_matching(name + 1, "[", "]");
self.tokens.get(end).is_some_and(|t| t.is_sym("("))
});
if self.tokens.get(name).is_some_and(|t| t.kind == TokenKind::Ident) && !is_instance
{
return self.parse_data_decl().map(ItemKind::DataDecl);
}
}
return self.parse_instantiation().map(ItemKind::Instantiation);
}
if t1.kind == TokenKind::Ident {
let t2 = self.nth(p + 2 - self.pos);
if t2.is_sym("(") {
return self.parse_instantiation().map(ItemKind::Instantiation);
}
if t2.is_sym("[") {
let after = self.scan_matching(p + 2, "[", "]");
if self.tokens.get(after).is_some_and(|t| t.is_sym("(")) {
return self.parse_instantiation().map(ItemKind::Instantiation);
}
}
return self.parse_data_decl().map(ItemKind::DataDecl);
}
if t1.is_sym("[") {
return self.parse_data_decl().map(ItemKind::DataDecl);
}
self.error("expected declaration or instantiation")
}
fn parse_package(&mut self) -> PResult<ItemKind> {
let kw = self.bump().text;
let Name { text: name, span: name_span } = self.expect_name()?;
self.expect_sym(";")?;
let mut items = Vec::new();
while !self.at_body_end("endpackage") {
items.push(self.item_or_recover()?);
}
let dangling = self.take_dangling();
self.expect_closer("endpackage")?;
let (end_label, end_label_span) = split_label(self.parse_label()?);
Ok(ItemKind::Package { kw, name, name_span, items, dangling, end_label, end_label_span })
}
fn parse_import_list(&mut self) -> PResult<Vec<ImportPath>> {
self.expect_kw("import")?;
let paths = self.parse_package_paths(false)?;
self.expect_sym(";")?;
Ok(paths)
}
/// The comma-separated `pkg::item` / `pkg::*` list of an `import` or an
/// `export`, without the leading keyword or the closing `;`.
/// `allow_star_pkg` admits `export *::*;`, whose left half is a wildcard
/// too — no `import` spells that.
fn parse_package_paths(&mut self, allow_star_pkg: bool) -> PResult<Vec<ImportPath>> {
let mut paths = Vec::new();
loop {
let star = self.cur().span;
let pkg = if allow_star_pkg && self.cur().is_sym("*") {
self.bump();
Name { text: "*".to_string(), span: star }
} else {
self.expect_name()?
};
self.expect_sym("::")?;
let star = self.cur().span;
let item = if self.eat_sym("*") {
Name { text: "*".to_string(), span: star }
} else {
self.expect_name()?
};
paths.push(ImportPath { pkg, item });
if !self.eat_sym(",") {
break;
}
}
Ok(paths)
}
// ------------------------------------------------------------------
// DPI (IEEE 1800 §35.5) and package export (§26.6)
// ------------------------------------------------------------------
/// `import "DPI-C" [context|pure] [c_name =] function|task <prototype>;`.
/// The declaration is a function/task prototype with a linkage prefix, so
/// it becomes an ordinary [`FunctionDecl`] / [`TaskDecl`] carrying that
/// prefix — every consumer that already knows about functions sees one.
fn parse_dpi_import(&mut self) -> PResult<ItemKind> {
self.expect_kw("import")?;
let spec = self.expect_dpi_spec()?;
// `context` is not a reserved word, so it is only the property when an
// `=` does not turn it into the linkage name instead.
let property = if self.cur().is_kw("pure")
|| (self.cur().kind == TokenKind::Ident
&& self.cur().text == "context"
&& !self.nth(1).is_sym("="))
{
Some(self.bump().text)
} else {
None
};
let c_identifier = self.parse_dpi_c_identifier();
let dpi = DpiImport { spec, property, c_identifier };
if self.cur().is_kw("task") {
self.parse_task_decl(Some(dpi)).map(ItemKind::Task)
} else {
self.parse_function_decl(Some(dpi)).map(ItemKind::Function)
}
}
/// `export "DPI-C" [c_name =] function|task name;` or a package re-export
/// `export pkg::item, pkg::*;`.
fn parse_export(&mut self) -> PResult<ExportDecl> {
self.expect_kw("export")?;
if self.cur().kind == TokenKind::String {
let spec = self.expect_dpi_spec()?;
let c_identifier = self.parse_dpi_c_identifier();
if !self.cur().is_kw("function") && !self.cur().is_kw("task") {
return self.error("expected `function` or `task` in a DPI export");
}
let kw = self.bump().text;
let name = self.expect_name()?;
self.expect_sym(";")?;
return Ok(ExportDecl::Dpi(DpiExport { spec, c_identifier, kw, name }));
}
let paths = self.parse_package_paths(true)?;
self.expect_sym(";")?;
Ok(ExportDecl::Package(paths))
}
fn expect_dpi_spec(&mut self) -> PResult<String> {
if self.cur().kind == TokenKind::String {
Ok(self.bump().text)
} else {
self.error("expected a DPI linkage spec string")
}
}
/// The optional `c_name =` that gives the linkage symbol a name of its own.
fn parse_dpi_c_identifier(&mut self) -> Option<Name> {
if self.cur().kind != TokenKind::Ident || !self.nth(1).is_sym("=") {
return None;
}
let span = self.cur().span;
let name = Name { text: self.bump().text, span };
self.bump();
Some(name)
}
// ------------------------------------------------------------------
// Classes
// ------------------------------------------------------------------
/// `[virtual] class [lifetime] name [#(params)] [extends base [#(...)]]
/// [implements a, b]; items endclass [: label]`.
///
/// The body is parsed by the ordinary item loop, so everything that
/// already works at module scope — declarations, `typedef`, `localparam`,
/// `import`, directives, macro invocations — works inside a class for
/// free, and nesting is charged against the item budget by `parse_item`.
fn parse_class(&mut self) -> PResult<ClassDecl> {
let prefix = self.take_member_prefix();
self.expect_kw("class")?;
let lifetime = if self.cur().is_kw("static") || self.cur().is_kw("automatic") {
Some(self.bump().text)
} else {
None
};
let Name { text: name, span: name_span } = self.expect_name()?;
let param_comments = self.take_before_open("#");
let params = self.parse_param_port_list()?;
let extends =
if self.cur().is_kw("extends") { Some(self.parse_class_extends()?) } else { None };
let mut implements = Vec::new();
if self.eat_kw("implements") {
loop {
let (text, span) = self.parse_scoped_name()?;
implements.push(Name { text, span });
if !self.eat_sym(",") {
break;
}
}
}
self.expect_sym(";")?;
let mut items = Vec::new();
while !self.at_body_end("endclass") {
items.push(self.item_or_recover()?);
}
let dangling = self.take_dangling();
self.expect_closer("endclass")?;
let (end_label, end_label_span) = split_label(self.parse_label()?);
Ok(ClassDecl {
prefix,
lifetime,
name,
name_span,
param_comments,
param_ports: params.ports,
param_directives: params.directives,
param_dangling: params.dangling,
extends,
implements,
items,
dangling,
end_label,
end_label_span,
})
}
/// `extends base [#( overrides )]`. The overrides are the same
/// [`Connection`] list an instantiation's `#( ... )` uses.
fn parse_class_extends(&mut self) -> PResult<ClassExtends> {
let start = self.here();
self.expect_kw("extends")?;
let (name, name_span) = self.parse_scoped_name()?;
let param_comments = self.take_before_open("#");
let mut params = None;
let mut param_directives = Vec::new();
if self.cur().is_sym("#") {
self.bump();
self.expect_sym("(")?;
let mut list = Vec::new();
self.take_list_directives(&mut param_directives, 0);
if !self.cur().is_sym(")") {
loop {
list.push(self.parse_connection()?);
if let Some(last) = list.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = list.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(&mut param_directives, list.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
}
let n = list.len();
self.take_last_entry_before_close(
list.last_mut().map(|c| &mut c.meta),
&mut param_directives,
n,
);
self.expect_sym(")")?;
params = Some(list);
}
Ok(ClassExtends {
name,
name_span,
param_comments,
params,
param_directives,
span: self.span_from(start),
})
}
/// `constraint name { ... }`, kept as verbatim source.
///
/// The constraint language is a grammar of its own (`dist`, `->`,
/// `solve ... before`, `inside`, `foreach`, `if`/`else`) that lucisv models
/// none of, and reflowing it has no payoff, so the block is copied out of
/// the source by span. A prototype (`constraint c;`) has no braces.
///
/// The name may carry a `my_class::` scope — the out-of-block constraint
/// definition of an `extern constraint` prototype (IEEE 1800 §18.5.2),
/// written at file or package scope. That is the constraint sibling of
/// `function my_class::method(...)`, so it reuses the same scoped-name
/// path; the scope is only consumed, since the whole item is verbatim and
/// binds no name either way.
fn parse_constraint(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
self.take_member_prefix();
self.expect_kw("constraint")?;
self.parse_method_name()?;
if !self.eat_sym(";") {
self.expect_sym("{")?;
self.skip_balanced("{", "}")?;
// `constraint c { ... };` — a stray `;` is legal and belongs to the
// block, not to the item that follows it.
self.eat_sym(";");
}
Ok(self.verbatim_since(start, col))
}
/// The `{ ... }` of a `randomize() with { ... }` inline constraint
/// (IEEE 1800 §18.7), kept as verbatim source.
///
/// It is a `constraint` body written inside an expression — the same
/// second grammar (`dist`, `soft`, constraint `if`, `->`) that
/// [`Parser::parse_constraint`] declines to model — so it gets exactly
/// the same treatment: skip to the matching brace and copy the bytes out.
/// The `with` keyword itself is left outside the capture — the caller has
/// already consumed it, together with the comments written on either side
/// of it — and the formatter writes it back.
fn parse_with_constraint(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
self.expect_sym("{")?;
self.skip_balanced("{", "}")?;
Ok(self.verbatim_since(start, col))
}
/// `covergroup name ... endgroup [: label]`, kept as verbatim source, for
/// the same reason constraints are: coverpoints, bins and crosses are a
/// separate grammar with nothing to gain from canonical layout.
fn parse_covergroup(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
self.take_member_prefix();
self.expect_kw("covergroup")?;
while !self.at_eof() && !self.cur().is_kw("endgroup") {
self.bump();
}
self.expect_closer("endgroup")?;
self.parse_label()?;
self.eat_sym(";");
Ok(self.verbatim_since(start, col))
}
/// True when the cursor opens a concurrent assertion (IEEE 1800 §16.14):
/// `[label :] assert|assume|cover|restrict property ( ... )`.
///
/// The `property` keyword is what makes this unambiguous, and demanding
/// it is what leaves the *immediate* assertion path (`assert (expr) ...`,
/// which is a real statement node) exactly as it was. `restrict` is not a
/// lexer keyword — it is an ordinary identifier everywhere else — so it is
/// matched by text, which is safe for the same reason: no type or instance
/// name can be followed by the `property` keyword.
fn at_concurrent_assertion(&self) -> bool {
let mut i = 0;
if self.cur().kind == TokenKind::Ident && self.nth(1).is_sym(":") {
i = 2;
}
let head = self.nth(i);
let opens = head.is_kw("assert")
|| head.is_kw("assume")
|| head.is_kw("cover")
|| (head.kind == TokenKind::Ident && head.text == "restrict");
opens && self.nth(i + 1).is_kw("property")
}
/// A concurrent assertion, kept as verbatim source.
///
/// `assert property (@(posedge clk) a |-> ##[1:3] b) else $error("...");`
/// — the property expression is a grammar of its own (`|->`, `##[1:3]`,
/// `throughout`, `disable iff`, `$rose`) that lucisv models none of, and
/// there is no layout convention worth inventing for it, so the whole
/// item is copied out of the source by span exactly as a `constraint` is.
fn parse_concurrent_assertion(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
if self.cur().kind == TokenKind::Ident && self.nth(1).is_sym(":") {
self.bump();
self.bump();
}
// `assert` / `assume` / `cover` / `restrict`.
self.bump();
self.expect_kw("property")?;
self.expect_sym("(")?;
self.skip_balanced("(", ")")?;
self.skip_action_block()?;
Ok(self.verbatim_since(start, col))
}
/// The action block after a concurrent assertion's property spec: a bare
/// `;`, a pass statement, an `else` fail statement, or both.
fn skip_action_block(&mut self) -> PResult<()> {
if self.eat_kw("else") {
return self.skip_action_stmt();
}
self.skip_action_stmt()?;
if self.eat_kw("else") {
self.skip_action_stmt()?;
}
Ok(())
}
/// One `statement_or_null` of an action block, skipped verbatim: a
/// `begin ... end` block, or everything through the next `;`.
///
/// Brackets *and* the block keywords ([`BLOCK_OPENERS`] /
/// [`BLOCK_CLOSERS`]) are skipped as units, so neither a `;` nor an `end`
/// written inside one ends the scan early: the pass statement of
/// `assert property (p) if (c) begin x = 1; end else y = 2;` is the whole
/// `if`, not `if (c) begin x = 1;`. A statement that ends with a block
/// ends *there* — no `;` follows one — unless an `else` continues it.
///
/// The scan never runs past the end of the file and never stands still:
/// every arm consumes at least one token, and `at_eof` is checked on every
/// turn, so unbalanced input is a clean parse error.
fn skip_action_stmt(&mut self) -> PResult<()> {
// How many block keywords are open. Zero means the scan is looking for
// the statement's own terminator.
let mut depth = 0usize;
loop {
if self.at_eof() {
return self.error("expected `;`");
}
let t = self.cur();
if t.is_sym("(") {
self.bump();
self.skip_balanced("(", ")")?;
} else if t.is_sym("[") {
self.bump();
self.skip_balanced("[", "]")?;
} else if t.is_sym("{") {
self.bump();
self.skip_balanced("{", "}")?;
} else if (t.is_kw("disable") || t.is_kw("wait")) && self.nth(1).is_kw("fork") {
// `disable fork` / `wait fork` name the enclosing block; they
// do not open one.
self.bump();
self.bump();
} else if BLOCK_OPENERS.iter().any(|k| t.is_kw(k)) {
depth += 1;
self.bump();
} else if BLOCK_CLOSERS.iter().any(|k| t.is_kw(k)) {
if depth == 0 {
// A closer with nothing open: the action statement is
// missing its terminator and the scan has reached the end
// of the block the assertion itself sits in.
return self.error("expected `;`");
}
depth -= 1;
self.bump();
if depth == 0 {
self.parse_label()?;
if !self.eat_kw("else") {
return Ok(());
}
}
} else if depth == 0 && self.eat_sym(";") {
return Ok(());
} else {
self.bump();
}
}
}
/// `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
/// the same second grammar, with local variable declarations mixed in.
fn parse_property_decl(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
let end_kw = if self.cur().is_kw("sequence") { "endsequence" } else { "endproperty" };
self.bump();
while !self.at_eof() && !self.cur().is_kw(end_kw) {
self.bump();
}
self.expect_closer(end_kw)?;
self.parse_label()?;
Ok(self.verbatim_since(start, col))
}
// ------------------------------------------------------------------
// Conditional-directive split recovery
//
// An `ifdef region whose arms are each an *incomplete fragment* of one
// construct — two spellings of a declaration head sharing one body, two
// struct bodies sharing one closing brace — is not a tree. There is no
// AST for it and no layout to apply, so it joins `constraint`,
// `covergroup` and the concurrent assertions in the verbatim bucket: the
// exact source bytes, re-indented on the first line only.
//
// The recovery is deliberately hard to reach. It fires only after a real
// parse failure, and only when that failure is the grammar refusing a
// `else / `elsif / `endif that closes a region which is genuinely open
// and which the failed item did not open, with a bracket the arm left
// open. Everything else — a plain syntax error that merely sits near a
// directive, a garbage token run with directives in it, an unterminated
// region, a stray closer with nothing open — still refuses.
// See `docs/features/directive-split/README.md`.
// ------------------------------------------------------------------
/// Count the conditional-compilation directive standing at the cursor,
/// which the caller is about to consume as an `ItemKind::Directive`.
///
/// This is the **only** place [`Parser::open_conds`] grows, and the whole
/// reason it is here rather than in [`Parser::bump`] is that `bump` cannot
/// tell item scope from anything else. The constructs lucisv keeps as
/// opaque bytes — `constraint`, `covergroup`, `property` / `sequence`,
/// concurrent assertions, and the split regions this module produces —
/// walk their bodies token by token *through* `bump` to find their closer,
/// so counting there let a `` `ifdef `` written inside a constraint body
/// leak into the file's item-scope nesting (QA round 4). Counting here
/// instead makes "not item scope, does not count" the **default**: a new
/// verbatim construct inherits the right behaviour by doing nothing, and
/// there is no flag anyone can forget to set.
///
/// Saturating on the way down, so a stray closer near the top of a file
/// cannot make a later, genuine region look unopened.
fn note_item_conditional(&mut self) {
let t = self.cur();
if opens_conditional(t) {
self.open_conds += 1;
} else if closes_conditional(t) {
self.open_conds = self.open_conds.saturating_sub(1);
}
}
/// Turn an item that is really one arm of a split conditional region — or
/// one whose own region splits it — into a verbatim block, or hand `err`
/// back untouched.
///
/// The two shapes are mirror images and are tried in that order:
///
/// - the item **is an arm** of a region opened before it started, and
/// failed on the `` `else `` / `` `endif `` that closes it
/// ([`Parser::at_split_conditional`]);
/// - the item **opened** a region part-way through and failed on the
/// `` `ifdef `` itself ([`Parser::at_opening_split`]).
fn split_conditional_item(&mut self, mark: &ItemMark, err: ParseError) -> PResult<ItemKind> {
if self.at_split_conditional(mark) {
if let Some((end_pos, conds_after)) = self.scan_split_extent(mark) {
// The block swallowed the region's own `else / `endif, which
// *are* item-scope nesting even though they now sit inside
// opaque bytes. The extent scan already worked out what they
// leave open, so this is the second and last place
// `open_conds` moves.
self.open_conds = conds_after;
return Ok(ItemKind::Verbatim(self.capture_split(mark, end_pos)));
}
}
if self.at_opening_split(mark) {
if let Some(end_pos) = self.scan_opening_split_extent(mark) {
// No `open_conds` adjustment: every exit of the scan leaves
// conditional nesting back at zero, so the block is
// conditional-balanced and item scope is undisturbed.
return Ok(ItemKind::Verbatim(self.capture_split(mark, end_pos)));
}
}
Err(err)
}
/// Replace the construct that began at `mark` with the source bytes
/// running from its first token to `end_pos`, and put the cursor there.
fn capture_split(&mut self, mark: &ItemMark, end_pos: usize) -> RawText {
self.diagnostics.truncate(mark.diags);
let start = self.tokens[mark.pos].span.start;
let col = self.tokens[mark.pos].col;
// Walk the span from the top rather than jumping the cursor: `bump`
// is what moves a token's trailing comment into the pending bucket,
// and the comment written after the construct's last token must end
// up there for the next node to harvest. The copies that fall *inside*
// the span — including the duplicates of the ones the failed parse
// already moved — are dropped by `verbatim_since`.
self.pos = mark.pos;
while self.pos < end_pos && !self.at_eof() {
self.bump();
}
self.verbatim_since(start, col)
}
/// True when the item that began at `mark` failed *because* it is one arm
/// of a conditional region it did not open.
///
/// Four things must hold at once:
///
/// 1. the cursor — where the failure was raised — stands on a
/// `` `else `` / `` `elsif `` / `` `endif ``;
/// 2. a conditional region was already open when the item started, so
/// that directive has something to close. A stray closer opens nothing
/// and ends nothing: it is broken input, and the parse error stands;
/// 3. the item's own conditional nesting is back to zero there, so the
/// live region is one opened *before* the item rather than by it;
/// 4. the arm left a bracket open, i.e. it is structurally a fragment.
/// A missing `;` leaves nothing open and is indistinguishable from a
/// typo, so it is refused.
fn at_split_conditional(&self, mark: &ItemMark) -> bool {
let at = self.cur();
if !continues_conditional(at) && !closes_conditional(at) {
return false;
}
if mark.conds == 0 {
return false;
}
let mut cond = 0i32;
let mut brackets = 0i32;
for t in self.tokens.get(mark.pos..self.pos).unwrap_or_default() {
if t.kind == TokenKind::Directive {
if opens_conditional(t) {
cond += 1;
} else if closes_conditional(t) {
cond -= 1;
}
} else if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
brackets += 1;
} else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") {
brackets -= 1;
}
}
cond == 0 && brackets > 0
}
/// One past the last token of the construct the split region belongs to,
/// paired with the item-scope conditional nesting left open after it — or
/// `None` when the file holds no such end.
///
/// The scan follows the *first* arm and skips the alternatives whole: the
/// arms are rival spellings of the same thing, so counting all of their
/// brackets would demand as many closers as there are arms. It ends where
/// all three of (a) the regions the scan itself opened are closed, (b) the
/// region that was already open has been closed — conditional nesting is
/// back to the level it stood at where that region began — and (c) the
/// brackets the chosen scan opened are closed: at the first `;` that sees
/// all three.
///
/// A `` `else `` / `` `elsif `` / `` `endif `` met at scan level zero with
/// no region live is a stray closer, not a split, and gives up — the same
/// refusal the trigger makes, repeated here because the scan walks past
/// the point the trigger looked at.
fn scan_split_extent(&self, mark: &ItemMark) -> Option<(usize, u32)> {
// Regions this scan opened, and regions that were already open when
// it started. A directive at scan level zero belongs to the latter.
let mut cond = 0i32;
let mut live = mark.conds;
let mut closed_outer = false;
let mut brackets = 0i32;
let mut i = mark.pos;
while let Some(t) = self.tokens.get(i) {
if t.kind == TokenKind::Eof {
return None;
}
if t.kind == TokenKind::Directive {
if opens_conditional(t) {
cond += 1;
} else if closes_conditional(t) {
if cond > 0 {
cond -= 1;
} else {
live = live.checked_sub(1)?;
closed_outer = true;
}
} else if continues_conditional(t) && cond == 0 {
live = live.checked_sub(1)?;
closed_outer = true;
i = self.skip_conditional_arms(i + 1)?;
continue;
}
} else if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
brackets += 1;
} else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") {
brackets -= 1;
if brackets < 0 {
return None;
}
} else if t.is_sym(";") && brackets == 0 && cond == 0 && closed_outer {
return Some((i + 1, live));
}
i += 1;
}
None
}
/// Skip from `from` — just past a `` `else `` / `` `elsif `` — through the
/// `` `endif `` that closes the region that directive belongs to, nested
/// regions included. `None` if the file ends first.
fn skip_conditional_arms(&self, from: usize) -> Option<usize> {
let mut nested = 0i32;
let mut i = from;
while let Some(t) = self.tokens.get(i) {
if t.kind == TokenKind::Eof {
return None;
}
if opens_conditional(t) {
nested += 1;
} else if closes_conditional(t) {
if nested == 0 {
return Some(i + 1);
}
nested -= 1;
}
i += 1;
}
None
}
/// True when the construct that began at `mark` failed *because* it opened
/// a conditional region part-way through and the rest of it lives in the
/// arms:
///
/// ```verilog
/// assign aes_ctrl_rnd_ctr =
/// `ifdef GATE_LEVEL
/// `AES_HIER.u_aes_cipher_control.mr_rnd_ctr[3:0];
/// `else
/// `AES_HIER.u_aes_cipher_control.rnd_ctr;
/// `endif
/// ```
///
/// This is [`Parser::at_split_conditional`]'s mirror image. There the
/// failure is on the directive that *closes* a region opened before the
/// construct; here it is on the `` `ifdef `` that opens one inside it. An
/// expression has no "this might be a pass-through directive" branch — the
/// directive pass-through lives at item- and statement-list boundaries and
/// in the four bracketed-list sites `directives-in-lists` covers — so the
/// parse fails immediately, before any bracket is opened and before the
/// closing-split trigger can ever be evaluated.
///
/// Two things must hold at once:
///
/// 1. the cursor stands on an `` `ifdef `` / `` `ifndef ``. Any other
/// directive mid-expression (`` `include ``, a bare `` `endif ``) is
/// still an ordinary parse error;
/// 2. the construct is **one unterminated run** reaching that directive —
/// it has consumed at least one token and no `;` at bracket depth zero
/// since it started. A failure that propagated up from deeper inside an
/// already-terminated construct would otherwise capture the whole
/// enclosing item on a guess; this is what keeps the recovery at the
/// innermost construct the region actually splits.
fn at_opening_split(&self, mark: &ItemMark) -> bool {
if !opens_conditional(self.cur()) {
return false;
}
if self.pos <= mark.pos {
return false;
}
let mut brackets = 0i32;
for t in self.tokens.get(mark.pos..self.pos).unwrap_or_default() {
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
brackets += 1;
} else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") {
brackets -= 1;
} else if t.is_sym(";") && brackets <= 0 {
return false;
}
}
true
}
/// One past the last token of the construct a region opened inside it
/// splits, or `None` when the file holds no such end.
///
/// Like [`Parser::scan_split_extent`] the scan follows the **first** arm
/// and skips the alternatives whole, because the arms are rival spellings
/// of the same thing and counting every arm's brackets would demand as
/// many closers as there are arms.
///
/// Where the construct ends depends on which side of the region its
/// terminator was written on, and both spellings are in the corpus:
///
/// - the arms each carry their own `;` (`chip_if.sv`), so the construct
/// ends at the `` `endif `` that closes the region — there is no `;`
/// after it, and scanning on would swallow the next item;
/// - the region is balanced *inside* the construct and the `;` comes after
/// it (`chip_earlgrey_asic.sv`, `jtag_dtm_reg_block.sv`), so the
/// construct ends at that `;`.
///
/// `terminated_in_arm` is what tells them apart: a `;` met at bracket
/// depth zero while a region is still open means the tail is inside the
/// arms.
///
/// A head that opens a body ends at its closing keyword instead, and one
/// whose ending is not modeled ([`ConstructEnd::Unknown`]) is refused.
///
/// Every exit leaves conditional nesting back at zero, so a captured block
/// is conditional-balanced and item-scope nesting is undisturbed.
fn scan_opening_split_extent(&self, mark: &ItemMark) -> Option<usize> {
let end = construct_end(self.tokens.get(mark.pos..)?);
if end == ConstructEnd::Unknown {
return None;
}
let semi_ends = end == ConstructEnd::Semi;
let mut cond = 0i32;
let mut brackets = 0i32;
let mut terminated_in_arm = false;
let mut i = mark.pos;
while let Some(t) = self.tokens.get(i) {
if t.kind == TokenKind::Eof {
return None;
}
if t.kind == TokenKind::Directive {
if opens_conditional(t) {
cond += 1;
} else if closes_conditional(t) {
cond -= 1;
if cond < 0 {
return None;
}
if semi_ends && cond == 0 && terminated_in_arm {
return Some(i + 1);
}
} else if continues_conditional(t) {
// A `else / `elsif with nothing open is a stray closer,
// not an arm boundary: broken input, and the parse error
// stands — the same refusal the closing-split scan makes.
if cond == 0 {
return None;
}
i = self.skip_conditional_arms(i + 1)?;
cond -= 1;
if semi_ends && cond == 0 && terminated_in_arm {
return Some(i);
}
continue;
}
} else if let ConstructEnd::Keyword(kw) = end {
if t.is_kw(kw) && brackets == 0 && cond == 0 {
return Some(self.past_end_label(i + 1));
}
}
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
brackets += 1;
} else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") {
brackets -= 1;
if brackets < 0 {
return None;
}
} else if semi_ends && t.is_sym(";") && brackets == 0 {
if cond == 0 {
return Some(i + 1);
}
terminated_in_arm = true;
}
i += 1;
}
None
}
/// One past `after_kw`'s optional `: name` — the label a closing keyword
/// may carry (`endfunction : new`), which belongs inside the block with
/// the keyword it names.
fn past_end_label(&self, after_kw: usize) -> usize {
let colon = self.tokens.get(after_kw).is_some_and(|t| t.is_sym(":"));
let name = self.tokens.get(after_kw + 1).is_some_and(|t| t.kind == TokenKind::Ident);
if colon && name {
after_kw + 2
} else {
after_kw
}
}
/// True when the cursor opens a parameterized type's `#( ... )`.
fn at_type_params(&self) -> bool {
self.cur().is_sym("#") && self.nth(1).is_sym("(")
}
/// The `#( ... )` of a parameterized type or class reference, verbatim.
fn parse_type_params(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
self.expect_sym("#")?;
self.expect_sym("(")?;
self.skip_balanced("(", ")")?;
Ok(self.verbatim_since(start, col))
}
/// Consume tokens through the `close` that matches the `open` already
/// consumed. Brackets inside strings and comments cannot appear here —
/// the lexer has already turned those into single tokens.
fn skip_balanced(&mut self, open: &str, close: &str) -> PResult<()> {
let mut depth = 1usize;
while depth > 0 {
if self.at_eof() {
return self.error(format!("expected `{close}`"));
}
let t = self.cur();
if t.is_sym(open) {
depth += 1;
} else if t.is_sym(close) {
depth -= 1;
}
self.bump();
}
Ok(())
}
/// The source bytes consumed since `start`, as verbatim text.
///
/// A comment written *inside* the block is part of those bytes, so the
/// copy [`Parser::bump`] moved into a pending bucket is dropped — leaving
/// it there would reattach it to the next node and print it a second time.
/// The filter is by span rather than by a saved length precisely so the
/// comment written *after* the block's last token on the same line
/// (`} // end of constraint`) survives: it is outside the span, so it
/// stays pending and is harvested by whoever comes next.
fn verbatim_since(&mut self, start: u32, col: u32) -> RawText {
let span = self.span_from(start);
let outside = |c: &Comment| c.span.end <= span.start || c.span.start >= span.end;
self.pending_leading.retain(outside);
self.pending_trailing.retain(outside);
RawText { text: self.slice(span), col, span }
}
// ------------------------------------------------------------------
// Module
// ------------------------------------------------------------------
/// A `module` / `macromodule` / `interface` declaration. The three share
/// one header grammar (IEEE 1800 §23.2.1, §25.3) and one body item list —
/// only the closing keyword differs, so `end_kw` is the whole difference.
fn parse_module(&mut self, end_kw: &str) -> PResult<Module> {
let kw = self.bump().text;
let Name { text: name, span: name_span } = self.expect_name()?;
let mut imports = Vec::new();
while self.cur().is_kw("import") {
let mut meta = self.take_meta();
let paths = self.parse_import_list()?;
meta.trailing = self.take_trailing();
imports.push(HeaderImport { meta, paths });
}
let param_comments = self.take_before_open("#");
let ParamPortList {
ports: param_ports,
directives: param_directives,
dangling: param_dangling,
} = self.parse_param_port_list()?;
let port_comments = self.take_before_open("(");
let (ports, port_dangling, port_directives) = self.parse_port_list()?;
self.expect_sym(";")?;
let mut items = Vec::new();
while !self.at_body_end(end_kw) {
items.push(self.item_or_recover()?);
}
let dangling = self.take_dangling();
self.expect_closer(end_kw)?;
let (end_label, end_label_span) = split_label(self.parse_label()?);
Ok(Module {
kw,
name,
name_span,
imports,
param_comments,
param_ports,
param_directives,
param_dangling,
port_comments,
ports,
port_directives,
port_dangling,
items,
dangling,
end_label,
end_label_span,
})
}
/// `modport a (input x, output y), b (...);` (IEEE 1800 §25.5).
fn parse_modport(&mut self) -> PResult<Vec<ModportDecl>> {
self.expect_kw("modport")?;
let mut out = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let Name { text: name, span: name_span } = self.expect_name()?;
self.expect_sym("(")?;
let mut ports = Vec::new();
while !self.cur().is_sym(")") && !self.at_eof() {
ports.push(self.parse_modport_port()?);
if !ports.last().is_some_and(|p: &ModportPort| p.comma) {
break;
}
}
let dangling = self.take_dangling();
self.expect_sym(")")?;
let span = self.span_from(start);
if let Some(last) = ports.last_mut() {
if last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
self.take_before_sep(&mut meta, ",");
let comma = self.eat_sym(",");
meta.trailing = self.take_trailing();
out.push(ModportDecl { meta, name, name_span, ports, dangling, comma, span });
if !comma {
break;
}
}
self.expect_sym(";")?;
Ok(out)
}
/// One direction group of a modport's port list. `input a, b, output c` is
/// two groups: the comma keeps the group open only while a plain name
/// follows it — a direction keyword starts the next group.
fn parse_modport_port(&mut self) -> PResult<ModportPort> {
const MODPORT_KEYWORDS: &[&str] =
&["input", "output", "inout", "ref", "import", "export", "clocking"];
let start = self.here();
let mut meta = self.take_meta();
let t = self.cur();
if t.kind != TokenKind::Keyword || !MODPORT_KEYWORDS.contains(&t.text.as_str()) {
return self.error("expected a modport port direction");
}
let kw = self.bump().text;
let mut names = vec![self.expect_name()?];
let mut span = self.span_from(start);
let mut comma = false;
loop {
self.take_before_sep(&mut meta, ",");
if !self.eat_sym(",") {
break;
}
if self.cur().kind != TokenKind::Ident {
// The comma separates this group from the next one.
comma = true;
break;
}
names.push(self.expect_name()?);
span = self.span_from(start);
}
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(ModportPort { meta, kw, names, comma, span })
}
/// `clocking cb @(posedge clk); ... endclocking` (IEEE 1800 §14.3). The
/// `default` keyword, when written, has already been consumed.
fn parse_clocking(&mut self, is_default: bool) -> PResult<ClockingDecl> {
self.expect_kw("clocking")?;
let name =
if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None };
// `default clocking cb;` selects an existing block and has no body.
let event = if self.eat_sym("@") { Some(self.parse_sens_list()?) } else { None };
self.expect_sym(";")?;
if event.is_none() {
return Ok(ClockingDecl {
is_default,
name,
event,
items: Vec::new(),
dangling: Vec::new(),
has_end: false,
end_label: None,
end_label_span: None,
});
}
let mut items = Vec::new();
while !self.at_body_end("endclocking") {
items.push(self.parse_clocking_item()?);
}
let dangling = self.take_dangling();
self.expect_closer("endclocking")?;
let (end_label, end_label_span) = split_label(self.parse_label()?);
Ok(ClockingDecl {
is_default,
name,
event,
items,
dangling,
has_end: true,
end_label,
end_label_span,
})
}
/// One item of a clocking block's body: `default input #1step output #0;`
/// or a direction group (`input #2 a, b;`).
fn parse_clocking_item(&mut self) -> PResult<ClockingItem> {
let start = self.here();
let mut meta = self.take_meta();
let kind = if self.eat_kw("default") {
let input = if self.eat_kw("input") { Some(self.parse_clocking_skew()?) } else { None };
let output =
if self.eat_kw("output") { Some(self.parse_clocking_skew()?) } else { None };
if input.is_none() && output.is_none() {
return self.error("expected `input` or `output` after `default`");
}
ClockingItemKind::Default { input, output }
} else {
let t = self.cur();
if !(t.is_kw("input") || t.is_kw("output") || t.is_kw("inout")) {
return self.error("expected a clocking item");
}
let dir = self.bump().text;
let skew =
if self.at_clocking_skew() { Some(self.parse_clocking_skew()?) } else { None };
let mut names = vec![self.expect_name()?];
while self.eat_sym(",") {
names.push(self.expect_name()?);
}
ClockingItemKind::Signals { dir, skew, names }
};
let span = self.span_from(start);
self.expect_sym(";")?;
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(ClockingItem { meta, kind, span })
}
/// True when the cursor is on a clocking skew rather than on the first
/// signal name: `#2`, `#1step`, `posedge`, `negedge`, `edge`.
fn at_clocking_skew(&self) -> bool {
let t = self.cur();
t.is_sym("#") || t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge")
}
/// A clocking skew, as written: `#2`, `#1step`, `negedge`. Kept as text —
/// it is a delay or an edge, never something lucisv re-lays out — so the
/// printer writes back exactly what the source said. The `#(min:typ:max)`
/// spelling is not supported; see the feature README's Assumptions.
fn parse_clocking_skew(&mut self) -> PResult<String> {
if self.eat_sym("#") {
let t = self.cur();
if !matches!(t.kind, TokenKind::Number | TokenKind::Ident) {
return self.error("expected a clocking skew delay");
}
return Ok(format!("#{}", self.bump().text));
}
let t = self.cur();
if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") {
return Ok(self.bump().text);
}
self.error("expected a clocking skew")
}
/// A `#( parameter ... )` port list, shared by module and class headers.
/// `ports` is `None` when no `#(` was written at the cursor at all.
fn parse_param_port_list(&mut self) -> PResult<ParamPortList> {
let mut out = ParamPortList::default();
if !self.cur().is_sym("#") {
return Ok(out);
}
self.bump();
self.expect_sym("(")?;
let mut list = Vec::new();
self.take_list_directives(&mut out.directives, 0);
if !self.cur().is_sym(")") {
loop {
list.push(self.parse_param_port()?);
if let Some(last) = list.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = list.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(&mut out.directives, list.len());
// Without a comma and without a directive the list is over.
// With one, only the closing bracket says so: an `` `ifdef``
// arm may end without a comma and another arm may still follow
// (`` `else``), or the arm may have been the tail of the list.
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
}
out.dangling = self.take_dangling();
self.expect_sym(")")?;
out.ports = Some(list);
Ok(out)
}
fn parse_param_port(&mut self) -> PResult<ParamPort> {
let start = self.here();
let mut meta = self.take_meta();
let kw = if self.cur().is_kw("parameter") || self.cur().is_kw("localparam") {
Some(self.bump().text)
} else {
None
};
if self.eat_kw("type") {
let Name { text: name, span: name_span } = self.expect_name()?;
let default = if self.eat_sym("=") { Some(self.parse_type_expr()?) } else { None };
let span = self.span_from(start);
meta.trailing = self.take_trailing();
return Ok(ParamPort {
meta,
kw,
ty: DataType::default(),
is_type: true,
name,
name_span,
unpacked: Vec::new(),
default,
comma: false,
span,
});
}
let ty = self.parse_opt_data_type()?;
let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?;
let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(ParamPort {
meta,
kw,
ty,
is_type: false,
name,
name_span,
unpacked,
default,
comma: false,
span,
})
}
/// The header port list, the comments written before its closing `)`, and
/// the directives written between its ports.
fn parse_port_list(&mut self) -> PResult<(PortList, Vec<Comment>, Vec<ListDirective>)> {
if !self.cur().is_sym("(") {
return Ok((PortList::None, Vec::new(), Vec::new()));
}
self.bump();
// Directives before the first port. Harvested here rather than in the
// loop below because both the ANSI/non-ANSI decision and the
// written-but-empty check read the token after them.
let mut directives = Vec::new();
self.take_list_directives(&mut directives, 0);
if self.cur().is_sym(")") {
// `module m (/* c */);` — the comments stay between the parens.
let dangling = self.take_dangling();
self.bump();
return Ok((PortList::Empty, dangling, directives));
}
let ansi = {
let t = self.cur();
t.is_kw("input")
|| t.is_kw("output")
|| t.is_kw("inout")
|| t.is_kw("ref")
|| TYPE_KEYWORDS.contains(&t.text.as_str())
|| NET_KEYWORDS.contains(&t.text.as_str())
// A direction is optional on the *first* ANSI port too (IEEE
// 1800 §23.2.2.2), and an interface port is normally written
// with none at all: `module m (bus_if bus, input logic clk);`.
// Such a port opens with a plain identifier, exactly as a
// non-ANSI name list does, so the two are told apart by what
// follows it — a second identifier (past any `pkg::` chain,
// `#( ... )` override or packed dimensions) means a type and a
// name, while the `,` or `)` of `module m (a, b);` does not.
|| (t.kind == TokenKind::Ident
&& (self.at_typed_declarator() || self.at_modport_port()))
};
if ansi {
let mut ports = Vec::new();
loop {
ports.push(self.parse_ansi_port()?);
if let Some(last) = ports.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = ports.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(&mut directives, ports.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
// Comments on their own lines before the `)` belong inside it.
let dangling = self.take_dangling();
self.expect_sym(")")?;
// A trailing comment on the closing line belongs to the last port.
if let Some(last) = ports.last_mut() {
if last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
Ok((PortList::Ansi(ports), dangling, directives))
} else {
let mut ports = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let name = self.expect_ident()?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let comma = self.eat_sym(",");
meta.trailing = self.take_trailing();
ports.push(NonAnsiPort { meta, name, comma, span });
let dirs = self.take_list_directives(&mut directives, ports.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
let dangling = self.take_dangling();
self.expect_sym(")")?;
Ok((PortList::NonAnsi(ports), dangling, directives))
}
}
fn parse_ansi_port(&mut self) -> PResult<AnsiPort> {
let start = self.here();
let mut meta = self.take_meta();
let dir = {
let t = self.cur();
if t.is_kw("input") || t.is_kw("output") || t.is_kw("inout") || t.is_kw("ref") {
Some(self.bump().text)
} else {
None
}
};
let net = {
let t = self.cur();
let is_net = t.kind == TokenKind::Keyword && NET_KEYWORDS.contains(&t.text.as_str());
if is_net || t.is_kw("var") {
Some(self.bump().text)
} else {
None
}
};
let ty = if self.at_modport_port() {
self.parse_modport_port_type()?
} else {
self.parse_opt_data_type()?
};
let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?;
let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(AnsiPort { meta, dir, net, ty, name, name_span, unpacked, default, comma: false, span })
}
/// Does the cursor sit on an interface port that names a modport,
/// `bus_if.mp bus` (IEEE 1800 §25.4)? Only a *port header* is spelled this
/// way — after an identifier anywhere else a `.` opens a member access —
/// so the shape is recognized here rather than in `parse_opt_data_type`.
fn at_modport_port(&self) -> bool {
self.cur().kind == TokenKind::Ident
&& self.nth(1).is_sym(".")
&& self.nth(2).kind == TokenKind::Ident
&& self.nth(3).kind == TokenKind::Ident
}
/// The `bus_if.mp` of an interface port, as its type. The modport is glued
/// onto the interface name exactly as a `pkg::` qualifier is, so every
/// consumer that prints or scans a type name still sees one string.
fn parse_modport_port_type(&mut self) -> PResult<DataType> {
let mut name = self.expect_ident()?;
self.expect_sym(".")?;
name.push('.');
name.push_str(&self.expect_ident()?);
Ok(DataType { name, ..DataType::default() })
}
/// Parse a possibly-implicit data type. Stops before the declarator name.
fn parse_opt_data_type(&mut self) -> PResult<DataType> {
let mut ty = DataType::default();
// `virtual [interface] <iface>` — a virtual interface type reference
// (IEEE 1800 §25.9). It stands wherever a type does: a typedef's base
// type, a task/function argument, a variable. (A *declaration* reaches
// this function with the `virtual` already taken into
// `DataDecl::qualifiers`, so this only fires for the other positions.)
if self.cur().is_kw("virtual") {
self.bump();
ty.virt =
Some(if self.eat_kw("interface") { VirtualKw::Interface } else { VirtualKw::Bare });
}
let t = self.cur();
// An anonymous aggregate stands where a type name does (IEEE 1800
// §6.19, §7.2): `enum logic [1:0] {IDLE, STOP} state, state_next;`
// (clock_divider.sv:59), `struct packed { ... } s;`. The body is the
// same one `typedef` takes, so the two share a parser.
if t.is_kw("enum") {
ty.extra = Some(Box::new(TypeExtra::Enum(self.parse_enum_type()?)));
return Ok(ty);
}
if t.is_kw("struct") || t.is_kw("union") {
ty.extra = Some(Box::new(TypeExtra::Struct(self.parse_struct_type()?)));
return Ok(ty);
}
if t.kind == TokenKind::Keyword && TYPE_KEYWORDS.contains(&t.text.as_str()) {
ty.name = self.bump().text;
} else if t.kind == TokenKind::Ident {
// User-defined type only if what follows still leaves an
// identifier for the declarator name.
if self.at_typed_declarator() {
let mut name = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
name.push_str("::");
name.push_str(&self.expect_ident()?);
}
ty.name = name;
if self.at_type_params() {
ty.extra = Some(Box::new(TypeExtra::Params(self.parse_type_params()?)));
}
}
}
if self.cur().is_kw("signed") || self.cur().is_kw("unsigned") {
ty.signing = Some(self.bump().text);
}
ty.packed = self.parse_dims()?;
Ok(ty)
}
fn parse_dims(&mut self) -> PResult<Vec<Dim>> {
let mut dims = Vec::new();
while self.cur().is_sym("[") {
let start = self.here();
self.bump();
let kind = if self.eat_sym("]") {
// `[]` — a dynamic array.
dims.push(Dim { kind: DimKind::Dynamic, span: self.span_from(start) });
continue;
} else if self.cur().is_sym("*") && self.nth(1).is_sym("]") {
// `[*]` — a wildcard-keyed associative array.
self.bump();
DimKind::Wildcard
} else {
let a = self.parse_expr()?;
let b = if self.eat_sym(":") { Some(self.parse_expr()?) } else { None };
DimKind::Range { a, b }
};
self.expect_sym("]")?;
dims.push(Dim { kind, span: self.span_from(start) });
}
Ok(dims)
}
fn parse_type_expr(&mut self) -> PResult<Expr> {
let start = self.here();
let ty = self.parse_type_ref()?;
if ty.is_implicit() {
// Nothing that can be a type stands here. `parse_type_ref` takes a
// bare identifier, so whatever is at the cursor is not one and
// `expect_ident` always fails — naming the offending token the way
// this position has always named it.
self.expect_ident()?;
return self.error("expected a type");
}
Ok(self.expr_at(start, ExprKind::Type(ty)))
}
// ------------------------------------------------------------------
// Declarations
// ------------------------------------------------------------------
fn parse_param_decl(&mut self) -> PResult<ParamDecl> {
let kw = self.bump().text;
// `localparam type payload_t = logic [$clog2(NumReq)-1:0];` — a type
// parameter outside the `#( ... )` list
// (lossy_valid_to_stream_tb.sv:26). Its default is a type, not a value.
let is_type = self.eat_kw("type");
let ty = if is_type { DataType::default() } else { self.parse_opt_data_type()? };
let declarators = self.parse_declarator_list(is_type)?;
Ok(ParamDecl { kw, is_type, ty, declarators })
}
/// Parse declarators up to (but not consuming) the terminating `;`.
fn parse_declarators(&mut self) -> PResult<Vec<Declarator>> {
self.parse_declarator_list(false)
}
/// Parse declarators; `type_init` makes each `= ...` a type rather than an
/// expression, which is what a `type` parameter's default is.
fn parse_declarator_list(&mut self, type_init: bool) -> PResult<Vec<Declarator>> {
let mut out = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?;
let init = if self.eat_sym("=") {
Some(if type_init { self.parse_type_expr()? } else { self.parse_expr()? })
} else {
None
};
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
// Harvested on the last declarator too: a comment written before
// the `;` (`logic x /* verilator split_var */;`) belongs to the
// declaration, and the `;` has not been consumed yet, so nothing
// written after it can be picked up here.
meta.trailing = self.take_trailing();
out.push(Declarator { meta, name, name_span, unpacked, init, span });
if !more {
break;
}
}
Ok(out)
}
fn parse_data_decl(&mut self) -> PResult<DataDecl> {
let mut net = None;
let mut qualifiers = Vec::new();
loop {
let t = self.cur();
if t.kind == TokenKind::Keyword && NET_KEYWORDS.contains(&t.text.as_str()) {
net = Some(self.bump().text);
} else if t.kind == TokenKind::Keyword && MEMBER_QUALIFIERS.contains(&t.text.as_str()) {
let was_virtual = t.is_kw("virtual");
qualifiers.push(self.bump().text);
// `virtual interface my_if h;` — the `interface` keyword is
// part of the qualifier, not a construct of its own, and is
// only ever legal directly after `virtual`.
if was_virtual && self.cur().is_kw("interface") {
qualifiers.push(self.bump().text);
}
} else {
break;
}
}
let delay = if net.is_some() && self.cur().is_sym("#") {
self.bump();
Some(self.parse_delay_value()?)
} else {
None
};
let ty = self.parse_opt_data_type()?;
let declarators = self.parse_declarators()?;
self.expect_sym(";")?;
Ok(DataDecl { net, delay, qualifiers, ty, declarators })
}
fn parse_port_decl(&mut self) -> PResult<PortDecl> {
let dir = self.bump().text;
let net = {
let t = self.cur();
let is_net = t.kind == TokenKind::Keyword && NET_KEYWORDS.contains(&t.text.as_str());
if is_net || t.is_kw("var") {
Some(self.bump().text)
} else {
None
}
};
let ty = self.parse_opt_data_type()?;
let declarators = self.parse_declarators()?;
self.expect_sym(";")?;
Ok(PortDecl { dir, net, ty, declarators })
}
fn parse_typedef(&mut self) -> PResult<Typedef> {
self.expect_kw("typedef")?;
if self.eat_kw("class") {
// Forward declaration: `typedef class my_class;` — no type to
// alias, just a name promised to exist later in the compilation.
let Name { text: name, span: name_span } = self.expect_name()?;
self.expect_sym(";")?;
return Ok(Typedef {
name,
name_span,
unpacked: Vec::new(),
kind: TypedefKind::ForwardClass,
});
}
if self.cur().is_kw("enum") {
let e = self.parse_enum_type()?;
let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?;
self.expect_sym(";")?;
return Ok(Typedef { name, name_span, unpacked, kind: TypedefKind::Enum(e) });
}
if self.cur().is_kw("struct") || self.cur().is_kw("union") {
let s = self.parse_struct_type()?;
let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?;
self.expect_sym(";")?;
return Ok(Typedef { name, name_span, unpacked, kind: TypedefKind::Struct(s) });
}
let ty = self.parse_opt_data_type()?;
let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?;
self.expect_sym(";")?;
Ok(Typedef { name, name_span, unpacked, kind: TypedefKind::Alias(ty) })
}
/// `enum [base] { A, B = 2 }` — the cursor is on `enum` and stops on the
/// token after the closing `}`. Shared by `typedef enum ...` and by an
/// anonymous enum used as a type in place (IEEE 1800 §6.19).
fn parse_enum_type(&mut self) -> PResult<EnumType> {
self.expect_kw("enum")?;
// The base type may be a keyword (`logic [1:0]`) or a typedef'd name
// (`typedef enum action_mask_t {...}`, prim_count_pkg.sv:10).
let base = if self.cur().is_sym("{") { None } else { Some(self.parse_type_ref()?) };
self.expect_sym("{")?;
let mut members = Vec::new();
let mut directives = Vec::new();
self.take_list_directives(&mut directives, 0);
loop {
let start = self.here();
let mut meta = self.take_meta();
let Name { text: name, span: name_span } = self.expect_name()?;
// Enum member ranges (`VAL[4]`) are rare; unsupported.
let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let comma = self.eat_sym(",");
meta.trailing = self.take_trailing();
members.push(EnumMember { meta, name, name_span, value, comma, span });
let dirs = self.take_list_directives(&mut directives, members.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym("}")) {
break;
}
}
let dangling = self.take_dangling();
self.expect_sym("}")?;
Ok(EnumType { base, members, directives, dangling })
}
/// `struct|union [packed] [signing] { members }` — the cursor is on the
/// keyword and stops on the token after the closing `}`. Shared by
/// `typedef struct ...`, an anonymous struct used as a type in place, and
/// a struct member whose own type is an inline struct (uart_reg_pkg.sv:30).
fn parse_struct_type(&mut self) -> PResult<StructType> {
let kw = self.bump().text;
let packed = self.eat_kw("packed");
let signing = if self.cur().is_kw("signed") || self.cur().is_kw("unsigned") {
Some(self.bump().text)
} else {
None
};
self.expect_sym("{")?;
let mut members = Vec::new();
while !self.cur().is_sym("}") && !self.at_eof() {
let start = self.here();
let mut meta = self.take_meta();
let ty = self.parse_opt_data_type()?;
let declarators = self.parse_declarators()?;
self.expect_sym(";")?;
let span = self.span_from(start);
meta.trailing = self.take_trailing();
members.push(StructMember { meta, ty, declarators, span });
}
let dangling = self.take_dangling();
self.expect_sym("}")?;
Ok(StructType { kw, packed, signing, members, dangling })
}
/// A data type in a position where one is *required* — an enum base type,
/// a `type` parameter's default. Unlike [`Parser::parse_opt_data_type`],
/// which only takes an identifier when a declarator name follows it, a
/// bare `my_type_t` here is the whole type.
fn parse_type_ref(&mut self) -> PResult<DataType> {
let ty = self.parse_opt_data_type()?;
if !ty.is_implicit() || self.cur().kind != TokenKind::Ident {
return Ok(ty);
}
let mut name = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
name.push_str("::");
name.push_str(&self.expect_ident()?);
}
let mut ty = DataType { name, ..DataType::default() };
if self.at_type_params() {
ty.extra = Some(Box::new(TypeExtra::Params(self.parse_type_params()?)));
}
if self.cur().is_kw("signed") || self.cur().is_kw("unsigned") {
ty.signing = Some(self.bump().text);
}
ty.packed = self.parse_dims()?;
Ok(ty)
}
// ------------------------------------------------------------------
// Module items
// ------------------------------------------------------------------
fn parse_cont_assign(&mut self) -> PResult<ContAssign> {
self.expect_kw("assign")?;
let strength = self.parse_opt_drive_strength()?;
let delay = if self.cur().is_sym("#") {
self.bump();
Some(self.parse_delay_value()?)
} else {
None
};
let mut assigns = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let lhs = self.parse_unary()?;
let mark = self.pending_trailing.len();
self.expect_sym("=")?;
let rhs_comments = self.take_around(mark);
let rhs = self.parse_expr()?;
let span = self.span_from(start);
// The last pair's separator is the statement's `;`, so a comment
// written before it (`assign y = a /* c */;`) belongs on the
// value's side of it, not after it.
self.take_before_sep(&mut meta, ",");
self.take_before_sep(&mut meta, ";");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
assigns.push(AssignPair { meta, lhs, rhs, rhs_comments, span });
if !more {
break;
}
}
self.expect_sym(";")?;
Ok(ContAssign { strength, delay, assigns })
}
/// 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`).
///
/// 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.
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;
self.expect_sym(",")?;
if !is_drive_strength(self.cur()) {
return self.error("expected a drive strength");
}
let second = self.bump().text;
self.expect_sym(")")?;
Ok(Some(DriveStrength { first, second }))
}
fn parse_delay_value(&mut self) -> PResult<Expr> {
if self.cur().is_sym("(") {
let start = self.here();
self.bump();
let inner_start = self.here();
let first = self.parse_expr()?;
let expr = if self.eat_sym(":") {
let typ = self.parse_expr()?;
self.expect_sym(":")?;
let max = self.parse_expr()?;
self.expr_at(
inner_start,
ExprKind::MinTypMax {
min: Box::new(first),
typ: Box::new(typ),
max: Box::new(max),
},
)
} else {
first
};
self.expect_sym(")")?;
Ok(self.expr_at(
start,
ExprKind::Paren { inner: Box::new(expr), before: Vec::new(), after: Vec::new() },
))
} else {
self.parse_primary()
}
}
/// True when the cursor opens a `bind` directive (IEEE 1800 §23.11).
///
/// `bind` is deliberately *not* in the lexer's keyword table — the same
/// call lucisv makes for `new`/`this`/`super` — so that `obj.bind()` keeps
/// parsing as the ordinary method call it is in existing testbenches.
/// A directive is recognized from its shape instead: the word `bind`,
/// then a target scope (a name, possibly a `.`-separated hierarchical
/// path), then either the `:` of an instance list or the module name of
/// the instantiation. A declaration of a variable called `bind` reaches
/// `;`, `,`, `=` or a dimension there, so it never matches.
fn at_bind_directive(&self) -> bool {
let t = self.cur();
if t.kind != TokenKind::Ident || t.text != "bind" {
return false;
}
let mut p = self.pos + 1;
if !self.tokens.get(p).is_some_and(|t| t.kind == TokenKind::Ident) {
return false;
}
p += 1;
while self.tokens.get(p).is_some_and(|t| t.is_sym("."))
&& self.tokens.get(p + 1).is_some_and(|t| t.kind == TokenKind::Ident)
{
p += 2;
}
self.tokens.get(p).is_some_and(|t| t.is_sym(":") || t.kind == TokenKind::Ident)
}
/// `bind <target> [: <inst>, ...] <module> [#(...)] <name> (...);`
fn parse_bind(&mut self) -> PResult<BindDirective> {
self.bump(); // `bind`
// The target is a bare string, so a comment written before it has no
// node to attach to: harvest it here, where source order is still
// known, rather than letting it drift onto the instance below.
let target_comments = self.take_dangling();
let start = self.here();
let mut target = self.expect_ident()?;
while self.cur().is_sym(".") {
self.bump();
target.push('.');
target.push_str(&self.expect_ident()?);
}
let target_span = self.span_from(start);
let mut instances = Vec::new();
if self.eat_sym(":") {
loop {
instances.push(self.expect_name()?);
if !self.eat_sym(",") {
break;
}
}
}
let module_comments = self.take_dangling();
let inst = self.parse_instantiation()?;
Ok(BindDirective { target, target_comments, target_span, instances, module_comments, inst })
}
fn parse_instantiation(&mut self) -> PResult<Instantiation> {
let module_start = self.here();
let mut module = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
module.push_str("::");
module.push_str(&self.expect_ident()?);
}
let module_span = self.span_from(module_start);
let param_comments = self.take_before_open("#");
let mut params = None;
let mut param_directives = Vec::new();
if self.cur().is_sym("#") {
self.bump();
self.expect_sym("(")?;
let mut list = Vec::new();
self.take_list_directives(&mut param_directives, 0);
if !self.cur().is_sym(")") {
loop {
list.push(self.parse_connection()?);
if let Some(last) = list.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = list.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(&mut param_directives, list.len());
// Same two break conditions as a header's lists (see
// `Parser::parse_module`): no comma and no directive ends
// the list, and after a directive only the closing bracket
// does — an `` `ifdef`` arm may end without a comma and
// still be followed by an `` `else`` arm.
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
}
// Comments before the `)` of the override list belong inside it.
let n = list.len();
self.take_last_entry_before_close(
list.last_mut().map(|c| &mut c.meta),
&mut param_directives,
n,
);
self.expect_sym(")")?;
params = Some(list);
}
let mut instances = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let Name { text: name, span: name_span } = self.expect_name()?;
let dims = self.parse_dims()?;
let conn_comments = self.take_before_open("(");
self.expect_sym("(")?;
let mut conn_directives = Vec::new();
let conns = self.parse_connections(&mut conn_directives)?;
self.expect_sym(")")?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
instances.push(Instance {
meta,
name,
name_span,
dims,
conn_comments,
conns,
conn_directives,
span,
});
if !more {
break;
}
}
self.expect_sym(";")?;
Ok(Instantiation {
module,
module_span,
param_comments,
params,
param_directives,
instances,
})
}
/// Move the comments written before a list's closing bracket onto the last
/// entry *in source order*, which is a trailing directive when the list has
/// one and the last element otherwise.
///
/// Without the directive case they would print before it, having moved
/// backwards across a token; with an element-less list (`` #(`include
/// "config.vh") ``) the directive is the only place they can go at all.
fn take_last_entry_before_close(
&mut self,
last_element: Option<&mut Meta>,
directives: &mut [ListDirective],
elements: usize,
) {
if let Some(d) = directives.last_mut().filter(|d| d.before == elements) {
self.take_before_sep(&mut d.meta, ")");
} else if let Some(meta) = last_element {
self.take_before_sep(meta, ")");
}
}
/// The connections of one instance. `directives` collects the
/// `` `ifdef``-style lines written between them; the harvest must run
/// before the `.`-peek below, or a directive standing before the first
/// connection would be read as a positional expression.
fn parse_connections(&mut self, directives: &mut Vec<ListDirective>) -> PResult<Connections> {
self.take_list_directives(directives, 0);
if self.cur().is_sym(")") {
return Ok(Connections::Ordered(Vec::new()));
}
if self.at_named_connection() {
let mut conns = Vec::new();
loop {
conns.push(self.parse_connection()?);
if let Some(last) = conns.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = conns.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(directives, conns.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
// Comments before the closing `)` belong to the last entry: after
// it they would sit outside the connection list entirely.
let n = conns.len();
self.take_last_entry_before_close(conns.last_mut().map(|c| &mut c.meta), directives, n);
Ok(Connections::Named(conns))
} else {
let mut conns = Vec::new();
loop {
let start = self.here();
let meta = self.take_meta();
let expr = if self.cur().is_sym(",") || self.cur().is_sym(")") {
None
} else {
Some(self.parse_expr()?)
};
// An omitted connection (`u (a, , c)`) consumed no token, so
// this is the empty span where it would have started.
let span = self.span_from(start);
let mut meta = meta;
self.take_before_sep(&mut meta, ",");
let comma = self.eat_sym(",");
if comma {
meta.trailing = self.take_trailing();
}
conns.push(OrderedConn { meta, expr, comma, span });
let dirs = self.take_list_directives(directives, conns.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
let n = conns.len();
self.take_last_entry_before_close(conns.last_mut().map(|c| &mut c.meta), directives, n);
Ok(Connections::Ordered(conns))
}
}
/// True when the connection list starts with a named connection. The
/// leading `(* ... *)` attributes of the first entry are looked past:
/// they belong to the connection, not to the list.
fn at_named_connection(&self) -> bool {
let mut i = self.pos;
while i < self.tokens.len() && self.tokens[i].kind == TokenKind::Attribute {
i += 1;
}
self.tokens.get(i).is_some_and(|t| t.is_sym("."))
}
/// `.name(expr)`, `.name()`, `.name`, `.*`, or (for parameter lists and
/// ordered parameter overrides) a bare expression.
fn parse_connection(&mut self) -> PResult<Connection> {
let start = self.here();
let mut meta = self.take_meta();
// `(* async *) .async_data_o (x)` — an attribute instance may precede
// a port connection (IEEE 1800 §A.4.1.1), corpus
// `common_cells/src/cdc_fifo_gray.sv:140`. Harvested exactly the way
// an item's or a statement's attributes are.
while self.cur().kind == TokenKind::Attribute {
meta.attrs.push(self.take_raw_text());
let tok = &mut self.tokens[self.pos];
meta.leading.append(&mut tok.leading);
}
if self.eat_sym(".") {
let star = self.cur().span;
if self.eat_sym("*") {
let span = self.span_from(start);
return Ok(Connection {
meta,
name: "*".to_string(),
name_span: star,
expr: None,
close_comments: Vec::new(),
comma: false,
span,
});
}
let Name { text: name, span: name_span } = self.expect_name()?;
let mark = self.pending_trailing.len();
let paren_start = self.here();
let mut close_comments = Vec::new();
let expr = if self.eat_sym("(") {
if self.cur().is_sym(")") {
// `.name(/* unused */)`: the comments were written inside
// these parens and are printed back inside them.
let inside = self.take_around(mark);
self.bump();
Some(self.expr_at(paren_start, ExprKind::Empty(inside)))
} else {
let value_mark = self.pending_trailing.len();
let e = self.parse_expr_or_type()?;
// `.name(x /* c */)`: written inside the parens, so it is
// printed inside them too.
close_comments = self.take_around(value_mark);
self.expect_sym(")")?;
Some(e)
}
} else {
None
};
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(Connection { meta, name, name_span, expr, close_comments, comma: false, span })
} else {
let e = self.parse_expr_or_type()?;
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(Connection {
meta,
name: String::new(),
name_span: TextRange::empty(span.start),
expr: Some(e),
close_comments: Vec::new(),
comma: false,
span,
})
}
}
/// In parameter connections a value may be a type (`.T(logic [7:0])`).
fn parse_expr_or_type(&mut self) -> PResult<Expr> {
let t = self.cur();
if t.kind == TokenKind::Keyword
&& TYPE_KEYWORDS.contains(&t.text.as_str())
&& !self.nth(1).is_sym("'")
{
return self.parse_type_expr();
}
self.parse_expr()
}
fn parse_gate_instantiation(&mut self) -> PResult<GateInstantiation> {
let gate = self.bump().text;
let delay = if self.cur().is_sym("#") {
self.bump();
Some(self.parse_delay_value()?)
} else {
None
};
let mut instances = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let name =
if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None };
let (name, name_span) = split_label(name);
self.expect_sym("(")?;
let mut args = Vec::new();
if !self.cur().is_sym(")") {
let first = self.parse_expr_item()?;
args = self.parse_expr_list(first, ")")?;
}
self.expect_sym(")")?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
instances.push(GateInstance { meta, name, name_span, args, span });
if !more {
break;
}
}
self.expect_sym(";")?;
Ok(GateInstantiation { gate, delay, instances })
}
// ------------------------------------------------------------------
// Generate constructs
// ------------------------------------------------------------------
/// An `else if` chain recurses here directly, bypassing `parse_item`. Gated.
fn parse_gen_if(&mut self) -> PResult<GenIf> {
self.enter()?;
let out = self.parse_gen_if_inner();
self.leave();
out
}
fn parse_gen_if_inner(&mut self) -> PResult<GenIf> {
let start = self.here();
self.expect_kw("if")?;
self.expect_sym("(")?;
let cond = self.parse_expr()?;
self.expect_sym(")")?;
let then = self.parse_gen_block()?;
let els = if self.cur().is_kw("else") {
let meta = self.take_meta();
self.bump();
if self.cur().is_kw("if") {
Some(Box::new(GenElse::If(meta, Box::new(self.parse_gen_if()?))))
} else {
let _ = meta;
Some(Box::new(GenElse::Block(self.parse_gen_block()?)))
}
} else {
None
};
Ok(GenIf { cond, then, els, span: self.span_from(start) })
}
fn parse_gen_for(&mut self) -> PResult<GenFor> {
self.expect_kw("for")?;
self.expect_sym("(")?;
let init_genvar = self.eat_kw("genvar");
let lhs = self.parse_unary()?;
self.expect_sym("=")?;
let rhs = self.parse_expr()?;
let init = SimpleAssign { lhs, op: "=".to_string(), rhs };
self.expect_sym(";")?;
let cond = self.parse_expr()?;
self.expect_sym(";")?;
let step = self.parse_for_step()?;
self.expect_sym(")")?;
let body = self.parse_gen_block()?;
Ok(GenFor { init, init_genvar, cond, step, body })
}
fn parse_gen_case(&mut self) -> PResult<GenCase> {
self.expect_kw("case")?;
self.expect_sym("(")?;
let expr = self.parse_expr()?;
self.expect_sym(")")?;
let mut items = Vec::new();
while !self.at_body_end("endcase") {
let start = self.here();
let mut meta = self.take_meta();
let labels = if self.eat_kw("default") {
let _ = self.eat_sym(":");
Vec::new()
} else {
let first = self.parse_expr_item()?;
let labels = self.parse_expr_list(first, ":")?;
self.expect_sym(":")?;
labels
};
let body = self.parse_gen_block()?;
let span = self.span_from(start);
meta.trailing = self.take_trailing();
items.push(GenCaseItem { meta, labels, body, span });
}
let dangling = self.take_dangling();
self.expect_closer("endcase")?;
Ok(GenCase { expr, items, dangling })
}
fn parse_gen_block(&mut self) -> PResult<GenBlock> {
let start = self.here();
if self.cur().is_kw("begin") {
self.bump();
let (label, label_span) = split_label(self.parse_label()?);
let mut items = Vec::new();
while !self.at_body_end("end") {
items.push(self.item_or_recover()?);
}
let dangling = self.take_dangling();
self.expect_closer("end")?;
let (end_label, end_label_span) = split_label(self.parse_label()?);
Ok(GenBlock {
label,
label_span,
is_block: true,
items,
dangling,
end_label,
end_label_span,
span: self.span_from(start),
})
} else {
let item = self.item_or_recover()?;
let span = item.span;
Ok(GenBlock {
label: None,
label_span: None,
is_block: false,
items: vec![item],
dangling: Vec::new(),
end_label: None,
end_label_span: None,
span,
})
}
}
// ------------------------------------------------------------------
// Functions and tasks
// ------------------------------------------------------------------
fn parse_function(&mut self) -> PResult<FunctionDecl> {
self.parse_function_decl(None)
}
fn parse_function_decl(&mut self, dpi: Option<DpiImport>) -> PResult<FunctionDecl> {
let prefix = self.take_member_prefix();
// `extern`, `pure virtual` and a DPI import all introduce a prototype:
// a header, a `;`, and no `endfunction`. The body is written elsewhere
// (in C for a DPI import, nowhere at all for a pure virtual).
let is_prototype = dpi.is_some() || prefix.iter().any(|q| q == "extern" || q == "pure");
self.expect_kw("function")?;
let mut qualifiers = Vec::new();
while self.cur().is_kw("automatic") || self.cur().is_kw("static") {
qualifiers.push(self.bump().text);
}
// Return type: everything up to the identifier followed by `(` or `;`.
let ret = {
let t = self.cur();
if t.kind == TokenKind::Ident && (self.nth(1).is_sym("(") || self.nth(1).is_sym(";")) {
None
} else {
let ty = self.parse_opt_data_type()?;
if ty.is_implicit() {
None
} else {
Some(ty)
}
}
};
// Out-of-body definitions of an `extern` method write the class name
// in front: `function void my_class::configure(...)`.
let (scope, Name { text: name, span: name_span }) = self.parse_method_name()?;
let has_parens = self.cur().is_sym("(");
let args = self.parse_tf_ports()?;
self.expect_sym(";")?;
let (stmts, dangling, end) = if is_prototype {
(Vec::new(), Vec::new(), None)
} else {
self.parse_tf_body("endfunction")?
};
let (end_label, end_label_span) = split_label(end);
// `endfunction : f;` — the stray `;` is a null class item
// (IEEE 1800 A.1.9). It is recorded here so the footer can print it
// back where it was written instead of on a line of its own.
let end_semi = !is_prototype && self.eat_sym(";");
Ok(FunctionDecl {
dpi,
prefix,
qualifiers,
is_prototype,
scope,
ret,
name,
name_span,
has_parens,
args,
stmts,
dangling,
end_label,
end_label_span,
end_semi,
})
}
fn parse_task(&mut self) -> PResult<TaskDecl> {
self.parse_task_decl(None)
}
fn parse_task_decl(&mut self, dpi: Option<DpiImport>) -> PResult<TaskDecl> {
let prefix = self.take_member_prefix();
let is_prototype = dpi.is_some() || prefix.iter().any(|q| q == "extern" || q == "pure");
self.expect_kw("task")?;
let mut qualifiers = Vec::new();
while self.cur().is_kw("automatic") || self.cur().is_kw("static") {
qualifiers.push(self.bump().text);
}
let (scope, Name { text: name, span: name_span }) = self.parse_method_name()?;
let has_parens = self.cur().is_sym("(");
let args = self.parse_tf_ports()?;
self.expect_sym(";")?;
let (stmts, dangling, end) = if is_prototype {
(Vec::new(), Vec::new(), None)
} else {
self.parse_tf_body("endtask")?
};
let (end_label, end_label_span) = split_label(end);
// See `parse_function_decl`: a stray `;` after the footer.
let end_semi = !is_prototype && self.eat_sym(";");
Ok(TaskDecl {
dpi,
prefix,
qualifiers,
is_prototype,
scope,
name,
name_span,
has_parens,
args,
stmts,
dangling,
end_label,
end_label_span,
end_semi,
})
}
/// `let name [( ports )] = expr;` (IEEE 1800 §11.12), corpus
/// `common_cells/test/clk_int_div_tb.sv:53`.
///
/// A `let` port is a task/function port without a direction — an optional
/// type, a name, optional dimensions and an optional default — so the
/// port list is read by [`Parser::parse_tf_ports`]. A `let` with no ports
/// writes no parens at all, which is what `has_parens` records.
fn parse_let(&mut self) -> PResult<LetDecl> {
self.expect_kw("let")?;
let Name { text: name, span: name_span } = self.expect_name()?;
let has_parens = self.cur().is_sym("(");
let ports = self.parse_tf_ports()?;
self.expect_sym("=")?;
let value = self.parse_expr()?;
self.expect_sym(";")?;
Ok(LetDecl { name, name_span, has_parens, ports, value })
}
fn parse_tf_ports(&mut self) -> PResult<Vec<TfArg>> {
let mut args = Vec::new();
if !self.cur().is_sym("(") {
return Ok(args);
}
self.bump();
if self.eat_sym(")") {
return Ok(args);
}
loop {
let start = self.here();
let mut meta = self.take_meta();
let dir = {
let t = self.cur();
if t.is_kw("const") && self.nth(1).is_kw("ref") {
// `const ref` (IEEE 1800 §13.5.2), corpus
// `ibex/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils_pkg.sv:104`.
self.bump();
self.bump();
Some("const ref".to_string())
} else if t.is_kw("input")
|| t.is_kw("output")
|| t.is_kw("inout")
|| t.is_kw("ref")
{
Some(self.bump().text)
} else {
None
}
};
let ty = self.parse_opt_data_type()?;
let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?;
let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
meta.trailing = self.take_trailing();
args.push(TfArg { meta, dir, ty, name, name_span, unpacked, default, span });
if !more {
break;
}
}
self.expect_sym(")")?;
Ok(args)
}
fn parse_tf_body(&mut self, end_kw: &str) -> PResult<(Vec<Stmt>, Vec<Comment>, Option<Name>)> {
let mut stmts = Vec::new();
while !self.at_body_end(end_kw) {
stmts.push(self.stmt_or_recover()?);
}
let dangling = self.take_dangling();
self.expect_closer(end_kw)?;
Ok((stmts, dangling, self.parse_label()?))
}
// ------------------------------------------------------------------
// Statements
// ------------------------------------------------------------------
/// Statements nest through blocks and every compound statement. Gated.
fn parse_stmt(&mut self) -> PResult<Stmt> {
self.enter()?;
let out = self.parse_stmt_inner();
self.leave();
out
}
fn parse_stmt_inner(&mut self) -> PResult<Stmt> {
let start = self.here();
let mut meta = self.take_meta();
while self.cur().kind == TokenKind::Attribute {
meta.attrs.push(self.take_raw_text());
let tok = &mut self.tokens[self.pos];
meta.leading.append(&mut tok.leading);
}
let mark =
ItemMark { pos: self.pos, conds: self.open_conds, diags: self.diagnostics.len() };
let kind = match self.parse_stmt_kind() {
Ok(kind) => kind,
Err(e) => self.split_conditional_stmt(&mark, e)?,
};
let span = self.span_from(start);
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(Stmt { meta, kind, span })
}
/// The statement half of [`Parser::split_conditional_item`]: a statement a
/// region opened inside it splits becomes a verbatim block.
///
/// `jtag_dtm_reg_block.sv:173` is the corpus shape — a `` `ifdef `` between
/// two named arguments of a call, deep inside a function body:
///
/// ```verilog
/// abits.configure(
/// .volatile(0),
/// `ifdef USE_DMI_INTERFACE
/// .reset(32'h10),
/// `else
/// .reset(32'h07),
/// `endif
/// .has_reset(1));
/// ```
///
/// Only the **opening** shape is recognized here. The closing one is
/// item-scope by construction: [`Parser::open_conds`] counts the
/// `` `ifdef ``s consumed as *items*, so `mark.conds` inside a body would
/// be answering a question about a different scope. Nothing in the corpus
/// asks for it, and guessing would widen the net for no evidence.
///
/// Running here rather than only at item level is what keeps the capture
/// at the innermost construct: a statement failure that reached
/// `parse_item_inner` would be scanned from the enclosing `module` or
/// `class` keyword instead.
fn split_conditional_stmt(&mut self, mark: &ItemMark, err: ParseError) -> PResult<StmtKind> {
if self.at_opening_split(mark) {
if let Some(end_pos) = self.scan_opening_split_extent(mark) {
return Ok(StmtKind::Verbatim(self.capture_split(mark, end_pos)));
}
}
Err(err)
}
fn parse_stmt_kind(&mut self) -> PResult<StmtKind> {
if self.at_macro_item() || self.at_spaced_macro_call() {
return Ok(StmtKind::MacroStmt(self.parse_macro_call()?));
}
// A concurrent assertion is legal wherever a statement is, and the
// `property` keyword is what tells it apart from the immediate
// `assert (expr)` handled below.
if self.at_concurrent_assertion() {
return Ok(StmtKind::Verbatim(self.parse_concurrent_assertion()?));
}
// A statement label (IEEE 1800 §9.3.5): `check_decode: assert (...)`.
// It is read only here, where a statement is expected — a case item's
// `LABEL:` is read by `parse_case_body`, which never reaches this
// function with the label still in front of it. The concurrent
// assertion above claims `label : assert property` first, because
// that whole construct is captured verbatim, label included.
if self.cur().kind == TokenKind::Ident && self.nth(1).is_sym(":") {
let Name { text: name, span: name_span } = self.expect_name()?;
self.expect_sym(":")?;
let stmt = Box::new(self.parse_stmt()?);
return Ok(StmtKind::Labeled { name, name_span, stmt });
}
let t = self.cur();
if t.kind == TokenKind::Directive {
return Ok(StmtKind::Directive(self.take_raw_text()));
}
if t.is_sym(";") {
self.bump();
return Ok(StmtKind::Null);
}
if t.is_sym("#") {
self.bump();
let delay = self.parse_delay_value()?;
let stmt = if self.eat_sym(";") { None } else { Some(Box::new(self.parse_stmt()?)) };
return Ok(StmtKind::Timing { control: TimingControl::Delay(delay), stmt });
}
if t.is_sym("@") {
self.bump();
let sens = self.parse_sens_list()?;
let stmt = if self.eat_sym(";") { None } else { Some(Box::new(self.parse_stmt()?)) };
return Ok(StmtKind::Timing { control: TimingControl::Event(sens), stmt });
}
if t.is_sym("->") {
self.bump();
let e = self.parse_unary()?;
self.expect_sym(";")?;
return Ok(StmtKind::EventTrigger(e));
}
if t.kind == TokenKind::Keyword {
return self.parse_keyword_stmt();
}
// Fallback: assignment or expression statement.
self.parse_assign_or_expr_stmt()
}
fn parse_keyword_stmt(&mut self) -> PResult<StmtKind> {
let kw = self.cur().text.clone();
match kw.as_str() {
"begin" => {
self.bump();
let (label, label_span) = split_label(self.parse_label()?);
let mut stmts = Vec::new();
while !self.at_body_end("end") {
stmts.push(self.stmt_or_recover()?);
}
let dangling = self.take_dangling();
self.expect_closer("end")?;
let (end_label, end_label_span) = split_label(self.parse_label()?);
Ok(StmtKind::Block {
label,
label_span,
stmts,
dangling,
end_label,
end_label_span,
})
}
"fork" => {
self.bump();
let (label, label_span) = split_label(self.parse_label()?);
let mut stmts = Vec::new();
while !self.at_eof()
&& !self.at_join_kw()
&& !(self.tolerant && self.at_sync_stop())
{
stmts.push(self.stmt_or_recover()?);
}
let dangling = self.take_dangling();
let join_kw = if self.tolerant && !self.at_join_kw() {
self.record("expected `join`");
"join".to_string()
} else {
self.bump().text
};
let (end_label, end_label_span) = split_label(self.parse_label()?);
Ok(StmtKind::ForkJoin {
label,
label_span,
join_kw,
stmts,
dangling,
end_label,
end_label_span,
})
}
"unique" | "unique0" | "priority" => {
let qualifier = Some(self.bump().text);
if self.cur().is_kw("if") {
self.parse_if_stmt(qualifier)
} else {
self.parse_case_stmt(qualifier)
}
}
"if" => self.parse_if_stmt(None),
"case" | "casex" | "casez" => self.parse_case_stmt(None),
"for" => {
self.bump();
self.expect_sym("(")?;
let mut init = Vec::new();
if !self.cur().is_sym(";") {
loop {
// Each init may introduce its own variable, and its
// type may be a keyword or a typedef'd name:
// `for (int i = 0, StateEnumT t = t.first(); ...)`
// (prim_sparse_fsm_flop.sv:48). An identifier only
// counts as a type when another identifier follows it
// — `for (i = 0; ...)` assigns to an existing `i`.
let ty = {
let t = self.cur();
let kw_type = t.kind == TokenKind::Keyword
&& TYPE_KEYWORDS.contains(&t.text.as_str());
if kw_type || (t.kind == TokenKind::Ident && self.at_typed_declarator())
{
Some(self.parse_opt_data_type()?)
} else {
None
}
};
let lhs = self.parse_unary()?;
self.expect_sym("=")?;
let rhs = self.parse_expr()?;
init.push(ForInit {
ty,
assign: SimpleAssign { lhs, op: "=".to_string(), rhs },
});
if !self.eat_sym(",") {
break;
}
}
}
self.expect_sym(";")?;
let cond = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) };
self.expect_sym(";")?;
let mut step = Vec::new();
if !self.cur().is_sym(")") {
step.push(self.parse_for_step()?);
while self.eat_sym(",") {
step.push(self.parse_for_step()?);
}
}
self.expect_sym(")")?;
let body = Box::new(self.parse_stmt()?);
Ok(StmtKind::For { init, cond, step, body })
}
"while" => {
self.bump();
self.expect_sym("(")?;
let cond = self.parse_expr()?;
self.expect_sym(")")?;
Ok(StmtKind::While { cond, body: Box::new(self.parse_stmt()?) })
}
"do" => {
self.bump();
let body = Box::new(self.parse_stmt()?);
self.expect_kw("while")?;
self.expect_sym("(")?;
let cond = self.parse_expr()?;
self.expect_sym(")")?;
self.expect_sym(";")?;
Ok(StmtKind::DoWhile { body, cond })
}
"repeat" => {
self.bump();
self.expect_sym("(")?;
let count = self.parse_expr()?;
self.expect_sym(")")?;
Ok(StmtKind::Repeat { count, body: Box::new(self.parse_stmt()?) })
}
"forever" => {
self.bump();
Ok(StmtKind::Forever { body: Box::new(self.parse_stmt()?) })
}
"foreach" => {
self.bump();
self.expect_sym("(")?;
let (target, vars) = self.parse_foreach_target()?;
self.expect_sym(")")?;
let body = Box::new(self.parse_stmt()?);
Ok(StmtKind::Foreach { target, vars, body })
}
"randcase" => {
self.bump();
let (items, dangling) = self.parse_case_body()?;
Ok(StmtKind::RandCase { items, dangling })
}
"return" => {
self.bump();
let e = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) };
self.expect_sym(";")?;
Ok(StmtKind::Return(e))
}
"break" => {
self.bump();
self.expect_sym(";")?;
Ok(StmtKind::Break)
}
"continue" => {
self.bump();
self.expect_sym(";")?;
Ok(StmtKind::Continue)
}
"disable" => {
self.bump();
// `disable fork;` kills every process the enclosing `fork`
// started; `fork` is a keyword, not a block name.
if self.cur().is_kw("fork") {
self.bump();
self.expect_sym(";")?;
return Ok(StmtKind::Disable("fork".to_string()));
}
let mut name = self.expect_ident()?;
while self.cur().is_sym(".") {
self.bump();
name.push('.');
name.push_str(&self.expect_ident()?);
}
self.expect_sym(";")?;
Ok(StmtKind::Disable(name))
}
"wait" => {
self.bump();
// `wait fork;` waits for the enclosing `fork`'s children
// (IEEE 1800 §9.6.1); `fork` is a keyword, not a condition.
if self.cur().is_kw("fork") {
self.bump();
self.expect_sym(";")?;
return Ok(StmtKind::WaitFork);
}
self.expect_sym("(")?;
let cond = self.parse_expr()?;
self.expect_sym(")")?;
let stmt =
if self.eat_sym(";") { None } else { Some(Box::new(self.parse_stmt()?)) };
Ok(StmtKind::Wait { cond, stmt })
}
"assert" | "assume" | "cover" => {
let kw = self.bump().text;
self.expect_sym("(")?;
let cond = self.parse_expr()?;
self.expect_sym(")")?;
let (then, els) = if self.eat_sym(";") {
(None, None)
} else if self.eat_kw("else") {
(None, Some(Box::new(self.parse_stmt()?)))
} else {
let then = Box::new(self.parse_stmt()?);
let els =
if self.eat_kw("else") { Some(Box::new(self.parse_stmt()?)) } else { None };
(Some(then), els)
};
Ok(StmtKind::Assert { kw, cond, then, els })
}
"force" => {
self.bump();
let lhs = self.parse_unary()?;
self.expect_sym("=")?;
let rhs = self.parse_expr()?;
self.expect_sym(";")?;
Ok(StmtKind::ForceRelease { kw: "force".into(), lhs, rhs: Some(rhs) })
}
"release" | "deassign" => {
let kw = self.bump().text;
let lhs = self.parse_unary()?;
self.expect_sym(";")?;
Ok(StmtKind::ForceRelease { kw, lhs, rhs: None })
}
"parameter" | "localparam" => {
let d = self.parse_param_decl()?;
self.expect_sym(";")?;
Ok(StmtKind::ParamDecl(d))
}
// A package import standing among a block's declarations
// (IEEE 1800 §13.4.2): the same statement the item level takes.
"import" => Ok(StmtKind::Import(self.parse_import_list()?)),
"input" | "output" | "inout" => {
let d = self.parse_port_decl()?;
Ok(StmtKind::PortDecl(d))
}
// `virtual` here is a local variable of virtual-interface type
// (`virtual my_if h;`), the only class-member qualifier that can
// also start a statement.
_ if NET_KEYWORDS.contains(&kw.as_str())
|| TYPE_KEYWORDS.contains(&kw.as_str())
|| matches!(
kw.as_str(),
"var"
| "automatic"
| "static"
| "const"
| "virtual"
| "enum"
| "struct"
| "union"
) =>
{
// A type keyword followed by `'` is a cast expression, not a
// declaration.
if self.nth(1).is_sym("'") {
return self.parse_assign_or_expr_stmt();
}
let d = self.parse_data_decl()?;
Ok(StmtKind::VarDecl(d))
}
_ => self.error(format!("unsupported statement starting with keyword `{kw}`")),
}
}
fn parse_if_stmt(&mut self, qualifier: Option<String>) -> PResult<StmtKind> {
self.expect_kw("if")?;
self.expect_sym("(")?;
let cond = self.parse_expr()?;
self.expect_sym(")")?;
let then = Box::new(self.parse_stmt()?);
let mut else_comments = Vec::new();
let els = if self.cur().is_kw("else") {
// Whatever was written in the gap before `else` stays on the
// keyword's left; the then-branch has already taken its own
// trailing comment.
else_comments = self.take_dangling();
self.bump();
Some(Box::new(self.parse_stmt()?))
} else {
None
};
Ok(StmtKind::If { qualifier, cond, then, else_comments, els })
}
fn parse_case_stmt(&mut self, qualifier: Option<String>) -> PResult<StmtKind> {
let kw = self.bump().text;
self.expect_sym("(")?;
let expr = self.parse_expr()?;
self.expect_sym(")")?;
// `case (x) inside` — the same statement with one extra token, whose
// labels may be `[lo:hi]` ranges (handled by `parse_expr_item`).
let inside = self.eat_kw("inside");
let (items, dangling) = self.parse_case_body()?;
Ok(StmtKind::Case { qualifier, kw, expr, inside, items, dangling })
}
/// The `label : statement` items of a `case`/`randcase` body, the
/// comments left dangling before `endcase`, and the `endcase` itself.
/// A `randcase` item's label is its weight expression, so the two bodies
/// are the same grammar.
fn parse_case_body(&mut self) -> PResult<(Vec<CaseItem>, Vec<Comment>)> {
let mut items = Vec::new();
while !self.at_body_end("endcase") {
let start = self.here();
let mut meta = self.take_meta();
let labels = if self.eat_kw("default") {
let _ = self.eat_sym(":");
Vec::new()
} else {
let first = self.parse_expr_item()?;
let labels = self.parse_expr_list(first, ":")?;
self.expect_sym(":")?;
labels
};
let stmt = self.stmt_or_recover()?;
let span = self.span_from(start);
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
items.push(CaseItem { meta, labels, stmt, span });
}
let dangling = self.take_dangling();
self.expect_closer("endcase")?;
Ok((items, dangling))
}
/// The `arr [ i, j ]` of a `foreach` header, split into the array and the
/// loop variables (IEEE 1800 §12.7.3).
///
/// The array is a package-scoped or hierarchical name that may carry
/// index and member selects along the way — `riscv_instr_pkg::supported_isa`
/// (`riscv_instr.sv:156`), `program_h[id].sub_program_id`
/// (`riscv_callstack_gen.sv:183`), `paths[0].slices`
/// (`csr_utils_pkg.sv:290`) — so it is parsed as a postfix chain. The
/// bracket group the `)` follows is the one that declares the loop
/// variables; every earlier one is an ordinary select.
fn parse_foreach_target(&mut self) -> PResult<(Expr, Vec<Name>)> {
let outer_links = self.links;
let out = self.parse_foreach_target_inner();
self.links = outer_links;
out
}
fn parse_foreach_target_inner(&mut self) -> PResult<(Expr, Vec<Name>)> {
let start = self.here();
let name = self.expect_ident()?;
let mut expr = self.expr_at(start, ExprKind::Ident(name));
loop {
self.link()?;
let t = self.cur();
if t.is_sym(".") {
self.bump();
let name = self.expect_ident()?;
expr = self.expr_at(start, ExprKind::Member { base: Box::new(expr), name });
} else if t.is_sym("::") {
self.bump();
let name = self.expect_ident()?;
expr = self.expr_at(start, ExprKind::Scope { base: Box::new(expr), name });
} else if t.is_sym("[") {
let after = self.scan_matching(self.pos, "[", "]");
if self.tokens.get(after).is_some_and(|t| t.is_sym(")")) {
break;
}
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 {
break;
}
}
self.expect_sym("[")?;
let mut vars = Vec::new();
if !self.cur().is_sym("]") {
vars.push(self.expect_name()?);
while self.eat_sym(",") {
vars.push(self.expect_name()?);
}
}
self.expect_sym("]")?;
Ok((expr, vars))
}
fn parse_for_step(&mut self) -> PResult<ForStep> {
let lhs = self.parse_unary()?;
let op = self.cur().text.clone();
if self.cur().kind == TokenKind::Symbol && (ASSIGN_OPS.contains(&op.as_str()) || op == "<=")
{
self.bump();
let rhs = self.parse_expr()?;
Ok(ForStep::Assign(SimpleAssign { lhs, op, rhs }))
} else {
Ok(ForStep::Expr(lhs))
}
}
fn parse_assign_or_expr_stmt(&mut self) -> PResult<StmtKind> {
// Declaration with a user-defined type: `my_t x;` / `my_t x = e;` /
// `my_t [N-1:0] x;`. An assignment (`x[i] = 1;`) is not one: nothing
// that could be a declarator name follows its brackets.
if self.cur().kind == TokenKind::Ident && self.at_typed_declarator() {
let d = self.parse_data_decl()?;
return Ok(StmtKind::VarDecl(d));
}
// The statement's own meta drained the pending comments, so anything
// trailing from here on was written inside this statement.
let mark = self.pending_trailing.len();
let lhs = self.parse_unary()?;
let op = self.cur().text.clone();
let is_assign = self.cur().kind == TokenKind::Symbol
&& (ASSIGN_OPS.contains(&op.as_str()) || op == "<=");
if is_assign {
// Comments on either side of the operator stay on their side of
// it (`x[6:0] /* opcode */ = v;`); left in the pending buffers
// they would be lost and the safety net would refuse the file.
let op_comments = self.take_around(mark);
self.bump();
let rhs_comments = self.take_around(mark);
let timing = if self.cur().is_sym("#") {
self.bump();
Some(TimingControl::Delay(self.parse_delay_value()?))
} else if self.cur().is_sym("@") {
self.bump();
Some(TimingControl::Event(self.parse_sens_list()?))
} else {
None
};
let rhs = self.parse_expr()?;
self.expect_sym(";")?;
Ok(StmtKind::Assign { lhs, op, op_comments, rhs_comments, timing, rhs })
} else {
self.expect_sym(";")?;
Ok(StmtKind::ExprStmt(lhs))
}
}
fn parse_sens_list(&mut self) -> PResult<SensList> {
if self.cur().is_sym("*") {
// `@*` without parens.
let before = self.take_leading_here();
self.bump();
return Ok(SensList::Star { before, after: Vec::new() });
}
if self.cur().kind == TokenKind::Ident {
// `@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));
}
if self.cur().is_sym("(") && self.nth(1).is_sym("*") {
// `@( /* c */ * /* d */ )`: the comments belong to the star, not
// to whatever node comes next.
let mut before = self.take_trailing_here();
self.bump(); // (
before.append(&mut self.take_leading_here());
let mut after = self.take_trailing_here();
self.bump(); // *
after.append(&mut self.take_leading_here());
self.expect_sym(")")?;
return Ok(SensList::Star { before, after });
}
self.expect_sym("(")?;
let mut items = Vec::new();
let mut sep = None;
loop {
let mut meta = self.take_meta();
let edge = {
let t = self.cur();
if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") {
Some(self.bump().text)
} else {
None
}
};
let expr = self.parse_expr()?;
// 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 });
// 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(",") {
Some(SensSep::Comma)
} else if self.eat_kw("or") {
Some(SensSep::Or)
} else {
break;
};
}
self.expect_sym(")")?;
Ok(SensList::List(items))
}
// ------------------------------------------------------------------
// Expressions
// ------------------------------------------------------------------
pub fn parse_expr(&mut self) -> PResult<Expr> {
self.parse_implication()
}
/// The implication operators `->` and `<->` (IEEE 1800 §11.3.2): the
/// lowest-precedence binary operators, below `? :`, right-associative.
///
/// They sit above [`Parser::parse_ternary`] rather than in the
/// precedence-climbing table because everything in that table binds
/// tighter than `? :`. A `->` is only read as an operator here, *after*
/// an operand — `-> ev;` at statement position is still an event trigger,
/// which `parse_stmt_kind` takes before any expression is parsed.
fn parse_implication(&mut self) -> PResult<Expr> {
let mark = self.pending_trailing.len();
let start = self.here();
let lhs = self.parse_ternary()?;
if !self.cur().is_sym("->") && !self.cur().is_sym("<->") {
return Ok(lhs);
}
let before = self.take_around(mark);
let op = self.bump().text;
let after = self.take_around(mark);
// Right-associative: `a -> b -> c` is `a -> (b -> c)`, so the chain
// recurses and is gated. Only the recursion is: an expression with no
// `->` in it must cost no nesting budget, or every other construct's
// depth limit would halve.
self.enter()?;
let rhs = self.parse_implication();
self.leave();
let rhs = rhs?;
Ok(self.expr_at(
start,
ExprKind::Binary {
lhs: Box::new(lhs),
op,
rhs: Box::new(rhs),
comments: Box::new(BinaryComments { before, after }),
},
))
}
/// The gate for the whole expression grammar: every expression recursion
/// (parens, concatenations, call arguments, index expressions, and the
/// `? :` chain itself) comes back through here.
fn parse_ternary(&mut self) -> PResult<Expr> {
self.enter()?;
let out = self.parse_ternary_inner();
self.leave();
out
}
fn parse_ternary_inner(&mut self) -> PResult<Expr> {
let mark = self.pending_trailing.len();
let start = self.here();
let cond = self.parse_binary(1)?;
if self.cur().is_sym("?") {
// Each of the four gaps inside a `? :` can hold comments; kept
// apart so none of them drifts across the `?` or the `:`.
let before_question = self.take_around(mark);
self.bump();
let after_question = self.take_around(mark);
let then = self.parse_expr()?;
let before_colon = self.take_around(mark);
self.expect_sym(":")?;
let after_colon = self.take_around(mark);
let els = self.parse_ternary()?;
Ok(self.expr_at(
start,
ExprKind::Ternary {
cond: Box::new(cond),
then: Box::new(then),
els: Box::new(els),
comments: Box::new(TernaryComments {
before_question,
after_question,
before_colon,
after_colon,
}),
},
))
} else {
Ok(cond)
}
}
fn binary_prec(&self) -> Option<u8> {
let t = self.cur();
if t.is_kw("inside") {
return Some(7);
}
if t.kind != TokenKind::Symbol {
return None;
}
let p = match t.text.as_str() {
"||" => 1,
"&&" => 2,
"|" => 3,
"^" | "^~" | "~^" => 4,
"&" => 5,
"==" | "!=" | "===" | "!==" | "==?" | "!=?" => 6,
"<" | "<=" | ">" | ">=" => 7,
"<<" | ">>" | "<<<" | ">>>" => 8,
"+" | "-" => 9,
"*" | "/" | "%" => 10,
"**" => 11,
_ => return None,
};
Some(p)
}
/// Operator chains grow the tree one layer per operator without any
/// parser recursion, so they are bounded by [`MAX_CHAIN_LENGTH`]; the
/// links this chain adds are released when it is finished.
fn parse_binary(&mut self, min_prec: u8) -> PResult<Expr> {
let outer_links = self.links;
let out = self.parse_binary_inner(min_prec);
self.links = outer_links;
out
}
fn parse_binary_inner(&mut self, min_prec: u8) -> PResult<Expr> {
let mark = self.pending_trailing.len();
let mut lhs = self.parse_unary()?;
while let Some(prec) = self.binary_prec() {
if prec < min_prec {
break;
}
if self.cur().is_kw("inside") {
self.bump();
// `x inside `MACRO` — the macro expands to the `{...}` set,
// so it stands in for one (corpus
// `opentitan/hw/ip/uart/dv/env/uart_scoreboard.sv:155`).
if self.cur().is_macro() {
let set = self.bump().text;
self.link()?;
let start = lhs.span.start;
lhs = self.expr_at(start, ExprKind::InsideMacro { lhs: Box::new(lhs), set });
continue;
}
self.expect_sym("{")?;
let mut ranges: Vec<ExprItem> = Vec::new();
loop {
let item_start = self.here();
let mut meta = self.take_meta();
let expr = if self.cur().is_sym("[") {
self.bump();
let lo = self.parse_expr()?;
self.expect_sym(":")?;
let hi = self.parse_expr()?;
self.expect_sym("]")?;
self.expr_at(
item_start,
ExprKind::ValueRange { lo: Box::new(lo), hi: Box::new(hi) },
)
} else {
self.parse_expr()?
};
let item_span = self.span_from(item_start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
ranges.push(ExprItem { meta, expr, span: item_span });
if !more {
break;
}
}
if let Some(last) = ranges.last_mut() {
self.take_before_sep(&mut last.meta, "}");
}
self.expect_sym("}")?;
self.link()?;
let start = lhs.span.start;
lhs = self.expr_at(start, ExprKind::Inside { lhs: Box::new(lhs), ranges });
continue;
}
// Comments between the operand and the operator belong to this
// node; left where they are they would drift past the operator.
let before = self.take_around(mark);
let op = self.bump().text;
// Comments between the operator and the right operand belong here
// too; left where they are they would drift past the operand.
let after = self.take_around(mark);
let rhs = self.parse_binary(prec + 1)?;
self.link()?;
let start = lhs.span.start;
lhs = self.expr_at(
start,
ExprKind::Binary {
lhs: Box::new(lhs),
op,
rhs: Box::new(rhs),
comments: Box::new(BinaryComments { before, after }),
},
);
}
Ok(lhs)
}
/// Stacked prefix operators (`~~~~x`) recurse here directly, without
/// passing through `parse_ternary`. Gated.
fn parse_unary(&mut self) -> PResult<Expr> {
self.enter()?;
let out = self.parse_unary_inner();
self.leave();
out
}
fn parse_unary_inner(&mut self) -> PResult<Expr> {
let t = self.cur();
if t.kind == TokenKind::Symbol
&& matches!(
t.text.as_str(),
"!" | "~" | "+" | "-" | "&" | "|" | "^" | "~&" | "~|" | "~^" | "^~" | "++" | "--"
)
{
let start = self.here();
let op = self.bump().text;
let expr = self.parse_unary()?;
return Ok(self.expr_at(start, ExprKind::Unary { op, expr: Box::new(expr) }));
}
self.parse_postfix()
}
/// True if the current token continues a postfix chain.
///
/// `base` is what has been parsed so far: a `#( ... )` only continues a
/// *name* (`uvm_config_db#(virtual bus_if)::get(...)`), never an arbitrary
/// expression, so `x #(y)` after anything else stays what it was.
fn at_postfix_segment(&self, base: &Expr) -> bool {
if self.at_type_params() && matches!(base.kind, ExprKind::Ident(_) | ExprKind::Scope { .. })
{
return true;
}
let t = self.cur();
t.is_sym(".")
|| t.is_sym("::")
|| t.is_sym("[")
|| t.is_sym("(")
|| (t.is_sym("'") && self.nth(1).is_sym("("))
|| t.is_sym("++")
|| t.is_sym("--")
// `with ( ... )` (an array method's iterator argument) and
// `with { ... }` (a `randomize` constraint block) are the two
// postfix spellings of `with`; the delimiter tells them apart and
// demanding one keeps the `with [range]` of a stream expression,
// which lucisv does not model, out of this path.
|| (t.is_kw("with") && (self.nth(1).is_sym("(") || self.nth(1).is_sym("{")))
}
/// Postfix segments are parsed by a loop, but each one wraps the
/// expression so far in another AST layer, so they are bounded by
/// [`MAX_CHAIN_LENGTH`]; the links are released when the chain ends.
fn parse_postfix(&mut self) -> PResult<Expr> {
let outer_links = self.links;
let out = self.parse_postfix_inner();
self.links = outer_links;
out
}
fn parse_postfix_inner(&mut self) -> PResult<Expr> {
let mut expr = self.parse_primary()?;
while self.at_postfix_segment(&expr) {
self.link()?;
// Every segment wraps what came before, so each new node starts
// where the expression so far started.
let start = expr.span.start;
let t = self.cur();
if t.is_sym("#") {
let params = self.parse_type_params()?;
expr =
self.expr_at(start, ExprKind::Parameterized { base: Box::new(expr), params });
} else if t.is_sym(".") {
self.bump();
let name = self.expect_ident()?;
expr = self.expr_at(start, ExprKind::Member { base: Box::new(expr), name });
} else if t.is_sym("::") {
self.bump();
let name = self.expect_ident()?;
expr = self.expr_at(start, ExprKind::Scope { base: Box::new(expr), name });
} else if t.is_sym("[") {
self.bump();
let a = self.parse_expr()?;
let t2 = self.cur();
if t2.is_sym(":") || t2.is_sym("+:") || t2.is_sym("-:") {
let op = self.bump().text;
let b = self.parse_expr()?;
self.expect_sym("]")?;
expr = self.expr_at(
start,
ExprKind::Range {
base: Box::new(expr),
op,
msb: Box::new(a),
lsb: Box::new(b),
},
);
} else {
self.expect_sym("]")?;
expr = self.expr_at(
start,
ExprKind::Index { base: Box::new(expr), index: Box::new(a) },
);
}
} else if t.is_sym("(") {
// Comments written around the brackets have no element to
// attach to: before the `(`, and inside an empty `()`.
let mut comments = CallComments {
before_open: self.take_before_open("("),
..CallComments::default()
};
self.bump();
let mut args = Vec::new();
if !self.cur().is_sym(")") {
let arg_start = self.here();
let meta = self.take_meta();
// A named first argument (`csr_wr(.ptr(x), ...)`) takes
// the same dispatch later elements get in
// `parse_expr_item`; anything else may be a type
// (`$bits(int)`).
let first_expr =
if self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident {
self.parse_named_arg()?
} else if self.at_omitted_element() {
self.expr_at(arg_start, ExprKind::Empty(Vec::new()))
} else {
self.parse_expr_or_type()?
};
let first =
ExprItem { meta, expr: first_expr, span: self.span_from(arg_start) };
args = self.parse_expr_list(first, ")")?;
} else {
// Only what was written *inside* the empty `()`: a comment
// queued from before the callee belongs to whoever owns
// the place it was written, not to this argument list.
comments.dangling = self.take_gap();
}
self.expect_sym(")")?;
expr = self.expr_at(
start,
ExprKind::Call { callee: Box::new(expr), args, comments: Box::new(comments) },
);
} else if t.is_kw("with") {
let mut comments =
WithComments { before_kw: self.take_dangling(), ..WithComments::default() };
if self.nth(1).is_sym("{") {
self.expect_kw("with")?;
comments.after_kw = self.take_before_open("{");
let block = self.parse_with_constraint()?;
expr = self.expr_at(
start,
ExprKind::WithConstraint {
base: Box::new(expr),
block,
comments: Box::new(comments),
},
);
} else {
self.bump(); // with
comments.after_kw = self.take_before_open("(");
// `( expression )` — an ordinary parenthesized primary,
// which is what IEEE 1800 §7.12 spells here.
let arg = self.parse_primary()?;
expr = self.expr_at(
start,
ExprKind::With {
base: Box::new(expr),
arg: Box::new(arg),
comments: Box::new(comments),
},
);
}
} else if t.is_sym("'") && self.nth(1).is_sym("(") {
// Cast: `expr'(x)`. The casting type is a `constant_primary`
// (IEEE 1800 §6.24.1): a name, a package-scoped or
// hierarchical name, a size, or a parenthesized constant
// expression — `(NumLevels)'(unsigned'(j))` (corpus
// `common_cells/src/lzc.sv:67`).
if !matches!(
expr.kind,
ExprKind::Ident(_)
| ExprKind::Number(_)
| ExprKind::Scope { .. }
| ExprKind::Member { .. }
| ExprKind::Paren { .. }
) {
return self.error("unsupported cast base expression");
}
self.bump(); // '
self.bump(); // (
let inner = self.parse_expr()?;
self.expect_sym(")")?;
expr = self
.expr_at(start, ExprKind::Cast { ty: Box::new(expr), expr: Box::new(inner) });
} else {
// `++` / `--`, the only remaining segment kind.
let op = self.bump().text;
expr = self.expr_at(start, ExprKind::Postfix { expr: Box::new(expr), op });
}
}
Ok(expr)
}
/// A streaming concatenation, the `{` already consumed and the cursor on
/// its `<<` or `>>`: IEEE 1800 §11.4.14
/// `{ (<<|>>) [slice_size] { stream_expression {, stream_expression} } }`.
///
/// The `with [range]` form of a stream expression is not supported; a
/// file using it keeps its old "expected expression" error.
fn parse_stream_concat(&mut self, start: u32) -> PResult<Expr> {
let dir = self.bump().text;
// The slice size is optional and is a constant expression or a type
// (`{<< byte {x}}`); a `{` here means it was omitted.
let slice =
if self.cur().is_sym("{") { None } else { Some(Box::new(self.parse_expr_or_type()?)) };
self.expect_sym("{")?;
let first = self.parse_expr_item()?;
let inner = self.parse_expr_list(first, "}")?;
self.expect_sym("}")?;
self.expect_sym("}")?;
Ok(self.expr_at(start, ExprKind::Stream { dir, slice, inner }))
}
/// True when the `'{` just consumed opens the replication form
/// `'{N{0}}` (IEEE 1800 §10.9.1) rather than a keyed or positional
/// pattern.
///
/// Decided by a lookahead rather than by parsing the first element,
/// because the element's leading comments are harvested by the parse and
/// there is nowhere to put them back. The first delimiter reached at
/// bracket depth zero says which form this is: `{` opens the replicated
/// list, `:` a keyed element, `,` or `}` a positional one. The `{` must
/// not be the very first token — `'{{a, b}}` is a pattern whose one
/// element is a concatenation.
fn at_assign_pattern_repl(&self) -> bool {
let mut depth = 0u32;
let mut i = self.pos;
while i < self.tokens.len() {
let t = &self.tokens[i];
if t.kind == TokenKind::Eof {
return false;
}
if t.kind == TokenKind::Symbol {
match t.text.as_str() {
"(" | "[" | "'{" => depth += 1,
")" | "]" => depth = depth.saturating_sub(1),
"{" if depth > 0 => depth += 1,
"{" => return i > self.pos,
"}" if depth > 0 => depth -= 1,
"}" | ":" | "," if depth == 0 => return false,
_ => {}
}
}
i += 1;
}
false
}
/// `'{N{a, b}}`, the `'{` already consumed.
fn parse_assign_pattern_repl(&mut self, start: u32) -> PResult<Expr> {
let count = self.parse_expr()?;
self.expect_sym("{")?;
let first = self.parse_expr_item()?;
let inner = self.parse_expr_list(first, "}")?;
self.expect_sym("}")?;
self.expect_sym("}")?;
Ok(self.expr_at(start, ExprKind::AssignPatternRepl { count: Box::new(count), inner }))
}
/// True when the cursor is the `new` of a shallow copy, IEEE 1800 §8.12:
/// `instr_h = new instr_template[name];` (corpus
/// `ibex/vendor/google_riscv-dv/src/isa/riscv_instr.sv:238`).
///
/// `new` is deliberately not a keyword (see `token.rs`'s `is_keyword`), so
/// this is a two-token test on an ordinary name. Only a plain identifier
/// **on `new`'s own line** starts a source handle: the constructor call
/// `new(...)`, the dynamic-array resize `new[N]` and the bare `new` of
/// `x = new;` are all followed by a symbol and keep parsing as a `Call`,
/// an `Index` and an `Ident`. Requiring the same line keeps a variable
/// actually named `new` that ends its line (`x = new;` written without the
/// `;` on the same line is not valid anyway) from swallowing the next
/// statement.
fn at_shallow_copy(&self) -> bool {
let cur = self.cur();
let next = self.nth(1);
cur.kind == TokenKind::Ident
&& cur.text == "new"
&& next.kind == TokenKind::Ident
&& !next.is_macro()
&& next.line == cur.line
}
fn parse_primary(&mut self) -> PResult<Expr> {
let start = self.here();
let t = self.cur();
match t.kind {
TokenKind::Number => {
// `` 32'h`DM_ADDR `` — a based number whose digits are a macro
// invocation (corpus
// `ibex/dv/uvm/core_ibex/tb/core_ibex_tb_top.sv:75`). The two
// tokens are one literal; joining their text here prints them
// back adjacent, which is the only spelling that re-lexes to
// the same pair.
if t.is_base_only_number() && self.nth(1).is_macro() {
let mut text = self.bump().text;
text.push_str(&self.bump().text);
return Ok(self.expr_at(start, ExprKind::Number(text)));
}
let text = self.bump().text;
Ok(self.expr_at(start, ExprKind::Number(text)))
}
TokenKind::String => {
let text = self.bump().text;
Ok(self.expr_at(start, ExprKind::Str(text)))
}
TokenKind::Ident | TokenKind::SystemIdent => {
if self.at_shallow_copy() {
self.bump(); // new
let src = self.parse_postfix()?;
return Ok(self.expr_at(start, ExprKind::New(Box::new(src))));
}
let text = self.bump().text;
Ok(self.expr_at(start, ExprKind::Ident(text)))
}
TokenKind::Keyword => {
let kw = t.text.clone();
// Type keyword casts: `int'(x)`, `signed'(y)`.
if (TYPE_KEYWORDS.contains(&kw.as_str())
|| kw == "signed"
|| kw == "unsigned"
|| kw == "const")
&& self.nth(1).is_sym("'")
&& self.nth(2).is_sym("(")
{
let ty_start = self.here();
let ty_text = self.bump().text;
let ty = self.expr_at(ty_start, ExprKind::Ident(ty_text));
self.bump(); // '
self.bump(); // (
let inner = self.parse_expr()?;
self.expect_sym(")")?;
return Ok(self.expr_at(
start,
ExprKind::Cast { ty: Box::new(ty), expr: Box::new(inner) },
));
}
// Type keyword used as an argument (e.g. `$bits(int)`).
if TYPE_KEYWORDS.contains(&kw.as_str()) {
return self.parse_type_expr();
}
self.error(format!("unexpected keyword `{kw}` in expression"))
}
TokenKind::Symbol => {
let sym = t.text.clone();
match sym.as_str() {
// A bare `$` — the upper bound of a queue (`q[$]`,
// `q[$-1]`, `int q[$]`). Kept an ordinary name, like
// `new`/`this`/`super`: one leaf makes every position
// work through the existing expression grammar, and lucisv
// checks legality nowhere else either.
"$" => {
self.bump();
Ok(self.expr_at(start, ExprKind::Ident("$".to_string())))
}
"(" => {
// Comments written just inside the parens stay there;
// anything else would move them across a token.
let mut before = self.take_trailing_here();
self.bump();
before.append(&mut self.take_leading_here());
let mark = self.pending_trailing.len();
let inner_start = self.here();
let inner = self.parse_expr()?;
let inner = if self.eat_sym(":") {
let typ = self.parse_expr()?;
self.expect_sym(":")?;
let max = self.parse_expr()?;
self.expr_at(
inner_start,
ExprKind::MinTypMax {
min: Box::new(inner),
typ: Box::new(typ),
max: Box::new(max),
},
)
} else {
inner
};
let after = self.take_around(mark);
self.expect_sym(")")?;
Ok(self.expr_at(
start,
ExprKind::Paren { inner: Box::new(inner), before, after },
))
}
"{" => {
self.bump();
if self.cur().is_sym("<<") || self.cur().is_sym(">>") {
return self.parse_stream_concat(start);
}
if self.cur().is_sym("}") {
// `{}` — the empty queue/dynamic-array literal
// (`q = {};`). Illegal as a Verilog concatenation,
// but lucisv is not a legality checker.
self.bump();
return Ok(self.expr_at(start, ExprKind::Concat(Vec::new())));
}
let first = self.parse_expr_item()?;
if self.cur().is_sym("{") {
// Replication {N{a, b}}
self.bump();
let inner_first = self.parse_expr_item()?;
let inner = self.parse_expr_list(inner_first, "}")?;
self.expect_sym("}")?;
self.expect_sym("}")?;
return Ok(self.expr_at(
start,
ExprKind::Repl { count: Box::new(first.expr), inner },
));
}
let items = self.parse_expr_list(first, "}")?;
self.expect_sym("}")?;
Ok(self.expr_at(start, ExprKind::Concat(items)))
}
"'{" => {
self.bump();
if self.at_assign_pattern_repl() {
return self.parse_assign_pattern_repl(start);
}
let mut items = Vec::new();
if !self.cur().is_sym("}") {
loop {
let item_start = self.here();
let mut meta = self.take_meta();
let key_or_val = if self.cur().is_kw("default") {
self.bump();
self.expr_at(item_start, ExprKind::Ident("default".to_string()))
} else {
self.parse_expr_or_type()?
};
let (key, value) = if self.eat_sym(":") {
(Some(key_or_val), self.parse_expr()?)
} else {
(None, key_or_val)
};
let item_span = self.span_from(item_start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
items.push(PatternItem { meta, key, value, span: item_span });
if !more {
break;
}
}
if let Some(last) = items.last_mut() {
self.take_before_sep(&mut last.meta, "}");
}
}
self.expect_sym("}")?;
Ok(self.expr_at(start, ExprKind::AssignPattern(items)))
}
_ => self.error("expected expression"),
}
}
_ => self.error("expected expression"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lexer::tokenize;
fn parse_ok(src: &str) -> SourceFile {
let toks = tokenize(src).expect("lex error");
match parse(toks, src) {
Ok(f) => f,
Err(e) => panic!("parse error in {src:?}: {e}"),
}
}
/// The texts of a comment slot, for the tests that pin where a comment
/// with no node of its own was attached.
fn texts(comments: &[Comment]) -> Vec<&str> {
comments.iter().map(|c| c.text.as_str()).collect()
}
/// The message of the parse error `src` must produce.
fn parse_err(src: &str) -> String {
let toks = tokenize(src).expect("lex error");
match parse(toks, src) {
Ok(_) => panic!("expected a parse error in {src:?}"),
Err(e) => e.message,
}
}
/// Parse on the stack every production parse site is given. Nesting all
/// the way to [`MAX_NESTING_DEPTH`] peaks around 5.9 MiB in an
/// unoptimized build, which is more than the 2 MiB a default test thread
/// gets — hence [`PARSE_STACK_SIZE`], and hence the fact that the tests
/// spell it rather than a number of their own: what they exercise is the
/// stack the shipped binaries actually run on.
fn parse_deep(src: String) -> PResult<SourceFile> {
std::thread::Builder::new()
.stack_size(PARSE_STACK_SIZE)
.spawn(move || parse(tokenize(&src).expect("lex error"), &src))
.expect("spawn parser thread")
.join()
.expect("parser thread crashed")
}
fn assert_too_deep(src: String) {
let err = parse_deep(src).expect_err("expected a nesting-depth error");
assert!(
err.message.contains(&format!("nesting too deep (limit {MAX_NESTING_DEPTH})")),
"unexpected error: {err}"
);
assert!(err.line > 0, "error carries a position: {err}");
}
fn assert_chain_too_long(src: String) {
let err = parse_deep(src).expect_err("expected a chain-length error");
assert!(
err.message.contains(&format!("expression chain too long (limit {MAX_CHAIN_LENGTH})")),
"unexpected error: {err}"
);
assert!(err.line > 0, "error carries a position: {err}");
}
/// `n` nested `begin` blocks in an `initial`, innermost one empty. The
/// module and the `initial` item each take one level, so the deepest
/// level reached is `n + 2`.
fn nested_begins(n: usize) -> String {
format!("module m;\ninitial\n{}{}\nendmodule\n", "begin\n".repeat(n), "end\n".repeat(n))
}
/// `assign x = a` followed by `n` copies of `segment`, e.g. `.b` — a
/// chain the parser builds in a loop, one AST layer per copy.
fn chain(segment: &str, n: usize) -> String {
format!("module m;\nassign x = a{};\nendmodule\n", segment.repeat(n))
}
#[test]
fn nesting_just_below_the_limit_parses() {
let src = nested_begins(MAX_NESTING_DEPTH as usize - 2);
parse_deep(src).expect("nesting at the limit must still parse");
}
#[test]
fn nesting_just_past_the_limit_is_a_parse_error() {
assert_too_deep(nested_begins(MAX_NESTING_DEPTH as usize - 1));
}
#[test]
fn deep_statement_nesting_errors() {
// The cli-polish QA repro: 150 levels of `if (clk) begin ... end`.
let n = 150;
assert_too_deep(format!(
"module m;\nalways @(posedge clk) begin\n{}x <= 1;\n{}end\nendmodule\n",
"if (clk) begin\n".repeat(n),
"end\n".repeat(n)
));
// `else if` chains recurse through the `else` branch.
assert_too_deep(format!(
"module m;\ninitial\n{}x <= 0;\nendmodule\n",
"if (c) x <= 1; else\n".repeat(300)
));
}
#[test]
fn deep_expression_nesting_errors() {
let d = 400;
// Parenthesized, concatenated, called, and `? :`-chained expressions
// all recurse through `parse_ternary`; stacked prefix operators
// recurse through `parse_unary`.
assert_too_deep(format!(
"module m;\nassign x = {}1{};\nendmodule\n",
"(".repeat(d),
")".repeat(d)
));
assert_too_deep(format!(
"module m;\nassign x = {}z{};\nendmodule\n",
"{a, ".repeat(d),
"}".repeat(d)
));
assert_too_deep(format!(
"module m;\nassign x = {}y{};\nendmodule\n",
"f(".repeat(d),
")".repeat(d)
));
assert_too_deep(format!("module m;\nassign x = {}z;\nendmodule\n", "a ? b : ".repeat(d)));
assert_too_deep(format!("module m;\nassign x = {}y;\nendmodule\n", "~".repeat(d)));
}
#[test]
fn deep_generate_nesting_errors() {
let d = 200;
assert_too_deep(format!(
"module m;\ngenerate\n{}wire w;\n{}endgenerate\nendmodule\n",
"if (1) begin\n".repeat(d),
"end\n".repeat(d)
));
assert_too_deep(format!(
"module m;\ngenerate\n{}wire w;\n{}endgenerate\nendmodule\n",
"for (i = 0; i < 2; i = i + 1) begin\n".repeat(d),
"end\n".repeat(d)
));
// Generate `else if` chains recurse without going through an item.
assert_too_deep(format!(
"module m;\ngenerate\n{}begin wire wz; end\nendgenerate\nendmodule\n",
"if (c) begin wire w; end else\n".repeat(d)
));
}
/// `n` copies of a block opener and its closer around one statement, in
/// an `initial` — the shape generated RTL nests.
fn nested_stmt_blocks(open: &str, close: &str, n: usize) -> String {
format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
open.repeat(n),
close.repeat(n)
)
}
#[test]
fn deep_nesting_errors_for_every_block_form() {
let d = 200;
// `fork`/`join` blocks are statements like `begin`/`end`.
assert_too_deep(nested_stmt_blocks("fork\n", "join\n", d));
// `case` carries the fattest frame in the grammar; the arm's own
// statement is a second gated level per source level.
assert_too_deep(nested_stmt_blocks("case (s)\n1: ", "endcase\n", d));
// Bodies that need no closer still recurse through the body
// statement.
assert_too_deep(nested_stmt_blocks("foreach (a[j])\n", "", d));
assert_too_deep(nested_stmt_blocks("while (c)\n", "", d));
assert_too_deep(nested_stmt_blocks("for (int i = 0; i < 4; i++)\n", "", d));
// Nested module declarations (IEEE 1800 §23.4) nest items, not
// statements, so they are gated by `parse_item`.
assert_too_deep(format!("{}wire w;\n{}", "module m;\n".repeat(d), "endmodule\n".repeat(d)));
}
#[test]
fn the_fattest_block_forms_still_parse_at_the_limit() {
// The stack these tests run on is `PARSE_STACK_SIZE`, so this is the
// load-bearing direction: the deepest *legal* input in the two most
// expensive families has to fit the stack every production parse site
// is given. `module` + `initial` + `begin` + the innermost statement
// and its expression cost six levels between them.
let n = MAX_NESTING_DEPTH as usize - 6;
parse_deep(nested_stmt_blocks("fork\n", "join\n", n)).expect("legal `fork` nesting");
parse_deep(nested_stmt_blocks("case (s)\n1: ", "endcase\n", n))
.expect("legal `case` nesting");
}
#[test]
fn chain_just_below_the_limit_parses() {
parse_deep(chain(".b", MAX_CHAIN_LENGTH as usize))
.expect("a chain at the limit must still parse");
}
#[test]
fn chain_just_past_the_limit_is_a_parse_error() {
assert_chain_too_long(chain(".b", MAX_CHAIN_LENGTH as usize + 1));
}
#[test]
fn long_chains_error() {
// These are built by loops, not by recursion, so they cost the parser
// no depth at all — but every segment is one more AST layer for the
// formatter to walk, which is what `MAX_CHAIN_LENGTH` bounds.
let n = MAX_CHAIN_LENGTH as usize + 1;
for segment in [".b", "::b", "[0]", "()", "++", " + a", " inside {1}"] {
assert_chain_too_long(chain(segment, n));
}
// Dimension expressions get their own (compact) formatter walk.
assert_chain_too_long(format!("module m;\nwire [a{}:0] w;\nendmodule\n", "+a".repeat(n)));
}
#[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));
assert_chain_too_long(format!(
"module m;\nassign x = {}z{};\nendmodule\n",
level.repeat(7),
")".repeat(7)
));
}
/// One of everything that opens a gated level or adds a chain link:
/// `parse_item`, `parse_stmt`, `parse_ternary`, `parse_unary`,
/// `parse_gen_if`, postfix segments and operator chains.
fn all_gates_unit() -> String {
"initial begin\n if (c) x <= (a ? b : ~c) + d.e[f] + g.h.i;\nend\n\
generate\n if (c) begin wire w; end else if (d) begin wire v; end\nendgenerate\n"
.to_string()
}
#[test]
fn depth_and_links_are_released_on_the_way_out() {
// Every gate and both chain sites run several times per unit, so a
// single missing release anywhere makes the counters creep up until a
// limit trips part-way through the 200 siblings.
parse_deep(format!("module m;\n{}endmodule\n", all_gates_unit().repeat(200)))
.expect("sibling constructs must not accumulate depth or links");
// 200 sibling blocks, each nested 40 deep.
let one = format!("initial\n{}{}\n", "begin\n".repeat(40), "end\n".repeat(40));
parse_deep(format!("module m;\n{}endmodule\n", one.repeat(200)))
.expect("sibling nesting must not accumulate depth");
// 200 sibling chains, each half the link budget long.
let half = format!("assign y = a{};\n", ".b".repeat(MAX_CHAIN_LENGTH as usize / 2));
parse_deep(format!("module m;\n{}endmodule\n", half.repeat(200)))
.expect("sibling chains must not accumulate links");
// Two chains inside *one* expression are siblings too, not a path:
// 200 links each is legal, 400 on one path would not be.
let n = 200;
parse_deep(format!(
"module m;\nassign x = a{} + c{};\nendmodule\n",
".b".repeat(n),
".d".repeat(n)
))
.expect("sibling chains in one expression must not accumulate links");
}
#[test]
fn simple_module() {
let f = parse_ok("module m(input clk, output reg [7:0] q); endmodule");
assert_eq!(f.items.len(), 1);
}
#[test]
fn module_with_params_and_body() {
parse_ok(
"module counter #(parameter WIDTH = 8) (
input wire clk, input wire rst_n,
output logic [WIDTH-1:0] count);
always_ff @(posedge clk or negedge rst_n) begin
if (!rst_n) count <= '0;
else count <= count + 1'b1;
end
endmodule : counter",
);
}
#[test]
fn instantiation_forms() {
parse_ok(
"module top;
sub #(.W(8), .D(16)) u_sub (.clk(clk), .out(out), .unused());
sub2 u2 (a, b, c);
and g1 (o, a, b);
mem #(8) banks [3:0] (.*);
endmodule",
);
}
#[test]
fn bind_directive_forms() {
parse_ok(
"module top;
bind target_mod checker u_chk (.a(x), .b(y));
bind i_inst checker #(.W(8)) u_chk2 (.*);
bind top.u_dut.u_core checker u_chk3 (.clk_i, .rst_ni);
bind fifo_v3 : i_a, i_b fifo_props u_props (.*);
endmodule",
);
// Also at top level and inside a generate block.
parse_ok("bind cpu cpu_assert u_a (.*);\n");
parse_ok(
"module m;
generate if (E) begin : g
bind sub checker u (.*);
end endgenerate
endmodule",
);
}
#[test]
fn a_bind_directive_wraps_an_ordinary_instantiation() {
let file =
parse_ok("module m;\n bind top.u_dut : u_a, u_b chk #(.W(8)) u (.a(x));\nendmodule\n");
let m = module_of(&file);
let ItemKind::Bind(b) = &m.items[0].kind else { panic!("expected a bind directive") };
assert_eq!(b.target, "top.u_dut");
assert_eq!(b.instances.iter().map(|n| n.text.as_str()).collect::<Vec<_>>(), ["u_a", "u_b"]);
assert_eq!(b.inst.module, "chk");
assert_eq!(b.inst.params.as_ref().map(Vec::len), Some(1));
assert_eq!(b.inst.instances[0].name, "u");
}
#[test]
fn the_comments_around_a_binds_head_are_kept() {
// QA round-1: the target is a bare string, so these two positions had
// no node to attach to and the comments drifted onto the instance.
let file = parse_ok("module m;\n bind /*c1*/ dut /*c2*/ chk u (.*);\nendmodule\n");
let ItemKind::Bind(b) = &module_of(&file).items[0].kind else {
panic!("expected a bind directive")
};
assert_eq!(texts(&b.target_comments), ["/*c1*/"]);
assert_eq!(texts(&b.module_comments), ["/*c2*/"]);
}
#[test]
fn bind_is_still_a_usable_identifier() {
// `bind` is not in the lexer's keyword table, so a method called
// `bind` — and a variable declared with a type of that name — keep
// parsing exactly as they did before the directive was supported.
parse_ok(
"module m;\n initial begin\n obj.bind();\n x = obj.bind;\n end\nendmodule\n",
);
parse_ok("module m;\n bind x;\n bind y = 1;\nendmodule\n");
}
#[test]
fn expressions() {
parse_ok(
"module e;
assign x = a ? {b, c[3:0], {4{d}}} : (e + f) * g;
assign y = data[base +: 8] | pkg::CONST;
assign z = int'(w) + 8'hFF + $clog2(DEPTH);
endmodule",
);
}
#[test]
fn generate_and_case() {
parse_ok(
"module g #(parameter N = 4)();
genvar i;
generate
for (i = 0; i < N; i = i + 1) begin : lane
sub u (.x(x[i]));
end
endgenerate
always_comb begin
case (sel)
2'b00: y = a;
2'b01, 2'b10: y = b;
default: y = '0;
endcase
end
endmodule",
);
}
#[test]
fn typedefs() {
parse_ok(
"typedef enum logic [1:0] {IDLE, RUN = 2, DONE} state_t;
typedef struct packed { logic [7:0] addr; logic valid; } req_t;
typedef logic [31:0] word_t;",
);
}
#[test]
fn functions_tasks() {
parse_ok(
"module f;
function automatic logic [7:0] add1(input logic [7:0] x);
return x + 1;
endfunction
task do_thing(input int n);
repeat (n) @(posedge clk);
endtask
endmodule",
);
}
#[test]
fn macro_items_and_statements() {
let file = parse_ok(
"`GLOBAL_MACRO(a, b)
package p;
`DEFINE_REGS(foo)
endpackage
module m;
`ASSERT_INIT(Check_A, N > 0)
`FFARNC(q, d, en, '0, clk_i, rst_ni);
`BARE
`BARE_SEMI;
generate
for (genvar i = 0; i < N; i++) begin : g
`FF(q[i], d[i], '0, clk_i, rst_ni)
end
endgenerate
always_ff @(posedge clk_i) begin
`DV_CHECK(a_i)
`uvm_info(\"id\", \"m\", UVM_LOW);
q <= d;
end
function automatic int f();
`TRACE_ENTER(f)
return 0;
endfunction
endmodule",
);
assert!(matches!(file.items[0].kind, ItemKind::MacroItem(_)));
}
/// The one-token lookahead in `at_macro_item` must not steal a macro that
/// names a type, a module or the target of an assignment.
#[test]
fn macro_lookahead_leaves_declarations_alone() {
let file = parse_ok(
"module m;
`MY_TYPE_T sig;
`MY_TYPE_T [3:0] vec;
`MY_MODULE u_inst (.a(sig));
`MY_MODULE #(.W(8)) u_param (.a(sig));
initial `LVALUE(x) = 1;
assign y = `PACK(a, b);
endmodule",
);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
assert!(
!m.items.iter().any(|i| matches!(i.kind, ItemKind::MacroItem(_))),
"no item should have been read as a standalone macro invocation"
);
}
/// `` `uvm_field_int (a, b) `` — the lexer only glues a `(` that touches
/// the macro name, so the argument list arrives as separate tokens and the
/// parser has to rebuild the invocation from the source bytes.
#[test]
fn a_space_before_the_argument_list_is_still_a_macro_item() {
let file = parse_ok(
"class c;\n `uvm_object_utils_begin(c)\n `uvm_field_int (a, UVM_DEFAULT)\n `uvm_object_utils_end\nendclass",
);
let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") };
let texts: Vec<&str> = c
.items
.iter()
.map(|i| match &i.kind {
ItemKind::MacroItem(call) => call.raw.text.as_str(),
other => panic!("expected a macro item, got {other:?}"),
})
.collect();
assert_eq!(
texts,
[
"`uvm_object_utils_begin(c)",
"`uvm_field_int (a, UVM_DEFAULT)",
"`uvm_object_utils_end",
],
"the space and the argument text are reproduced byte-for-byte"
);
}
/// The spaced reading is offered at item and statement position only. In
/// an expression `` `A (b) `` may be `` `A `` applied to `(b)`, which
/// depends on a `` `define`` lucisv never sees.
#[test]
fn a_spaced_macro_in_expression_position_is_still_a_call() {
let file = parse_ok("module m;\nassign x = `A (b);\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
assert!(
matches!(a.assigns[0].rhs.kind, ExprKind::Call { .. }),
"expression position must keep its old parse: {:?}",
a.assigns[0].rhs.kind
);
}
/// A `(` that opens the *next* line is not the macro's argument list.
#[test]
fn a_paren_on_the_next_line_does_not_join_the_macro() {
let file = parse_ok("module m;\n`BARE\ninitial x = (a);\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::MacroItem(call) = &m.items[0].kind else { panic!("expected a macro item") };
assert_eq!(call.raw.text, "`BARE");
assert!(matches!(m.items[1].kind, ItemKind::Initial(_)));
}
/// A macro that ends its line is complete; the declaration below it is its
/// own item, not the declarator of a macro-named type.
#[test]
fn a_bare_macro_ending_its_line_does_not_type_the_next_declaration() {
let file = parse_ok(
"class c;\n `uvm_component_new\n\n uvm_report_server rs;\n `MY_TYPE_T sig;\nendclass",
);
let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") };
assert!(matches!(c.items[0].kind, ItemKind::MacroItem(_)));
assert!(matches!(c.items[1].kind, ItemKind::DataDecl(_)));
// Same line ⇒ still a declaration with a macro-named type.
assert!(matches!(c.items[2].kind, ItemKind::DataDecl(_)));
}
/// A macro statement that ends its line is complete whatever *kind* of
/// token opens the next line — a symbol as much as an identifier
/// (`corpus/ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv:160`).
#[test]
fn a_symbol_on_the_next_line_does_not_continue_a_macro_statement() {
let file = parse_ok(
"class c;\n\
task t;\n\
`uvm_info(`gfn, \"waiting\", UVM_MEDIUM)\n\
@(negedge rst_n);\n\
`DV_WAIT\n\
#10ns;\n\
`SEND\n\
-> ev;\n\
`PRE\n\
{a, b} = c;\n\
endtask\n\
endclass",
);
let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") };
let ItemKind::Task(t) = &c.items[0].kind else { panic!("expected a task") };
let macros = t.stmts.iter().filter(|s| matches!(s.kind, StmtKind::MacroStmt(_))).count();
assert_eq!(macros, 4, "each macro stands alone: {:?}", t.stmts);
assert_eq!(t.stmts.len(), 8, "and each next line opens its own statement");
}
/// The same rule must not fire on the macro's *own* line, and a macro
/// whose argument list spans lines owns every line it covers.
#[test]
fn a_symbol_on_the_macros_own_line_still_continues_it() {
let file = parse_ok(
"module m;\n\
`MY_TYPE_T [3:0] vec;\n\
`PACKED(a,\n\
b) [7:0] wide;\n\
endmodule",
);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
assert!(
!m.items.iter().any(|i| matches!(i.kind, ItemKind::MacroItem(_))),
"both lines declare: {:?}",
m.items
);
}
/// `instr_h = new instr_template[name];` — IEEE 1800 §8.12 shallow copy
/// (corpus `ibex/vendor/google_riscv-dv/src/isa/riscv_instr.sv:238`).
#[test]
fn new_followed_by_a_name_is_a_shallow_copy() {
let file = parse_ok(
"class c;\n\
function void f();\n\
instr_h = new instr_template[name];\n\
endfunction\n\
endclass",
);
let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") };
let ItemKind::Function(f) = &c.items[0].kind else { panic!("expected a function") };
let StmtKind::Assign { rhs, .. } = &f.stmts[0].kind else { panic!("expected an assign") };
let ExprKind::New(src) = &rhs.kind else {
panic!("expected a shallow copy: {:?}", rhs.kind)
};
assert!(matches!(src.kind, ExprKind::Index { .. }), "got {:?}", src.kind);
}
/// The constructor, the bare handle and the dynamic-array resize are all
/// followed by a symbol, so they keep parsing as they always did.
#[test]
fn the_other_spellings_of_new_keep_their_old_parse() {
let file = parse_ok(
"class c;\n\
function void f();\n\
a = new;\n\
b = new(x, y);\n\
d = new[n];\n\
new = 1;\n\
endfunction\n\
endclass",
);
let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") };
let ItemKind::Function(f) = &c.items[0].kind else { panic!("expected a function") };
let rhs_kinds: Vec<&ExprKind> = f
.stmts
.iter()
.map(|s| {
let StmtKind::Assign { rhs, .. } = &s.kind else { panic!("expected an assign") };
&rhs.kind
})
.collect();
assert!(matches!(rhs_kinds[0], ExprKind::Ident(n) if n == "new"));
assert!(matches!(rhs_kinds[1], ExprKind::Call { .. }));
assert!(matches!(rhs_kinds[2], ExprKind::Index { .. }));
// `new` used as an ordinary variable name is still an ordinary name.
assert!(matches!(rhs_kinds[3], ExprKind::Number(_)));
}
/// `` 32'h`DM_ADDR `` — the lexer stops the number at the base, and the
/// parser joins the pair back into one literal.
#[test]
fn a_macro_digit_number_is_one_primary_expression() {
let file = parse_ok("module m;\nlocalparam int A = 32'h`DM_ADDR;\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::ParamDecl(p) = &m.items[0].kind else { panic!("expected a localparam") };
let init = p.declarators[0].init.as_ref().expect("a value");
assert!(
matches!(&init.kind, ExprKind::Number(n) if n == "32'h`DM_ADDR"),
"got {:?}",
init.kind
);
}
/// A base with no digits and no macro after it stays an error: the macro
/// must be the very next token.
#[test]
fn a_base_only_number_without_a_macro_is_a_parse_error() {
let src = "module m;\nlocalparam int A = 32'h`ifdef;\nendmodule";
let toks = tokenize(src).expect("lex error");
assert!(parse(toks, src).is_err(), "a directive is not the number's digits");
}
#[test]
fn elaboration_tasks_stand_where_items_do() {
let file = parse_ok(
"module m;\n\
$error(\"a\", \"b\");\n\
$fatal(1, \"c\");\n\
$warning(\"d\");\n\
$info(\"e\");\n\
if (W < 1) $error(\"f\");\n\
endmodule",
);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
for item in &m.items[..4] {
assert!(matches!(item.kind, ItemKind::ElabTask(_)), "got {:?}", item.kind);
}
let ItemKind::GenIf(g) = &m.items[4].kind else { panic!("expected a generate if") };
assert!(matches!(g.then.items[0].kind, ItemKind::ElabTask(_)));
}
/// The list is closed: `$display` is only legal inside a procedural block,
/// and accepting it as an item would swallow a real error.
#[test]
fn a_non_elaboration_system_task_is_not_an_item() {
let src = "module m;\n$display(\"x\");\nendmodule";
let err = parse(tokenize(src).expect("lex error"), src).expect_err("strict must refuse");
assert!(err.message.contains("expected item"), "unexpected: {err}");
}
#[test]
fn macro_semicolon_is_reproduced_not_invented() {
let file = parse_ok("module m;\n`A(x)\n`B(y);\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let semis: Vec<bool> = m
.items
.iter()
.map(|i| match &i.kind {
ItemKind::MacroItem(call) => call.semi,
other => panic!("expected a macro item, got {other:?}"),
})
.collect();
assert_eq!(semis, [false, true]);
}
#[test]
fn event_list_separators_are_recorded_as_written() {
let file =
parse_ok("module m;\nalways @(posedge clk, negedge rst_n or a, b) q <= d;\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::Always { stmt, .. } = &m.items[0].kind else { panic!("expected an always") };
let StmtKind::Timing { control: TimingControl::Event(SensList::List(items)), .. } =
&stmt.kind
else {
panic!("expected an event control")
};
let seps: Vec<Option<SensSep>> = items.iter().map(|i| i.sep).collect();
assert_eq!(
seps,
[None, Some(SensSep::Comma), Some(SensSep::Or), Some(SensSep::Comma)],
"each separator must be kept as written"
);
}
#[test]
fn header_imports_stay_separate_statements() {
let file =
parse_ok("module m\n import a::*;\n import b::t, c::u;\n(input clk);\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let paths: Vec<Vec<String>> =
m.imports.iter().map(|i| i.paths.iter().map(ImportPath::text).collect()).collect();
assert_eq!(paths, vec![vec!["a::*".to_string()], vec!["b::t".into(), "c::u".into()]]);
}
#[test]
fn a_written_empty_parameter_list_is_distinguishable_from_none() {
let file = parse_ok("module m;\n sub #() u0 (.a(x));\n sub u1 (.a(x));\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let params: Vec<bool> = m
.items
.iter()
.map(|i| match &i.kind {
ItemKind::Instantiation(inst) => inst.params.is_some(),
other => panic!("expected an instantiation, got {other:?}"),
})
.collect();
assert_eq!(params, [true, false], "`#()` is Some(empty), no `#(...)` is None");
}
#[test]
fn comments_before_a_closing_paren_stay_with_their_list() {
let file = parse_ok(
"module m #(\n parameter int W = 8\n /* lint_on */\n) (\n input a\n // tail\n);\nendmodule",
);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
assert_eq!(m.param_dangling.len(), 1, "the pragma belongs inside `#( ... )`");
assert_eq!(m.port_dangling.len(), 1, "the comment belongs inside the port list");
}
#[test]
fn comments_around_a_ternary_are_kept_per_position() {
let file =
parse_ok("module m;\nassign y = c /* a */ ? /* b */ x /* c */ : /* d */ z;\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
let ExprKind::Ternary { comments, .. } = &a.assigns[0].rhs.kind else {
panic!("expected a ternary")
};
assert_eq!(comments.before_question.len(), 1);
assert_eq!(comments.after_question.len(), 1);
assert_eq!(comments.before_colon.len(), 1);
assert_eq!(comments.after_colon.len(), 1);
}
#[test]
fn comments_on_both_sides_of_a_binary_operator_are_kept_apart() {
let file = parse_ok("module m;\nassign y = a /* pre */ && /* post */ b;\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
let ExprKind::Binary { comments, .. } = &a.assigns[0].rhs.kind else {
panic!("expected a binary expression")
};
assert_eq!(comments.before.len(), 1, "one comment before the operator");
assert_eq!(comments.after.len(), 1, "one comment after the operator");
}
#[test]
fn a_comment_before_a_list_comma_lands_in_before_sep() {
let file = parse_ok("module m (input a /* pre */, /* post */ input b);\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let PortList::Ansi(ports) = &m.ports else { panic!("expected an ANSI port list") };
assert_eq!(ports[0].meta.before_sep.len(), 1, "written before the comma");
assert_eq!(ports[0].meta.before_sep[0].text, "/* pre */");
let trailing = ports[0].meta.trailing.as_ref().expect("written after the comma");
assert_eq!(trailing.text, "/* post */");
}
#[test]
fn a_comment_after_the_last_element_is_not_a_before_sep_comment() {
// No separator follows, so the comment stays where it always was —
// this is the case the whole existing suite pins, and the harvest must
// not start stealing it.
let file = parse_ok("module m (input a /* tail */);\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let PortList::Ansi(ports) = &m.ports else { panic!("expected an ANSI port list") };
assert!(ports[0].meta.before_sep.is_empty(), "nothing separates it from the `)`");
assert_eq!(ports[0].meta.trailing.as_ref().expect("a trailing comment").text, "/* tail */");
}
#[test]
fn a_trailing_comment_carries_its_own_span() {
// The handshake `docs/features/format-fences/README.md` asked for: a
// same-line comment now has a byte offset, so a fence written there
// can be located in the source.
let src = "module m;\n wire a; // lucisv: off\nendmodule\n";
let file = parse_ok(src);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let trailing = m.items[0].meta.trailing.as_ref().expect("a trailing comment");
assert_eq!(
&src[trailing.span.start as usize..trailing.span.end as usize],
"// lucisv: off"
);
assert_eq!((trailing.line, trailing.col), (2, 11));
}
#[test]
fn several_trailing_comments_merge_into_one_spanning_run() {
let src = "module m;\n wire a; /* one */ /* two */\nendmodule\n";
let file = parse_ok(src);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let trailing = m.items[0].meta.trailing.as_ref().expect("a trailing comment");
assert_eq!(trailing.text, "/* one */ /* two */");
assert_eq!(
&src[trailing.span.start as usize..trailing.span.end as usize],
"/* one */ /* two */",
"the span runs from the first comment to the last"
);
}
#[test]
fn comments_before_a_headers_brackets_land_on_the_module() {
let src = "module m\n// params\n#(parameter int P = 1)\n// ports\n(input a);\nendmodule\n";
let file = parse_ok(src);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
assert_eq!(m.param_comments.len(), 1);
assert_eq!(m.param_comments[0].text, "// params");
assert_eq!(m.port_comments.len(), 1);
assert_eq!(m.port_comments[0].text, "// ports");
let params = m.param_ports.as_ref().expect("a parameter port list");
assert!(params[0].meta.leading.is_empty(), "not the first parameter's leading comment");
}
#[test]
fn a_header_without_brackets_keeps_its_comment_for_the_next_construct() {
// `take_before_open` is a no-op unless the bracket is actually there,
// so a module that writes neither `#(` nor `(` must not steal the
// comment that belongs to its first item.
let src = "module m;\n// the data bus\nwire x;\nendmodule\n";
let file = parse_ok(src);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
assert!(m.param_comments.is_empty());
assert!(m.port_comments.is_empty());
assert_eq!(m.items[0].meta.leading[0].text, "// the data bus");
}
#[test]
fn comments_before_an_instantiations_brackets_land_on_it() {
let src = "module m;\nsub\n// params\n#(.W(8)) u\n// conns\n(.a(b));\nendmodule\n";
let file = parse_ok(src);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
panic!("expected an instantiation")
};
assert_eq!(inst.param_comments.len(), 1);
assert_eq!(inst.param_comments[0].text, "// params");
assert_eq!(inst.instances[0].conn_comments.len(), 1);
assert_eq!(inst.instances[0].conn_comments[0].text, "// conns");
}
#[test]
fn an_attribute_and_the_comments_around_it_keep_their_source_order() {
// The formatter merges the two lists by span, so both must carry
// offsets that put the attribute between the comments.
let src = "// before\n(* keep *)\n// after\nmodule m;\nendmodule\n";
let file = parse_ok(src);
let meta = &file.items[0].meta;
assert_eq!(meta.attrs.len(), 1);
assert_eq!(meta.leading.len(), 2);
assert!(meta.leading[0].span.start < meta.attrs[0].span.start);
assert!(meta.attrs[0].span.start < meta.leading[1].span.start);
}
// ------------------------------------------------------------------
// Error recovery
// ------------------------------------------------------------------
/// White-box version of the handshake in
/// `docs/features/recursion-limit/README.md`: recovery neither leaks nor
/// resets the two budgets, so both counters are back at zero once a file
/// full of recovered errors has been parsed.
#[test]
fn both_budgets_are_balanced_after_recovering() {
let src = "module m;\n wire a\n assign x = ((1 +;\n initial begin\n y = ;\n end\n bad ) ) ;\nendmodule\n@#!\nmodule n;\n wire b\nendmodule\n";
let mut p = Parser::new(tokenize(src).expect("lex error"), src, true);
p.parse_source_file().expect("tolerant parsing never fails");
assert!(!p.diagnostics.is_empty(), "the source is broken on purpose");
assert_eq!(p.depth, 0, "nesting budget left open after recovery");
assert_eq!(p.links, 0, "chain budget left open after recovery");
}
fn module_of(file: &SourceFile) -> &Module {
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
m
}
#[test]
fn a_directive_between_ports_records_its_place_and_the_commas_around_it() {
let src =
"module m (\n input a,\n`ifdef X\n input b,\n`endif\n input c\n);\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
assert_eq!(ports.len(), 3);
assert_eq!(
ports.iter().map(|p| p.comma).collect::<Vec<_>>(),
vec![true, true, false],
"the commas the source wrote, not the ones the positions imply"
);
let d = &m.port_directives;
assert_eq!(d.len(), 2);
assert_eq!(d[0].raw.text, "`ifdef X");
assert_eq!(d[0].before, 1, "written before the second port");
assert_eq!(d[1].raw.text, "`endif");
assert_eq!(d[1].before, 2, "written before the third port");
assert!(d.iter().all(|d| !d.comma), "no comma follows either directive");
}
#[test]
fn a_comma_written_after_a_directive_belongs_to_the_directive() {
// The shape `prim_sparse_fsm_flop.sv` writes: the comma lives inside
// the `ifdef arm so that both arms are legal. Deriving the comma from
// the element's position would move it across the directive.
let src = "module m #(\n parameter int A = 1\n`ifdef S\n ,\n parameter int B = 2\n`endif\n) ();\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
let params = m.param_ports.as_ref().expect("a parameter port list");
assert_eq!(params.len(), 2);
assert!(!params[0].comma, "the first parameter wrote no comma of its own");
assert!(!params[1].comma);
assert_eq!(m.param_directives.len(), 2);
assert!(m.param_directives[0].comma, "`ifdef carries the comma");
assert!(!m.param_directives[1].comma);
}
#[test]
fn a_list_with_no_directive_keeps_an_empty_directive_vector() {
// The harvest is a no-op unless a directive is actually there, which
// is what keeps every pre-existing list byte-for-byte unchanged.
let src = "module m #(parameter int P = 1) (input a, input b);\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
assert!(m.param_directives.is_empty());
assert!(m.port_directives.is_empty());
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
assert_eq!(ports.iter().map(|p| p.comma).collect::<Vec<_>>(), vec![true, false]);
}
// ------------------------------------------------------------------
// A direction-less first ANSI port (IEEE 1800 §23.2.2.2)
// `docs/features/ansi-first-port/README.md`
// ------------------------------------------------------------------
/// The `(dir, type, name)` of every port of an ANSI header.
fn ansi_ports(src: &str) -> Vec<(String, String, String)> {
let file = parse_ok(src);
let m = module_of(&file);
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports in {src:?}") };
ports
.iter()
.map(|p| (p.dir.clone().unwrap_or_default(), p.ty.name.clone(), p.name.clone()))
.collect()
}
fn cell(dir: &str, ty: &str, name: &str) -> (String, String, String) {
(dir.to_string(), ty.to_string(), name.to_string())
}
#[test]
fn an_interface_typed_first_port_needs_no_direction() {
assert_eq!(
ansi_ports("module m (bus_if bus, input logic clk);\nendmodule\n"),
[cell("", "bus_if", "bus"), cell("input", "logic", "clk")]
);
assert_eq!(
ansi_ports("module m (bus_if bus);\nendmodule\n"),
[cell("", "bus_if", "bus")],
"alone in the list"
);
assert_eq!(
ansi_ports("interface i (bus_if bus);\nendinterface\n"),
[cell("", "bus_if", "bus")],
"an interface header is the same node and the same list"
);
}
#[test]
fn a_modport_qualified_port_keeps_the_modport_in_its_type() {
// IEEE 1800 §25.4. The modport is glued onto the interface name, the
// way a `pkg::` qualifier already is, so nothing downstream needs a
// second field to print or scan.
assert_eq!(
ansi_ports("module m (bus_if.mp bus);\nendmodule\n"),
[cell("", "bus_if.mp", "bus")]
);
assert_eq!(
ansi_ports("module m (input logic clk, bus_if.mp bus);\nendmodule\n"),
[cell("input", "logic", "clk"), cell("", "bus_if.mp", "bus")],
"later in the list too, which never parsed either"
);
}
#[test]
fn a_package_scoped_first_port_is_a_type_and_a_name() {
assert_eq!(
ansi_ports("module m (my_pkg::state_t s);\nendmodule\n"),
[cell("", "my_pkg::state_t", "s")]
);
assert_eq!(
ansi_ports("module m (my_pkg::state_t s, output logic q);\nendmodule\n"),
[cell("", "my_pkg::state_t", "s"), cell("output", "logic", "q")]
);
}
#[test]
fn a_direction_less_first_port_mixes_with_directed_ones_in_both_orders() {
assert_eq!(
ansi_ports("module m (state_t s, input a, output logic q);\nendmodule\n"),
[cell("", "state_t", "s"), cell("input", "", "a"), cell("output", "logic", "q")]
);
assert_eq!(
ansi_ports("module m (input a, state_t s);\nendmodule\n"),
[cell("input", "", "a"), cell("", "state_t", "s")],
"the ordering that always parsed is unchanged"
);
}
#[test]
fn a_typed_first_port_carries_its_dimensions_like_any_other() {
assert_eq!(
ansi_ports("module m (word_t [3:0] d, input a);\nendmodule\n"),
[cell("", "word_t", "d"), cell("input", "", "a")],
"packed dimensions sit between the type and the name"
);
assert_eq!(
ansi_ports("module m (item #(A, B) req);\nendmodule\n"),
[cell("", "item", "req")],
"a parameterized type, whose `#( ... )` is kept in the type"
);
}
#[test]
fn a_name_only_port_list_is_still_non_ansi() {
// The disambiguation must not eat the non-ANSI list: what follows the
// first identifier is a `,` or a `)`, not a second name.
let file = parse_ok("module m (a, b, c);\ninput a;\ninput b;\noutput c;\nendmodule\n");
let m = module_of(&file);
let PortList::NonAnsi(ports) = &m.ports else { panic!("expected a non-ANSI port list") };
assert_eq!(ports.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), vec!["a", "b", "c"]);
assert_eq!(ports.iter().map(|p| p.comma).collect::<Vec<_>>(), vec![true, true, false]);
let file = parse_ok("module m (a);\ninput a;\nendmodule\n");
let PortList::NonAnsi(ports) = &module_of(&file).ports else { panic!("non-ANSI") };
assert_eq!(ports.len(), 1, "a one-name list has no comma to look past either");
}
#[test]
fn the_other_port_list_spellings_are_untouched() {
let file = parse_ok("module m ();\nendmodule\n");
assert!(matches!(module_of(&file).ports, PortList::Empty), "empty parens");
let file = parse_ok("module m;\nendmodule\n");
assert!(matches!(module_of(&file).ports, PortList::None), "no list at all");
assert_eq!(
ansi_ports("module m (input a, b);\nendmodule\n"),
[cell("input", "", "a"), cell("", "", "b")],
"a continuation port still inherits its direction from the one before"
);
}
#[test]
fn what_is_not_a_bare_identifier_classifies_exactly_as_it_did() {
// The clause only fires on a `TokenKind::Ident`, so a macro-produced
// list (a `Directive` token) and an escaped name are read the way
// they always were, and a comment between the name and its comma is
// trivia that the lookahead never sees.
for src in [
"module m (`PORT_LIST);\nendmodule\n",
"module m (\\esc_name , b);\nendmodule\n",
"module m (a /* why */, b);\nendmodule\n",
] {
let file = parse_ok(src);
assert!(
matches!(module_of(&file).ports, PortList::NonAnsi(_)),
"still a non-ANSI list: {src:?}"
);
}
}
#[test]
fn a_broken_header_still_reports_its_own_token() {
// Recovery is unchanged: neither new shape swallows a genuinely
// broken list, and the diagnostic still names what blocked it.
assert!(parse_err("module m (bus_if bus;\nendmodule\n").contains("expected `)`"));
assert!(parse_err("module m (a[3], b);\nendmodule\n").contains("expected `)`"));
let (file, diags) = crate::parse_source_tolerant("module m (bus_if bus\nendmodule\n");
assert!(!diags.is_empty(), "a header that never closes is still an error");
assert!(!file.items.is_empty(), "and the file is still addressable");
}
#[test]
fn the_two_shapes_left_open_by_ansi_first_port_still_refuse() {
// Pinned so a future round that changes either does it on purpose
// (docs/features/ansi-first-port/README.md, Status): the generic
// `interface` port is a different production wanting a "any
// interface" DataType, and a modport-qualified *declaration* type
// would change how a `.` after an identifier reads everywhere.
assert!(parse_err("module m (interface bus);\nendmodule\n").contains("expected"));
assert!(parse_err("module m;\n virtual bus_if.mp v;\nendmodule\n").contains("expected"));
}
#[test]
fn both_arms_of_an_else_are_ordinary_elements_of_one_list() {
// lucisv does not evaluate the condition: an `ifdef/`else pair simply
// contributes every element of both arms, in source order.
let src = "module m (\n`ifdef X\n input a\n`else\n input b\n`endif\n);\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
assert_eq!(ports.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), vec!["a", "b"]);
assert!(ports.iter().all(|p| !p.comma), "neither arm's port wrote a comma");
assert_eq!(m.port_directives.len(), 3);
}
#[test]
fn a_directive_between_enum_members_lands_on_the_enum() {
let src = "typedef enum logic {\n A,\n`include \"more.svh\"\n B\n} e_t;\n";
let file = parse_ok(src);
let ItemKind::Typedef(t) = &file.items[0].kind else { panic!("expected a typedef") };
let TypedefKind::Enum(e) = &t.kind else { panic!("expected an enum") };
assert_eq!(e.members.len(), 2);
assert_eq!(e.directives.len(), 1);
assert_eq!(e.directives[0].raw.text, "`include \"more.svh\"");
assert_eq!(e.directives[0].before, 1);
}
#[test]
fn a_comment_before_a_list_directive_stays_with_the_directive() {
let src = "module m (\n input a,\n // only when X\n`ifdef X // why\n input b\n`endif\n);\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
let d = &m.port_directives[0];
assert_eq!(d.meta.leading.len(), 1);
assert_eq!(d.meta.leading[0].text, "// only when X");
assert_eq!(d.meta.trailing.as_ref().expect("a trailing comment").text, "// why");
}
#[test]
fn a_directive_inside_an_element_is_still_a_parse_error() {
// A directive runs to end of line, so it can only stand *between*
// elements. One written mid-declaration is out of scope by design;
// this pins that it is refused rather than half-parsed.
let src = "module m (\n input\n`ifdef X\n logic\n`endif\n a\n);\nendmodule\n";
assert!(parse(tokenize(src).expect("lex error"), src).is_err());
}
fn instantiation_of(file: &SourceFile) -> &Instantiation {
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::Instantiation(i) = &m.items[0].kind else {
panic!("expected an instantiation")
};
i
}
#[test]
fn a_directive_between_connections_records_its_place_and_the_commas() {
let src =
"module m;\n sub u (\n .a(x),\n`ifdef X\n .b(y),\n`endif\n .c(z)\n );\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
assert_eq!(conns.len(), 3);
assert_eq!(
conns.iter().map(|c| c.comma).collect::<Vec<_>>(),
vec![true, true, false],
"the commas the source wrote, not the ones the positions imply"
);
let d = &inst.instances[0].conn_directives;
assert_eq!(d.len(), 2);
assert_eq!(d[0].raw.text, "`ifdef X");
assert_eq!(d[0].before, 1, "written before the second connection");
assert_eq!(d[1].raw.text, "`endif");
assert_eq!(d[1].before, 2);
assert!(d.iter().all(|d| !d.comma));
assert!(inst.param_directives.is_empty(), "the override list holds none");
}
#[test]
fn a_directive_between_parameter_overrides_lands_on_the_instantiation() {
// The `picorv32/testbench.v` shape: nested `ifdef, the outer one
// wrapping the whole override list.
let src = "module m;\n sub #(\n`ifndef S\n`ifdef T\n .P(0),\n`endif\n .Q(1)\n`endif\n ) u (.a(x));\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let params = inst.params.as_ref().expect("an override list");
assert_eq!(params.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), vec!["P", "Q"]);
assert_eq!(params.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, false]);
let d = &inst.param_directives;
assert_eq!(d.iter().map(|d| d.before).collect::<Vec<_>>(), vec![0, 0, 1, 2]);
assert_eq!(d[0].raw.text, "`ifndef S");
assert_eq!(d[3].raw.text, "`endif");
}
#[test]
fn an_override_list_may_be_nothing_but_a_directive() {
// `picorv32/scripts/torture/testbench.v`: the whole `#( ... )` is one
// `include, so there is no element to hang the directive on.
let src = "module m;\n sub #(\n`include \"config.vh\"\n ) u (.a(x));\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
assert!(inst.params.as_ref().expect("a written `#()`").is_empty());
assert_eq!(inst.param_directives.len(), 1);
assert_eq!(inst.param_directives[0].raw.text, "`include \"config.vh\"");
assert_eq!(inst.param_directives[0].before, 0);
}
#[test]
fn a_connection_list_may_be_nothing_but_a_directive() {
let src = "module m;\n sub u (\n`ifdef X\n`endif\n );\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let Connections::Ordered(conns) = &inst.instances[0].conns else {
panic!("an element-less list has no `.` to make it named")
};
assert!(conns.is_empty());
assert_eq!(inst.instances[0].conn_directives.len(), 2);
}
#[test]
fn a_directive_before_the_first_connection_does_not_hide_the_dot() {
// The harvest must run before the `.`-peek that chooses named over
// ordered connections, or the backtick is read as a positional value.
let src =
"module m;\n sub u (\n`ifdef X\n .a(x),\n`endif\n .b(y)\n );\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
assert_eq!(conns.len(), 2);
assert_eq!(inst.instances[0].conn_directives[0].before, 0);
}
#[test]
fn a_directive_between_positional_connections_is_harvested_too() {
let src =
"module m;\n sub u (\n x,\n`ifdef X\n y,\n`endif\n z\n );\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let Connections::Ordered(conns) = &inst.instances[0].conns else {
panic!("expected ordered connections")
};
assert_eq!(conns.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, true, false]);
assert_eq!(inst.instances[0].conn_directives.len(), 2);
}
#[test]
fn an_instantiation_with_no_directive_keeps_empty_directive_vectors() {
// The harvest is a no-op unless a directive is actually there, which
// is what keeps every pre-existing instantiation byte-for-byte alike.
let src = "module m;\n sub #(.P(1)) u (.a(x), .b(y));\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
assert!(inst.param_directives.is_empty());
assert!(inst.instances[0].conn_directives.is_empty());
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
assert_eq!(conns.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, false]);
}
#[test]
fn a_directive_inside_a_connection_is_captured_or_refused_by_kind() {
// Superseded in part by `directive-in-statements` (2026-08-29). A
// *conditional* region inside a connection's parens is the bucket-7
// shape — `chip_earlgrey_asic.sv` writes one inside a parameter
// value's concatenation — so it is now captured verbatim rather than
// refused. `directives-in-lists` still does not read it as a list
// element: the whole instantiation becomes opaque bytes.
let src =
"module m;\n sub u (\n .a(\n`ifdef X\n y\n`endif\n )\n );\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.starts_with("sub u ("), "{:?}", raw.text);
assert!(raw.text.ends_with(");"), "{:?}", raw.text);
// Any *other* directive there is still an ordinary parse error: the
// recovery triggers on `ifdef / `ifndef only.
let msg = parse_err(
"module m;\n sub u (\n .a(\n`include \"x.vh\"\n y\n )\n );\nendmodule\n",
);
assert!(msg.contains("`include"), "{msg}");
}
/// The strict entry point keeps its contract: it fails at the *first*
/// error, with the same message tolerant mode files as its first
/// diagnostic.
#[test]
fn strict_parsing_still_stops_at_the_first_error() {
let src = "module m;\n wire a\n wire b;\n wire c\nendmodule\n";
let err = parse(tokenize(src).expect("lex error"), src).expect_err("strict must refuse");
let (_, diags) = crate::parse_source_tolerant(src);
assert_eq!(diags.len(), 2, "tolerant mode reports both");
assert_eq!(err.message, diags[0].message);
assert_eq!((err.line, err.col), (diags[0].line, diags[0].col));
}
fn class_of(file: &SourceFile) -> &ClassDecl {
let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") };
c
}
#[test]
fn class_header_parts_are_kept_apart() {
let f = parse_ok(
"virtual class c #(parameter int W = 8) extends pkg::base #(.A(1), b) \
implements i, j;\nendclass : c\n",
);
let c = class_of(&f);
assert_eq!(c.prefix, ["virtual"]);
assert_eq!(c.name, "c");
assert_eq!(c.param_ports.as_ref().expect("a parameter port list").len(), 1);
let ext = c.extends.as_ref().expect("an extends clause");
assert_eq!(ext.name, "pkg::base");
let params = ext.params.as_ref().expect("base parameter overrides");
assert_eq!(params.len(), 2);
assert_eq!(params[0].name, "A");
// An ordered override has no name, only an expression.
assert_eq!(params[1].name, "");
assert_eq!(c.implements.iter().map(|n| n.text.as_str()).collect::<Vec<_>>(), ["i", "j"]);
assert_eq!(c.end_label.as_deref(), Some("c"));
}
#[test]
fn class_bodies_hold_ordinary_items() {
let f = parse_ok(
"class c;\n `M(x)\n`ifdef Y\n int a;\n`endif\n typedef int t;\n \
localparam int W = 1;\n import p::q;\n rand bit [3:0] r;\nendclass\n",
);
let kinds: Vec<&str> = class_of(&f)
.items
.iter()
.map(|i| match &i.kind {
ItemKind::MacroItem(_) => "macro",
ItemKind::Directive(_) => "directive",
ItemKind::Typedef(_) => "typedef",
ItemKind::ParamDecl(_) => "param",
ItemKind::Import(_) => "import",
ItemKind::DataDecl(_) => "data",
_ => "other",
})
.collect();
assert_eq!(
kinds,
["macro", "directive", "data", "directive", "typedef", "param", "import", "data"]
);
}
#[test]
fn member_qualifiers_land_on_the_construct_they_qualify() {
let f = parse_ok(
"class c;\n local rand int a;\n pure virtual function void g();\n \
extern task t(int x);\n protected virtual task automatic u();\n endtask\nendclass\n",
);
let items = &class_of(&f).items;
let ItemKind::DataDecl(d) = &items[0].kind else { panic!("expected a declaration") };
assert_eq!(d.qualifiers, ["local", "rand"]);
let ItemKind::Function(g) = &items[1].kind else { panic!("expected a function") };
assert_eq!(g.prefix, ["pure", "virtual"]);
assert!(g.is_prototype && g.stmts.is_empty());
let ItemKind::Task(t) = &items[2].kind else { panic!("expected a task") };
assert_eq!(t.prefix, ["extern"]);
assert!(t.is_prototype);
let ItemKind::Task(u) = &items[3].kind else { panic!("expected a task") };
assert_eq!(u.prefix, ["protected", "virtual"]);
assert_eq!(u.qualifiers, ["automatic"]);
assert!(!u.is_prototype);
}
#[test]
fn a_dpi_import_is_a_function_prototype_with_a_linkage_prefix() {
let f = parse_ok(
"package p;\n import \"DPI-C\"\n function void env_final();\n \
import \"DPI-C\" context function chandle mk(int unsigned k);\n \
import \"DPI-C\" pure my_c_name = task tick(input int n);\nendpackage\n",
);
let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected package") };
let ItemKind::Function(a) = &items[0].kind else { panic!("expected a function") };
let dpi = a.dpi.as_ref().expect("DPI prefix");
assert_eq!(dpi.spec, "\"DPI-C\"");
assert_eq!(dpi.property, None);
assert!(dpi.c_identifier.is_none());
assert!(a.is_prototype && a.stmts.is_empty() && a.has_parens);
assert_eq!(a.name, "env_final");
let ItemKind::Function(b) = &items[1].kind else { panic!("expected a function") };
assert_eq!(b.dpi.as_ref().and_then(|d| d.property.clone()), Some("context".to_string()));
assert_eq!(b.ret.as_ref().map(|t| t.name.clone()), Some("chandle".to_string()));
assert_eq!(b.args.len(), 1);
assert!(b.args[0].dir.is_none());
let ItemKind::Task(c) = &items[2].kind else { panic!("expected a task") };
let dpi = c.dpi.as_ref().expect("DPI prefix");
assert_eq!(dpi.property, Some("pure".to_string()));
assert_eq!(dpi.c_identifier.as_ref().map(|n| n.text.clone()), Some("my_c_name".into()));
assert!(c.is_prototype);
}
#[test]
fn a_dpi_import_without_a_port_list_has_no_parens() {
let f = parse_ok("module m;\n import \"DPI-C\" function chandle get;\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Function(g) = &m.items[0].kind else { panic!("expected a function") };
assert!(!g.has_parens && g.args.is_empty());
assert_eq!(g.name, "get");
}
#[test]
fn context_is_a_linkage_name_when_an_equals_sign_follows_it() {
let f =
parse_ok("package p;\n import \"DPI-C\" context = function void f();\nendpackage\n");
let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected package") };
let ItemKind::Function(g) = &items[0].kind else { panic!("expected a function") };
let dpi = g.dpi.as_ref().expect("DPI prefix");
assert_eq!(dpi.property, None);
assert_eq!(dpi.c_identifier.as_ref().map(|n| n.text.clone()), Some("context".into()));
}
#[test]
fn exports_split_into_dpi_and_package_re_exports() {
let f = parse_ok(
"package p;\n export \"DPI-C\" function f;\n export \"DPI-C\" cn = task t;\n \
export q::*;\n export r::a, s::b;\n export *::*;\nendpackage\n",
);
let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected package") };
let kinds: Vec<String> = items
.iter()
.map(|i| match &i.kind {
ItemKind::Export(ExportDecl::Dpi(d)) => {
let c = d.c_identifier.as_ref().map(|n| n.text.as_str()).unwrap_or("-");
format!("dpi {} {} {} {}", d.spec, c, d.kw, d.name.text)
}
ItemKind::Export(ExportDecl::Package(paths)) => format!(
"pkg {}",
paths.iter().map(ImportPath::text).collect::<Vec<_>>().join(", ")
),
_ => "other".to_string(),
})
.collect();
assert_eq!(
kinds,
[
"dpi \"DPI-C\" - function f",
"dpi \"DPI-C\" cn task t",
"pkg q::*",
"pkg r::a, s::b",
"pkg *::*",
]
);
}
#[test]
fn a_plain_package_import_is_still_a_package_import() {
let f = parse_ok("package p;\n import q::*, r::t;\nendpackage\n");
let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected package") };
let ItemKind::Import(paths) = &items[0].kind else { panic!("expected an import") };
assert_eq!(paths.len(), 2);
// `import *::*;` is not a thing; only `export` writes a wildcard package.
assert!(
parse_err("package p;\n import *::*;\nendpackage\n").contains("expected identifier")
);
}
#[test]
fn a_dpi_export_needs_a_function_or_task_keyword() {
let msg = parse_err("package p;\n export \"DPI-C\" f;\nendpackage\n");
assert!(msg.contains("expected `function` or `task` in a DPI export"), "{msg}");
}
#[test]
fn an_out_of_body_method_keeps_its_class_scope_apart_from_its_name() {
let f = parse_ok("function void my_class::configure(int x);\nendfunction\n");
let ItemKind::Function(g) = &f.items[0].kind else { panic!("expected a function") };
assert_eq!(g.scope.as_deref(), Some("my_class"));
assert_eq!(g.name, "configure");
}
#[test]
fn constraints_and_covergroups_are_captured_verbatim() {
let src = "class c;\n constraint x {\n a == 0; // why\n }\n \
covergroup g;\n coverpoint a;\n endgroup : g\nendclass\n";
let f = parse_ok(src);
let items = &class_of(&f).items;
let ItemKind::Verbatim(a) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(a.text, "constraint x {\n a == 0; // why\n }");
assert_eq!(a.text, src[a.span.as_range()]);
let ItemKind::Verbatim(b) = &items[1].kind else { panic!("expected a verbatim block") };
assert_eq!(b.text, "covergroup g;\n coverpoint a;\n endgroup : g");
}
#[test]
fn a_comment_after_a_verbatim_block_stays_outside_it() {
// The comment is written past the block's last token, so it must not
// be swallowed by the capture *or* dropped from the plumbing.
let f =
parse_ok("class c;\n constraint x {\n a == 0;\n } // why\n int b;\nendclass\n");
let items = &class_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(!raw.text.contains("why"), "the capture swallowed the comment: {:?}", raw.text);
assert_eq!(items[0].meta.trailing.as_ref().expect("the comment survived").text, "// why");
}
// ------------------------------------------------------------------
// Out-of-block constraints
// (`docs/features/out-of-class-constraints/README.md`)
// ------------------------------------------------------------------
#[test]
fn an_out_of_block_constraint_is_a_file_scope_verbatim_item() {
let src = "constraint my_item::delay_c {\n soft delay dist {0 :/ 5};\n}\n";
let f = parse_ok(src);
let ItemKind::Verbatim(raw) = &f.items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "constraint my_item::delay_c {\n soft delay dist {0 :/ 5};\n}");
assert_eq!(raw.text, src[raw.span.as_range()], "the capture is the source bytes");
}
#[test]
fn an_out_of_block_constraint_scope_may_be_a_chain() {
// `pkg::cls::name` — the same chain `parse_method_name` accepts for an
// out-of-body method. Nothing is bound either way, so all that matters
// is that the whole chain is consumed before the `{`.
let f = parse_ok("constraint pkg::cls::deep_c { x < 4; }\n");
let ItemKind::Verbatim(raw) = &f.items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "constraint pkg::cls::deep_c { x < 4; }");
}
#[test]
fn an_out_of_block_constraint_lives_in_a_package_too() {
let f = parse_ok("package p;\n constraint c::x { a > 0; }\nendpackage\n");
let ItemKind::Package { items, .. } = &f.items[0].kind else {
panic!("expected a package")
};
assert!(matches!(items[0].kind, ItemKind::Verbatim(_)), "{:?}", items[0].kind);
}
#[test]
fn an_out_of_block_constraint_keeps_its_trailing_semicolon_and_comments() {
// `constraint C::c { ... };` — the stray `;` belongs to the block, and
// a comment written past the block must stay outside the capture.
let f = parse_ok("// head\nconstraint c::x { a == 0; }; // tail\nint b;\n");
let ItemKind::Verbatim(raw) = &f.items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "constraint c::x { a == 0; };");
assert!(!raw.text.contains("tail"), "the capture swallowed the comment: {:?}", raw.text);
assert_eq!(f.items[0].meta.leading[0].text, "// head");
assert_eq!(f.items[0].meta.trailing.as_ref().expect("trailing comment").text, "// tail");
}
#[test]
fn an_in_class_constraint_still_rejects_a_scope_free_syntax_error() {
// The widened name must not swallow a genuinely broken header: the
// `::` path only accepts an identifier after the separator.
assert_eq!(parse_err("constraint c:: { a == 0; }\n"), "expected identifier (found \"{\")");
assert_eq!(parse_err("constraint 4::x { a == 0; }\n"), "expected identifier (found \"4\")");
}
// ------------------------------------------------------------------
// Concurrent assertions (`docs/features/assertions/README.md`)
// ------------------------------------------------------------------
#[test]
fn a_concurrent_assertion_is_captured_verbatim() {
let src = "module m;\n assert property (@(posedge clk) a |-> ##[1:3] b);\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Verbatim(raw) = &module_of(&f).items[0].kind else {
panic!("expected a verbatim block")
};
assert_eq!(raw.text, "assert property (@(posedge clk) a |-> ##[1:3] b);");
assert_eq!(raw.text, src[raw.span.as_range()]);
}
#[test]
fn every_concurrent_assertion_keyword_parses_at_item_position() {
// `restrict` is not a lexer keyword — it reaches the item dispatch as
// an identifier — so it is worth pinning next to the other three.
for kw in ["assert", "assume", "cover", "restrict"] {
let f = parse_ok(&format!("module m;\n {kw} property (a |-> b);\nendmodule\n"));
assert!(
matches!(module_of(&f).items[0].kind, ItemKind::Verbatim(_)),
"`{kw} property` did not parse as a verbatim item"
);
}
}
#[test]
fn a_label_before_a_concurrent_assertion_is_part_of_the_capture() {
let f = parse_ok("NoNMI: assume property (~irq_nm_i);\n");
let ItemKind::Verbatim(raw) = &f.items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "NoNMI: assume property (~irq_nm_i);");
}
#[test]
fn an_assertion_action_block_is_part_of_the_capture() {
let f = parse_ok("module m;\n assert property (a) else $error(\"no\");\nendmodule\n");
let ItemKind::Verbatim(raw) = &module_of(&f).items[0].kind else {
panic!("expected a verbatim block")
};
assert_eq!(raw.text, "assert property (a) else $error(\"no\");");
}
#[test]
fn an_assertion_action_block_may_be_a_begin_end_block() {
let src = "module m;\n assert property (a) else begin\n $error(\"no\");\n end\n wire w;\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") };
assert_eq!(raw.text, "assert property (a) else begin\n $error(\"no\");\n end");
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)), "the next item was swallowed");
}
#[test]
fn an_action_block_keeps_a_nested_begin_end_whole() {
// QA round-1: the scan used to stop at the first `;` inside the
// nested block, leaving its `end` (and the `else`) behind.
let src = "module m;\n assert property (a |-> b)\n if (c) begin\n x = 1;\n end\n else y = 2;\n wire w;\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") };
assert_eq!(
raw.text,
"assert property (a |-> b)\n if (c) begin\n x = 1;\n end\n else y = 2;"
);
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)), "the next item was swallowed");
}
#[test]
fn an_action_block_may_be_a_fork_or_a_case() {
// `disable fork` / `wait fork` name the enclosing block rather than
// opening one, so neither may push the scan's block depth.
let fork = "fork\n x = 1;\n begin\n disable fork;\n wait fork;\n end\n join_none";
let case = "case (s)\n 1: x = 1;\n default: begin\n y = 2;\n end\n endcase";
for body in [fork, case] {
let src =
format!("module m;\n assert property (a)\n {body}\n wire w;\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 {body}")
};
assert_eq!(raw.text, format!("assert property (a)\n {body}"));
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)), "the next item was swallowed");
}
}
#[test]
fn an_unbalanced_action_block_is_a_clean_error() {
// Never past the end of the file, never a loop.
assert_eq!(
parse_err(
"module m;\n assert property (a)\n if (c) begin\n x = 1;\nendmodule\n"
),
"expected `;` (found \"<eof>\")"
);
// A closer with nothing open ends the scan where it stands.
assert_eq!(
parse_err("module m;\n initial begin\n assert property (a)\n end\nendmodule\n"),
"expected `;` (found \"end\")"
);
}
#[test]
fn both_halves_of_an_action_block_are_captured() {
let f = parse_ok(
"module m;\n assert property (a) $info(\"y\"); else $error(\"n\");\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, "assert property (a) $info(\"y\"); else $error(\"n\");");
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)), "the next item was swallowed");
}
#[test]
fn a_concurrent_assertion_also_parses_in_statement_position() {
let f = parse_ok(
"module m;\n initial begin\n assert property (@(posedge clk) a |-> b);\n x = 1;\n end\nendmodule\n",
);
let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else {
panic!("expected an initial block")
};
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
let StmtKind::Verbatim(raw) = &stmts[0].kind else {
panic!("expected a verbatim statement, got {:?}", stmts[0].kind)
};
assert_eq!(raw.text, "assert property (@(posedge clk) a |-> b);");
assert!(matches!(stmts[1].kind, StmtKind::Assign { .. }), "the next statement was lost");
}
#[test]
fn an_immediate_assertion_still_takes_the_statement_path() {
// No `property` keyword, so nothing about the verbatim capture may
// pre-empt the structural immediate-assertion node.
let f = parse_ok("module m;\n initial assert (x == 1) else $error(\"no\");\nendmodule\n");
let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else {
panic!("expected an initial block")
};
assert!(matches!(stmt.kind, StmtKind::Assert { .. }), "got {:?}", stmt.kind);
}
#[test]
fn property_and_sequence_declarations_are_captured_verbatim() {
let src =
"module m;\n property p(int w);\n realtime t;\n a |-> b;\n endproperty : p\n \
sequence s;\n a ##1 b;\n endsequence\nendmodule\n";
let f = parse_ok(src);
let items = &module_of(&f).items;
let ItemKind::Verbatim(p) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(p.text, "property p(int w);\n realtime t;\n a |-> b;\n endproperty : p");
let ItemKind::Verbatim(s) = &items[1].kind else { panic!("expected a verbatim block") };
assert_eq!(s.text, "sequence s;\n a ##1 b;\n endsequence");
}
#[test]
fn an_unclosed_property_declaration_is_an_error_not_a_swallowed_file() {
assert!(
parse_err("module m;\n property p;\n a |-> b;\nendmodule\n")
.contains("expected `endproperty`"),
"an unterminated property must be reported"
);
}
#[test]
fn a_parameterized_type_is_a_declaration_and_a_parameterized_module_is_an_instance() {
let f =
parse_ok("module m;\n port_t #(bit [3:0]) p;\n sub #(.W(8)) u (.a(a));\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") };
assert_eq!(d.ty.name, "port_t");
assert_eq!(d.ty.params().expect("type parameters").text, "#(bit [3:0])");
assert!(matches!(m.items[1].kind, ItemKind::Instantiation(_)));
}
#[test]
fn a_parameterized_class_reference_is_one_expression_segment() {
let f = parse_ok("class c;\n function void f();\n \
x = uvm_config_db#(virtual bus_if)::get(this);\n endfunction\nendclass\n");
let ItemKind::Function(g) = &class_of(&f).items[0].kind else {
panic!("expected a function")
};
let StmtKind::Assign { rhs, .. } = &g.stmts[0].kind else {
panic!("expected an assignment")
};
// call( scope( parameterized( ident ) ) )
let ExprKind::Call { callee, .. } = &rhs.kind else { panic!("expected a call") };
let ExprKind::Scope { base, name } = &callee.kind else { panic!("expected a scope") };
assert_eq!(name, "get");
let ExprKind::Parameterized { base, params } = &base.kind else {
panic!("expected a parameterized reference")
};
assert_eq!(params.text, "#(virtual bus_if)");
assert!(matches!(&base.kind, ExprKind::Ident(n) if n == "uvm_config_db"));
}
#[test]
fn a_typedef_can_forward_declare_a_class() {
let f = parse_ok("typedef class c;\n");
let ItemKind::Typedef(t) = &f.items[0].kind else { panic!("expected a typedef") };
assert_eq!(t.name, "c");
assert!(matches!(t.kind, TypedefKind::ForwardClass));
}
#[test]
fn class_bodies_are_charged_against_the_nesting_budget() {
// Classes nest through `parse_item`, like modules and packages, so a
// pathologically nested file is a clean error rather than a crash.
let deep = |n: usize| {
let mut s = String::new();
for i in 0..n {
s.push_str(&format!("class c{i};\n"));
}
for _ in 0..n {
s.push_str("endclass\n");
}
s
};
assert!(parse_deep(deep(MAX_NESTING_DEPTH as usize - 1)).is_ok());
assert_too_deep(deep(MAX_NESTING_DEPTH as usize + 1));
}
// ------------------------------------------------------------------
// Dynamic types (queues, dynamic/associative arrays, named args)
// ------------------------------------------------------------------
fn first_decl(file: &SourceFile) -> &DataDecl {
let ItemKind::DataDecl(d) = &file.items[0].kind else { panic!("expected a declaration") };
d
}
#[test]
fn a_queue_dim_is_a_range_whose_bound_is_a_dollar_ident() {
let f = parse_ok("module m;\n string q[$];\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") };
let [dim] = &d.declarators[0].unpacked[..] else { panic!("expected one dim") };
let DimKind::Range { a, b } = &dim.kind else { panic!("expected a range dim") };
assert!(matches!(&a.kind, ExprKind::Ident(n) if n == "$"));
assert!(b.is_none());
}
#[test]
fn a_bounded_queue_keeps_its_bound() {
let f = parse_ok("int q[$:8];\n");
let [dim] = &first_decl(&f).declarators[0].unpacked[..] else { panic!("one dim") };
let DimKind::Range { a, b } = &dim.kind else { panic!("expected a range dim") };
assert!(matches!(&a.kind, ExprKind::Ident(n) if n == "$"));
assert!(matches!(&b.as_ref().expect("bound").kind, ExprKind::Number(n) if n == "8"));
}
#[test]
fn a_dynamic_array_dim_is_empty_and_a_wildcard_dim_is_a_star() {
let f = parse_ok("int a[];\nlogic b[*];\n");
let [dim] = &first_decl(&f).declarators[0].unpacked[..] else { panic!("one dim") };
assert!(matches!(dim.kind, DimKind::Dynamic));
let ItemKind::DataDecl(d) = &f.items[1].kind else { panic!("expected a declaration") };
assert!(matches!(d.declarators[0].unpacked[0].kind, DimKind::Wildcard));
}
#[test]
fn a_multi_dim_declarator_may_end_in_a_queue_or_dynamic_dim() {
let f = parse_ok("payload_t q[NumInp-1:0][$];\nseq_t s[NUM_HARTS][];\n");
let dims = &first_decl(&f).declarators[0].unpacked;
assert_eq!(dims.len(), 2);
assert!(matches!(&dims[0].kind, DimKind::Range { b: Some(_), .. }));
assert!(matches!(&dims[1].kind, DimKind::Range { a, b: None }
if matches!(&a.kind, ExprKind::Ident(n) if n == "$")));
let ItemKind::DataDecl(d) = &f.items[1].kind else { panic!("expected a declaration") };
assert!(matches!(d.declarators[0].unpacked[1].kind, DimKind::Dynamic));
}
#[test]
fn a_parameterized_type_with_a_queue_declarator_is_a_declaration_not_an_instance() {
let f = parse_ok("class c;\n item_t #(A, B) q[$];\nendclass\n");
let c = class_of(&f);
let ItemKind::DataDecl(d) = &c.items[0].kind else { panic!("expected a declaration") };
assert_eq!(d.ty.name, "item_t");
assert!(d.ty.params().is_some());
assert_eq!(d.declarators[0].name, "q");
}
#[test]
fn an_empty_brace_pair_is_an_empty_concat() {
let f = parse_ok("module m;\n initial q = {};\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected initial") };
let StmtKind::Assign { rhs, .. } = &stmt.kind else { panic!("expected an assignment") };
assert!(matches!(&rhs.kind, ExprKind::Concat(items) if items.is_empty()));
}
#[test]
fn dollar_indexes_parse_as_ordinary_expressions() {
// `q[$]` and `q[$-1]` — the `$` is an expression leaf, so member
// access and arithmetic around it need no special cases.
let f = parse_ok("module m;\n initial q[$].label = q2[$-1];\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected initial") };
let StmtKind::Assign { lhs, .. } = &stmt.kind else { panic!("expected an assignment") };
let ExprKind::Member { base, name } = &lhs.kind else { panic!("expected a member") };
assert_eq!(name, "label");
assert!(matches!(&base.kind, ExprKind::Index { .. }));
}
#[test]
fn named_call_arguments_keep_their_names_and_values() {
let f = parse_ok(
"module m;\n initial csr_wr(.ptr(ral.ovrd), .value(x), .flag());\nendmodule\n",
);
let src = "module m;\n initial csr_wr(.ptr(ral.ovrd), .value(x), .flag());\nendmodule\n";
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected initial") };
let StmtKind::ExprStmt(call) = &stmt.kind else { panic!("expected a call statement") };
let ExprKind::Call { args, .. } = &call.kind else { panic!("expected a call") };
let names: Vec<&str> = args
.iter()
.map(|a| match &a.expr.kind {
ExprKind::NamedArg { name, name_span, .. } => {
assert_eq!(&src[name_span.start as usize..name_span.end as usize], name);
name.as_str()
}
other => panic!("expected a named argument, got {other:?}"),
})
.collect();
assert_eq!(names, ["ptr", "value", "flag"]);
let ExprKind::NamedArg { value, .. } = &args[2].expr.kind else { unreachable!() };
assert!(matches!(value.kind, ExprKind::Empty(_)), "`.flag()` is explicitly empty");
}
#[test]
fn case_inside_records_the_keyword_and_takes_range_labels() {
let f = parse_ok(
"module m;\n initial case (x) inside\n [A:B], C: y = 1;\n default: y = 0;\n endcase\nendmodule\n",
);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected initial") };
let StmtKind::Case { inside, items, .. } = &stmt.kind else { panic!("expected a case") };
assert!(*inside);
assert!(matches!(&items[0].labels[0].expr.kind, ExprKind::ValueRange { .. }));
assert!(matches!(&items[0].labels[1].expr.kind, ExprKind::Ident(n) if n == "C"));
assert!(items[1].labels.is_empty(), "default has no labels");
}
#[test]
fn a_plain_case_is_not_inside() {
let f = parse_ok("module m;\n initial case (x)\n 1: y = 1;\n endcase\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected initial") };
let StmtKind::Case { inside, .. } = &stmt.kind else { panic!("expected a case") };
assert!(!*inside);
}
#[test]
fn a_bare_event_control_is_recorded_without_parens() {
let f = parse_ok("module m;\n task t;\n @ev;\n @a.b.c;\n endtask\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Task(task) = &m.items[0].kind else { panic!("expected a task") };
let StmtKind::Timing { control: TimingControl::Event(SensList::Bare(e)), .. } =
&task.stmts[0].kind
else {
panic!("expected a bare event control")
};
assert!(matches!(&e.kind, ExprKind::Ident(n) if n == "ev"));
let StmtKind::Timing { control: TimingControl::Event(SensList::Bare(e)), .. } =
&task.stmts[1].kind
else {
panic!("expected a bare event control")
};
assert!(matches!(&e.kind, ExprKind::Member { name, .. } if name == "c"));
}
#[test]
fn a_parenthesized_event_control_stays_a_list() {
// `@(ev)` and `@ev` are different token streams; each keeps its own.
let f = parse_ok("module m;\n task t;\n @(ev);\n endtask\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Task(task) = &m.items[0].kind else { panic!("expected a task") };
assert!(matches!(
&task.stmts[0].kind,
StmtKind::Timing { control: TimingControl::Event(SensList::List(_)), .. }
));
}
#[test]
fn a_macro_followed_by_a_hierarchical_call_stands_alone() {
// `` `WAIT_FOR_RESET `` ⏎ `cov.cg.sample(a);` — a declarator name is
// never followed by `.`, so the macro is a standalone statement.
let f = parse_ok(
"module m;\n task t;\n `WAIT_FOR_RESET\n cov.cg.sample(a);\n endtask\nendmodule\n",
);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Task(task) = &m.items[0].kind else { panic!("expected a task") };
assert!(matches!(&task.stmts[0].kind, StmtKind::MacroStmt(_)));
assert!(matches!(&task.stmts[1].kind, StmtKind::ExprStmt(_)));
}
#[test]
fn an_interface_is_a_module_with_its_own_closing_keyword() {
let f = parse_ok("interface bus_if (input clk);\n logic a;\nendinterface : bus_if\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected an interface") };
assert_eq!(m.kw, "interface");
assert_eq!(m.end_kw(), "endinterface");
assert_eq!(m.end_label.as_deref(), Some("bus_if"));
assert!(matches!(&m.ports, PortList::Ansi(p) if p.len() == 1));
}
#[test]
fn an_interface_header_takes_the_module_header_imports() {
// corpus/ibex/dv/uvm/core_ibex/fcov/core_ibex_pmp_fcov_if.sv:7
let f = parse_ok(
"interface fcov_if import ibex_pkg::*; #(parameter int W = 1) (input clk);\nendinterface\n",
);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected an interface") };
assert_eq!(m.imports.len(), 1);
assert_eq!(m.imports[0].paths[0].text(), "ibex_pkg::*");
assert_eq!(m.param_ports.as_ref().map(Vec::len), Some(1));
}
#[test]
fn interface_class_is_not_an_interface() {
// IEEE 1800-2017 8.26: a different construct, deliberately unsupported.
assert!(parse_err("interface class ic;\nendclass\n").contains("`interface`"));
}
#[test]
fn a_modport_keeps_the_grouping_the_source_wrote() {
// corpus/common_cells/src/stream_intf.sv:29
let f = parse_ok(
"interface i;\n modport In (output ready, input valid, data);\nendinterface\n",
);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected an interface") };
let ItemKind::Modport(decls) = &m.items[0].kind else { panic!("expected a modport") };
assert_eq!(decls.len(), 1);
assert_eq!(decls[0].name, "In");
assert_eq!(decls[0].ports.len(), 2);
assert_eq!(decls[0].ports[0].kw, "output");
assert_eq!(decls[0].ports[1].kw, "input");
let names: Vec<&str> = decls[0].ports[1].names.iter().map(|n| n.text.as_str()).collect();
assert_eq!(names, ["valid", "data"]);
}
#[test]
fn one_modport_declaration_may_name_several_modports() {
let f = parse_ok("interface i;\n modport a (input x), b (output x);\nendinterface\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected an interface") };
let ItemKind::Modport(decls) = &m.items[0].kind else { panic!("expected a modport") };
assert_eq!(decls.len(), 2);
assert_eq!(decls[0].name, "a");
assert_eq!(decls[1].name, "b");
}
#[test]
fn a_clocking_block_parses_its_items() {
// corpus/common_cells/test/stream_register_tb.sv:75
let f = parse_ok(
"module m;\n clocking cb @(posedge clk);\n default input #2 output #4;\n input a, b;\n output negedge c;\n endclocking\nendmodule\n",
);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Clocking(c) = &m.items[0].kind else { panic!("expected a clocking block") };
assert!(!c.is_default);
assert_eq!(c.name.as_ref().map(|n| n.text.as_str()), Some("cb"));
assert_eq!(c.items.len(), 3);
assert!(matches!(
&c.items[0].kind,
ClockingItemKind::Default { input: Some(i), output: Some(o) } if i == "#2" && o == "#4"
));
assert!(matches!(
&c.items[1].kind,
ClockingItemKind::Signals { dir, skew: None, names } if dir == "input" && names.len() == 2
));
assert!(matches!(
&c.items[2].kind,
ClockingItemKind::Signals { dir, skew: Some(s), .. } if dir == "output" && s == "negedge"
));
}
#[test]
fn a_default_clocking_may_be_anonymous_or_body_less() {
// corpus/ibex/dv/formal/check/top.sv:143, and IEEE 1800-2017 14.12.
let f = parse_ok("module m;\n default clocking @(posedge clk); endclocking\n default clocking cb;\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Clocking(anon) = &m.items[0].kind else {
panic!("expected a clocking block")
};
assert!(anon.is_default && anon.name.is_none() && anon.event.is_some() && anon.has_end);
let ItemKind::Clocking(sel) = &m.items[1].kind else { panic!("expected a clocking block") };
assert!(sel.is_default && sel.event.is_none() && !sel.has_end);
}
#[test]
fn a_virtual_interface_type_stands_in_every_type_position() {
// corpus/ibex/dv/uvm/icache/dv/env/ibex_icache_env_pkg.sv:28 (typedef)
// and corpus/common_cells/test/stream_test.sv:31 (argument).
let f = parse_ok(
"package p;\n typedef virtual push_pull_if #(.W(4)) vif_t;\n function void f(virtual interface bus_if h);\n endfunction\nendpackage\n",
);
let ItemKind::Package { items, .. } = &f.items[0].kind else {
panic!("expected a package")
};
let ItemKind::Typedef(t) = &items[0].kind else { panic!("expected a typedef") };
let TypedefKind::Alias(ty) = &t.kind else { panic!("expected a type alias") };
assert_eq!(ty.virt, Some(VirtualKw::Bare));
assert_eq!(ty.name, "push_pull_if");
let ItemKind::Function(fun) = &items[1].kind else { panic!("expected a function") };
assert_eq!(fun.args[0].ty.virt, Some(VirtualKw::Interface));
assert_eq!(fun.args[0].ty.name, "bus_if");
}
#[test]
fn an_anonymous_enum_declares_a_variable() {
// corpus/common_cells/src/deprecated/clock_divider.sv:59
let f =
parse_ok("module m;\n enum logic [1:0] {IDLE, STOP} state, state_next;\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") };
let Some(TypeExtra::Enum(e)) = d.ty.inline() else { panic!("expected an inline enum") };
assert_eq!(e.members.len(), 2);
assert_eq!(e.base.as_ref().map(|b| b.name.as_str()), Some("logic"));
assert_eq!(d.declarators.len(), 2);
}
#[test]
fn an_anonymous_struct_declares_a_variable() {
let f = parse_ok("module m;\n struct packed {logic a;} s;\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") };
let Some(TypeExtra::Struct(st)) = d.ty.inline() else {
panic!("expected an inline struct")
};
assert_eq!(st.kw, "struct");
assert!(st.packed);
assert_eq!(d.declarators[0].name, "s");
}
#[test]
fn a_struct_member_may_itself_be_an_inline_aggregate() {
// corpus/opentitan/hw/ip/uart/rtl/uart_reg_pkg.sv:30
let f = parse_ok(
"package p;\n typedef struct packed {\n struct packed {logic q;} tx;\n } r_t;\nendpackage\n",
);
let ItemKind::Package { items, .. } = &f.items[0].kind else {
panic!("expected a package")
};
let ItemKind::Typedef(t) = &items[0].kind else { panic!("expected a typedef") };
let TypedefKind::Struct(st) = &t.kind else { panic!("expected a struct") };
assert!(matches!(st.members[0].ty.inline(), Some(TypeExtra::Struct(_))));
}
#[test]
fn an_enum_base_type_may_be_a_typedef_name() {
// corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_count_pkg.sv:10
let f = parse_ok(
"package p;\n typedef enum action_mask_t {Clr = 4'h1} action_e;\nendpackage\n",
);
let ItemKind::Package { items, .. } = &f.items[0].kind else {
panic!("expected a package")
};
let ItemKind::Typedef(t) = &items[0].kind else { panic!("expected a typedef") };
let TypedefKind::Enum(e) = &t.kind else { panic!("expected an enum") };
assert_eq!(e.base.as_ref().map(|b| b.name.as_str()), Some("action_mask_t"));
}
#[test]
fn packed_dimensions_may_follow_a_typedef_type_name() {
// corpus/common_cells/src/stream_xbar.sv:98
let f = parse_ok("module m;\n payload_t [A-1:0][B-1:0] out_data;\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") };
assert_eq!(d.ty.name, "payload_t");
assert_eq!(d.ty.packed.len(), 2);
assert_eq!(d.declarators[0].name, "out_data");
}
#[test]
fn an_indexed_assignment_is_not_a_declaration() {
let f = parse_ok("module m;\n always_comb begin\n x[i] = 1;\n end\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Always { stmt, .. } = &m.items[0].kind else { panic!("expected an always") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
assert!(
matches!(stmts[0].kind, StmtKind::Assign { .. }),
"expected an assignment, got {:?}",
stmts[0].kind
);
}
#[test]
fn a_type_parameter_may_be_declared_as_an_item() {
// corpus/common_cells/test/lossy_valid_to_stream_tb.sv:26
let f = parse_ok("module m;\n localparam type payload_t = logic [7:0];\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::ParamDecl(d) = &m.items[0].kind else { panic!("expected a parameter") };
assert!(d.is_type);
assert!(matches!(d.declarators[0].init.as_ref().map(|e| &e.kind), Some(ExprKind::Type(_))));
}
#[test]
fn a_for_init_may_declare_a_typedef_typed_variable() {
// corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_sparse_fsm_flop.sv:48
let f = parse_ok(
"module m;\n initial for (int i = 0, state_e t = t.first(); i < 2; i += 1, t = t.next()) x = i;\nendmodule\n",
);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::For { init, step, .. } = &stmt.kind else { panic!("expected a for") };
assert_eq!(init.len(), 2);
assert_eq!(init[0].ty.as_ref().map(|t| t.name.as_str()), Some("int"));
assert_eq!(init[1].ty.as_ref().map(|t| t.name.as_str()), Some("state_e"));
assert_eq!(step.len(), 2);
}
#[test]
fn an_unterminated_anonymous_enum_is_an_error() {
assert!(parse_err("module m;\n enum logic [1:0] {A, B state;\nendmodule\n")
.contains("expected"));
}
/// Run `check` on the right-hand side of `src`'s first continuous
/// assignment. A closure rather than a getter: the parsed file owns the
/// expression and must outlive the borrow.
fn with_assign_rhs(src: &str, check: impl FnOnce(&Expr)) {
let f = parse_ok(src);
let ItemKind::ContAssign(a) = &module_of(&f).items[0].kind else {
panic!("expected an assign")
};
check(&a.assigns[0].rhs);
}
#[test]
fn a_cast_base_may_be_parenthesized_or_scoped() {
// corpus/common_cells/src/lzc.sv:67 and
// corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_lc_sender.sv:32.
with_assign_rhs("module m;\n assign a = (NumLevels)'(unsigned'(j));\nendmodule\n", |e| {
let ExprKind::Cast { ty, .. } = &e.kind else { panic!("expected a cast") };
assert!(
matches!(ty.kind, ExprKind::Paren { .. }),
"base is the parenthesized expression"
);
});
with_assign_rhs("module m;\n assign a = lc_ctrl_pkg::TxWidth'(x);\nendmodule\n", |e| {
let ExprKind::Cast { ty, .. } = &e.kind else { panic!("expected a cast") };
assert!(matches!(ty.kind, ExprKind::Scope { .. }), "base is the scoped name");
});
}
#[test]
fn a_cast_base_that_is_not_a_constant_primary_is_still_rejected() {
let msg = parse_err("module m;\n assign a = f(1)'(x);\nendmodule\n");
assert!(msg.contains("unsupported cast base expression"), "unexpected: {msg}");
}
#[test]
fn an_arrow_at_statement_position_is_still_an_event_trigger() {
let f =
parse_ok("module m;\n initial begin\n -> ev;\n x = a -> b;\n end\nendmodule\n");
let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else {
panic!("expected an initial")
};
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
assert!(matches!(stmts[0].kind, StmtKind::EventTrigger(_)), "`-> ev;` is a trigger");
let StmtKind::Assign { rhs, .. } = &stmts[1].kind else { panic!("expected an assignment") };
assert!(matches!(rhs.kind, ExprKind::Binary { .. }), "`a -> b` is an implication");
}
#[test]
fn the_implication_operators_are_right_associative_and_bind_loosest() {
// `a ? b : c -> d` is `(a ? b : c) -> d`; `a -> b -> c` is
// `a -> (b -> c)` (IEEE 1800 §11.3.2).
with_assign_rhs("module m;\n assign y = a ? b : c -> d;\nendmodule\n", |e| {
let ExprKind::Binary { lhs, op, .. } = &e.kind else {
panic!("expected an implication")
};
assert_eq!(op, "->");
assert!(matches!(lhs.kind, ExprKind::Ternary { .. }), "the `? :` is the left operand");
});
with_assign_rhs("module m;\n assign y = a -> b -> c;\nendmodule\n", |e| {
let ExprKind::Binary { rhs, .. } = &e.kind else { panic!("expected an implication") };
assert!(matches!(rhs.kind, ExprKind::Binary { .. }), "the chain nests to the right");
});
}
#[test]
fn only_a_brace_after_the_first_element_makes_an_assignment_pattern_a_replication() {
// corpus/opentitan/hw/ip/uart/rtl/uart.sv:17.
with_assign_rhs("module m;\n assign y = '{NumRegs{0}};\nendmodule\n", |e| {
assert!(matches!(e.kind, ExprKind::AssignPatternRepl { .. }));
});
for src in [
"module m;\n assign y = '{a: 0, b: 1};\nendmodule\n",
"module m;\n assign y = '{x, y};\nendmodule\n",
"module m;\n assign y = '{{a, b}};\nendmodule\n",
"module m;\n assign y = '{default: 0};\nendmodule\n",
] {
with_assign_rhs(src, |e| {
assert!(matches!(e.kind, ExprKind::AssignPattern(_)), "not a replication: {src:?}");
});
}
}
#[test]
fn a_streaming_concatenation_keeps_its_direction_and_optional_slice_size() {
// corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_sha2_pkg.sv:123.
with_assign_rhs("module m;\n assign y = {<<8{v}};\nendmodule\n", |e| {
let ExprKind::Stream { dir, slice, inner } = &e.kind else {
panic!("expected a stream")
};
assert_eq!(dir, "<<");
assert!(matches!(slice.as_deref().map(|s| &s.kind), Some(ExprKind::Number(_))));
assert_eq!(inner.len(), 1);
});
with_assign_rhs("module m;\n assign y = {>>{a, b}};\nendmodule\n", |e| {
let ExprKind::Stream { dir, slice, inner } = &e.kind else {
panic!("expected a stream")
};
assert_eq!(dir, ">>");
assert!(slice.is_none(), "no slice size was written");
assert_eq!(inner.len(), 2);
});
}
#[test]
fn a_drive_strength_is_only_read_where_a_strength_keyword_follows_the_paren() {
// corpus/ibex/vendor/lowrisc_ip/ip/prim_generic/rtl/prim_usb_diff_rx.sv:39.
let f = parse_ok("module m;\n assign (weak0, pull1) a = b;\n assign c = d;\nendmodule\n");
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"));
let ItemKind::ContAssign(b) = &items[1].kind else { panic!("expected an assign") };
assert!(b.strength.is_none());
}
#[test]
fn an_attribute_may_precede_a_named_port_connection() {
// corpus/common_cells/src/cdc_fifo_gray.sv:140.
let f =
parse_ok("module m;\n sub u (\n (* async *) .a(x),\n .b(y)\n );\nendmodule\n");
let ItemKind::Instantiation(inst) = &module_of(&f).items[0].kind else {
panic!("expected an instantiation")
};
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
assert_eq!(conns[0].meta.attrs.len(), 1);
assert_eq!(conns[0].meta.attrs[0].text, "(* async *)");
assert_eq!(conns[0].name, "a");
assert!(conns[1].meta.attrs.is_empty());
}
// ------------------------------------------------------------------
// DV statements (`docs/features/dv-statements/README.md`)
// ------------------------------------------------------------------
/// The statements of the one `initial` block of a single-item module.
fn initial_stmts(f: &SourceFile) -> &Vec<Stmt> {
let ItemKind::Initial(stmt) = &module_of(f).items[0].kind else {
panic!("expected an initial block")
};
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
stmts
}
#[test]
fn a_randomize_with_block_is_captured_verbatim_and_the_call_is_not() {
let f = parse_ok(
"module m;\n initial begin\n x = std::randomize(y) with {\n y > 1;\n };\n end\nendmodule\n",
);
let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else {
panic!("expected an assignment")
};
let ExprKind::WithConstraint { base, block, .. } = &rhs.kind else {
panic!("expected a with-constraint, got {:?}", rhs.kind)
};
// The `with` keyword is outside the capture; the braces are inside.
assert_eq!(block.text, "{\n y > 1;\n }");
assert!(matches!(base.kind, ExprKind::Call { .. }), "the call is still structural");
}
#[test]
fn an_array_method_with_argument_is_an_ordinary_expression() {
let f = parse_ok(
"module m;\n initial begin\n n = q.sum() with (item.w);\n end\nendmodule\n",
);
let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else {
panic!("expected an assignment")
};
let ExprKind::With { base, arg, .. } = &rhs.kind else {
panic!("expected a with-expression, got {:?}", rhs.kind)
};
assert!(matches!(base.kind, ExprKind::Call { .. }));
assert!(matches!(arg.kind, ExprKind::Paren { .. }));
}
#[test]
fn the_comments_around_a_calls_brackets_and_a_with_are_kept() {
// QA round-1: four positions with no node of their own — before the
// `(`, inside an empty `()`, before `with`, and after it.
let f = parse_ok(
"module m;\n initial begin\n x = o.randomize /*c1*/ ( /*c2*/ ) /*c3*/ with /*c4*/ {\n y > 1;\n };\n end\nendmodule\n",
);
let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else {
panic!("expected an assignment")
};
let ExprKind::WithConstraint { base, comments, .. } = &rhs.kind else {
panic!("expected a with-constraint, got {:?}", rhs.kind)
};
assert_eq!(texts(&comments.before_kw), ["/*c3*/"]);
assert_eq!(texts(&comments.after_kw), ["/*c4*/"]);
let ExprKind::Call { comments, .. } = &base.kind else { panic!("expected a call") };
assert_eq!(texts(&comments.before_open), ["/*c1*/"]);
assert_eq!(texts(&comments.dangling), ["/*c2*/"]);
}
#[test]
fn an_argument_carries_its_own_comments_and_the_call_carries_none() {
// A list with elements has somewhere to put them, so the call's own
// slots stay empty — two homes for one comment would print it twice.
let f = parse_ok("module m;\n initial begin\n f( /*c*/ a);\n end\nendmodule\n");
let StmtKind::ExprStmt(e) = &initial_stmts(&f)[0].kind else {
panic!("expected an expression statement, got {:?}", initial_stmts(&f)[0].kind)
};
let ExprKind::Call { args, comments, .. } = &e.kind else { panic!("expected a call") };
assert!(comments.is_empty(), "the call kept comments the argument owns");
assert_eq!(texts(&args[0].meta.leading), ["/*c*/"]);
}
#[test]
fn a_with_that_opens_neither_a_paren_nor_a_brace_is_not_a_postfix_segment() {
// The stream expression's `with [range]` is still unsupported, and
// still fails where it always did rather than being mis-read.
assert!(
parse_err("module m;\n initial x = {<<{a with [0:1]}};\nendmodule\n").contains("with")
);
}
#[test]
fn a_foreach_splits_the_array_from_its_loop_variables() {
let f = parse_ok(
"module m;\n initial begin\n foreach (pkg::a[i].b[j]) x = 1;\n end\nendmodule\n",
);
let StmtKind::Foreach { target, vars, .. } = &initial_stmts(&f)[0].kind else {
panic!("expected a foreach")
};
// Everything before the last bracket group is the array.
assert!(matches!(target.kind, ExprKind::Member { .. }));
assert_eq!(vars.len(), 1);
assert_eq!(vars[0].text, "j");
}
#[test]
fn a_foreach_over_a_selected_array_keeps_the_select_on_the_array() {
let f = parse_ok(
"module m;\n initial begin\n foreach (a[i][j]) x = 1;\n end\nendmodule\n",
);
let StmtKind::Foreach { target, vars, .. } = &initial_stmts(&f)[0].kind else {
panic!("expected a foreach")
};
assert!(matches!(target.kind, ExprKind::Index { .. }));
assert_eq!(vars[0].text, "j");
}
#[test]
fn a_randcase_takes_case_items_without_a_selector() {
let f = parse_ok(
"module m;\n initial begin\n randcase\n 1: x = 0;\n 5: x = 1;\n endcase\n end\nendmodule\n",
);
let StmtKind::RandCase { items, .. } = &initial_stmts(&f)[0].kind else {
panic!("expected a randcase")
};
assert_eq!(items.len(), 2);
assert_eq!(items.iter().filter(|i| i.labels.is_empty()).count(), 0);
}
#[test]
fn wait_fork_is_a_statement_of_its_own_and_wait_expr_still_is_not() {
let f = parse_ok(
"module m;\n initial begin\n wait fork;\n wait (done);\n end\nendmodule\n",
);
let stmts = initial_stmts(&f);
assert!(matches!(stmts[0].kind, StmtKind::WaitFork));
assert!(matches!(stmts[1].kind, StmtKind::Wait { .. }));
}
#[test]
fn an_import_stands_among_a_blocks_declarations() {
let f = parse_ok(
"module m;\n initial begin\n import p::*;\n x = 1;\n end\nendmodule\n",
);
let StmtKind::Import(paths) = &initial_stmts(&f)[0].kind else {
panic!("expected an import statement")
};
assert_eq!(paths[0].pkg.text, "p");
assert_eq!(paths[0].item.text, "*");
}
#[test]
fn a_let_declaration_keeps_its_ports_and_its_value() {
let f = parse_ok("module m;\n let max(a, b) = (a > b) ? a : b;\nendmodule\n");
let ItemKind::Let(l) = &module_of(&f).items[0].kind else { panic!("expected a let") };
assert_eq!(l.name, "max");
assert!(l.has_parens);
assert_eq!(l.ports.len(), 2);
assert_eq!(l.ports[1].name, "b");
assert!(matches!(l.value.kind, ExprKind::Ternary { .. }));
}
#[test]
fn an_omitted_call_argument_is_an_empty_element_that_still_holds_its_place() {
let f = parse_ok("module m;\n initial x = f(a, , b);\nendmodule\n");
let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else {
panic!("expected an initial block")
};
let StmtKind::Assign { rhs, .. } = &stmt.kind else { panic!("expected an assignment") };
let ExprKind::Call { args, .. } = &rhs.kind else { panic!("expected a call") };
assert_eq!(args.len(), 3);
assert!(matches!(args[1].expr.kind, ExprKind::Empty(_)));
}
#[test]
fn a_statement_label_wraps_the_statement_it_names() {
let f = parse_ok(
"module m;\n initial begin\n chk: assert (a) x++; else y++;\n end\nendmodule\n",
);
let StmtKind::Labeled { name, stmt, .. } = &initial_stmts(&f)[0].kind else {
panic!("expected a labeled statement")
};
assert_eq!(name, "chk");
assert!(matches!(stmt.kind, StmtKind::Assert { .. }));
}
#[test]
fn a_label_before_a_concurrent_assertion_still_takes_the_verbatim_path() {
// The concurrent-assertion check runs first and swallows the label.
let f = parse_ok(
"module m;\n initial begin\n NoNMI: assert property (@(posedge c) a);\n end\nendmodule\n",
);
assert!(matches!(initial_stmts(&f)[0].kind, StmtKind::Verbatim(_)));
}
#[test]
fn a_stray_semicolon_after_a_footer_label_is_recorded_not_dropped() {
let f = parse_ok("class c;\n task t();\n endtask : t;\n function void g();\n endfunction\nendclass\n");
let ItemKind::Class(class) = &f.items[0].kind else { panic!("expected a class") };
let ItemKind::Task(t) = &class.items[0].kind else { panic!("expected a task") };
assert!(t.end_semi);
let ItemKind::Function(g) = &class.items[1].kind else { panic!("expected a function") };
assert!(!g.end_semi);
}
#[test]
fn a_comment_before_else_is_kept_on_the_keywords_left() {
let f = parse_ok(
"module m;\n initial\n if (a) x = 1;\n // why\n else x = 2;\nendmodule\n",
);
let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else {
panic!("expected an initial block")
};
let StmtKind::If { else_comments, els, .. } = &stmt.kind else { panic!("expected an if") };
assert_eq!(else_comments.len(), 1);
assert_eq!(else_comments[0].text, "// why");
// The else-branch itself did not also take the comment.
assert!(els.as_ref().expect("an else").meta.leading.is_empty());
}
// ------------------------------------------------------------------
// Split conditional regions (`docs/features/directive-split/README.md`)
// ------------------------------------------------------------------
/// The verbatim item a split conditional region collapsed into, with the
/// items that came before and after it, so every test can also assert
/// that nothing around the region was swallowed.
fn split_items(file: &SourceFile) -> Vec<String> {
file.items
.iter()
.map(|i| match &i.kind {
ItemKind::Verbatim(raw) => format!("verbatim:{}", raw.text),
ItemKind::Directive(raw) => format!("directive:{}", raw.text),
ItemKind::DataDecl(_) => "decl".to_string(),
ItemKind::ParamDecl(_) => "param".to_string(),
ItemKind::Typedef(_) => "typedef".to_string(),
_ => "other".to_string(),
})
.collect()
}
#[test]
fn alternative_declaration_heads_sharing_one_body_are_captured_verbatim() {
// corpus/ibex/vendor/google_riscv-dv/target/rv32imc/riscv_core_setting.sv:98
let src = "`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] \
= {\n`endif\n MVENDORID\n};\n\nparameter int AFTER = 1;\n";
let f = parse_ok(src);
let kinds = split_items(&f);
assert_eq!(kinds.len(), 3, "{kinds:?}");
assert_eq!(kinds[0], "directive:`ifdef DSIM");
assert_eq!(kinds[2], "param", "the item after the region was not swallowed");
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, src[raw.span.as_range()]);
assert!(raw.text.starts_with("privileged_reg_t"), "{:?}", raw.text);
assert!(raw.text.ends_with("};"), "{:?}", raw.text);
assert!(raw.text.contains("`else") && raw.text.contains("`endif"), "{:?}", raw.text);
}
#[test]
fn alternative_struct_bodies_sharing_one_closing_are_captured_verbatim() {
// corpus/ibex/vendor/google_riscv-dv/src/riscv_instr_pkg.sv:1236
let src = "package p;\n`ifdef _VCP\n typedef struct packed {\n bit l;\n`else\n \
typedef struct{\n rand bit l;\n`endif\n } pmp_cfg_reg_t;\n\n parameter \
int AFTER = 1;\nendpackage\n";
let f = parse_ok(src);
let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected package") };
assert_eq!(items.len(), 3, "{:?}", items.len());
let ItemKind::Verbatim(raw) = &items[1].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, src[raw.span.as_range()]);
assert!(raw.text.starts_with("typedef struct packed {"), "{:?}", raw.text);
assert!(raw.text.ends_with("} pmp_cfg_reg_t;"), "{:?}", raw.text);
assert!(matches!(items[2].kind, ItemKind::ParamDecl(_)), "the next item survived");
}
#[test]
fn an_ifndef_and_an_elsif_chain_are_the_same_shape() {
let src = "`ifndef A\nint x[] = {\n`elsif B\nconst int x[] = {\n`else\nstatic int x[] = \
{\n`endif\n 1\n};\n";
let f = parse_ok(src);
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") };
// Every arm is inside the one block, and only the first arm's `{` was
// counted -- otherwise the scan would still be looking for two more.
assert!(raw.text.contains("`elsif B") && raw.text.contains("`else"), "{:?}", raw.text);
assert!(raw.text.ends_with("};"), "{:?}", raw.text);
}
#[test]
fn a_balanced_region_inside_the_shared_tail_does_not_end_the_scan() {
let src = "`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n 1,\n`ifdef B\n \
2,\n`endif\n 3\n};\n\nparameter int AFTER = 1;\n";
let f = parse_ok(src);
let kinds = split_items(&f);
assert_eq!(kinds.len(), 3, "{kinds:?}");
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") };
assert!(raw.text.contains("`ifdef B"), "the nested region is inside: {:?}", raw.text);
assert_eq!(kinds[2], "param", "the item after the region was not swallowed");
}
#[test]
fn comments_inside_a_split_region_are_kept_and_the_one_after_it_is_not() {
let src = "// head\n`ifdef A // which\nint x[] = { // open\n`else // other\nconst int \
x[] = {\n`endif\n // why\n 1\n}; // done\nint y;\n";
let f = parse_ok(src);
assert_eq!(texts(&f.items[0].meta.leading), ["// head"]);
assert_eq!(
f.items[0].meta.trailing.as_ref().expect("`ifdef's own comment").text,
"// which"
);
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") };
for c in ["// open", "// other", "// why"] {
assert!(raw.text.contains(c), "{c} was dropped from {:?}", raw.text);
}
assert!(!raw.text.contains("// done"), "the trailing comment was swallowed");
assert_eq!(
f.items[1].meta.trailing.as_ref().expect("the comment survived").text,
"// done"
);
}
// -- the trigger refuses everything that is not a split ---------------
#[test]
fn a_plain_syntax_error_inside_a_complete_arm_is_still_an_error() {
// Both arms are whole declarations; the `= ;` is an ordinary typo
// that merely happens to sit inside a conditional region.
let msg = parse_err("`ifdef A\nwire x = ;\n`else\nwire x = 1;\n`endif\n");
assert!(msg.contains("expected expression"), "{msg}");
// ... and the same typo with a bracket open before it, so the only
// thing missing is the `else`/`endif` at the cursor.
let msg = parse_err("`ifdef A\nint x[] = {1, };\nwire y = ;\n`else\n`endif\n");
assert!(msg.contains("expected expression"), "{msg}");
}
#[test]
fn a_garbage_token_run_between_directives_is_still_an_error() {
let msg = parse_err("`ifdef A\n) ] }\n`else\n(\n`endif\n;\n");
assert!(msg.contains("expected item"), "{msg}");
let msg = parse_err("module m;\n`ifdef A\n = = =\n`else\n ;\n`endif\nendmodule\n");
assert!(!msg.is_empty(), "{msg}");
}
#[test]
fn an_unterminated_region_with_broken_code_is_still_an_error() {
// No `endif at all: the scan finds no end for the region and the
// original error stands.
let msg = parse_err("`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n 1\n};\n");
assert!(msg.contains("`else"), "{msg}");
// An `endif but no terminating `;` before the end of the file.
let msg = parse_err("`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n 1\n");
assert!(msg.contains("`else"), "{msg}");
}
#[test]
fn a_missing_semicolon_is_not_a_split() {
// The arm left no bracket open, so it is a fragment of nothing: the
// shape is indistinguishable from a forgotten `;` and is refused.
let msg = parse_err("`ifdef A\nwire x\n`else\nwire y\n`endif\n;\n");
assert!(msg.contains("`else"), "{msg}");
}
#[test]
fn a_stray_endif_is_never_a_split() {
// QA repro (2026-08-26): nothing opened a region, so the `endif
// closes nothing and the arm before it is a fragment of nothing.
// Recovering here would reformat invalid Verilog and exit 0.
let msg = parse_err("int x[] = {\n`endif\n1\n};\n");
assert!(msg.contains("expected expression") && msg.contains("`endif"), "{msg}");
let msg = parse_err("module m;\n int x[] = {\n`endif\n 1\n};\nendmodule\n");
assert!(msg.contains("`endif"), "{msg}");
}
#[test]
fn a_closed_region_does_not_leave_a_later_endif_something_to_close() {
// QA repro (2026-08-26): a legitimately closed region, then an
// accidental duplicate closer, then a bracket-opening declaration.
// The duplicate re-opens nothing, so the `else below is still stray.
let msg = parse_err(
"module m;\n`ifdef FOO\n wire a;\n`endif\n`endif\n int x[] = {\n`else\n const int \
x[] = {\n`endif\n 1\n};\nendmodule\n",
);
assert!(msg.contains("`else"), "{msg}");
}
#[test]
fn a_stray_endif_with_no_item_to_break_is_left_exactly_as_it_was() {
// lucisv has never validated directive nesting -- a lone `endif at
// item position is an ordinary `ItemKind::Directive`, before this
// work and after it. What matters is that no bracket-opening item
// near it gets swallowed into a verbatim block.
let f = parse_ok("wire a;\n`endif\nwire b;\n`endif\nint x[] = {1};\n");
let kinds = split_items(&f);
assert_eq!(
kinds,
["decl", "directive:`endif", "decl", "directive:`endif", "decl"],
"nothing was collapsed into a verbatim block"
);
}
#[test]
fn a_split_nested_inside_an_open_region_is_still_recovered() {
// The guard is "a region is live", not "exactly one region is live":
// both corpus shapes still recover when they sit inside an outer
// `ifdef that stays open across them.
let a = parse_ok(
"`ifdef OUTER\n`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst \
privileged_reg_t csr[] = {\n`endif\n MVENDORID\n};\n`endif\nparameter int AFTER = \
1;\n",
);
let ItemKind::Verbatim(raw) = &a.items[2].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("};"), "{:?}", raw.text);
// The outer region's own `endif is still its own directive item, and
// the item past it was not swallowed.
let kinds = split_items(&a);
assert_eq!(kinds[3], "directive:`endif", "{kinds:?}");
assert_eq!(kinds[4], "param", "{kinds:?}");
let b = parse_ok(
"package p;\n`ifdef OUTER\n`ifdef _VCP\n typedef struct packed {\n bit l;\n\
`else\n typedef struct{\n rand bit l;\n`endif\n } pmp_cfg_reg_t;\n`endif\n \
parameter int AFTER = 1;\nendpackage\n",
);
let ItemKind::Package { items, .. } = &b.items[0].kind else { panic!("expected package") };
let ItemKind::Verbatim(raw) = &items[2].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("} pmp_cfg_reg_t;"), "{:?}", raw.text);
assert!(matches!(items[4].kind, ItemKind::ParamDecl(_)), "the next item survived");
}
/// `Parser::open_conds` once the whole file has parsed. The invariant it
/// pins: this is the number of `` `ifdef ``/`` `ifndef `` regions opened
/// **at item scope** and not closed at item scope — nothing consumed
/// inside an opaque verbatim body may move it.
fn open_conds_after(src: &str) -> u32 {
let toks = tokenize(src).expect("lex error");
let mut p = Parser::new(toks, src, false);
p.parse_source_file().expect("parse error");
p.open_conds
}
#[test]
fn item_scope_conditional_nesting_ignores_opaque_bodies() {
// QA repro (2026-08-26, round 4): an unbalanced `ifdef written inside
// a construct lucisv keeps as opaque bytes used to leak into the
// file's item-scope nesting, because those bodies are walked token by
// token through `bump`. Every one of them must leave the count alone.
assert_eq!(open_conds_after("wire x;\n"), 0);
assert_eq!(open_conds_after("`ifdef A\nwire x;\n"), 1, "an item-scope region does count");
assert_eq!(open_conds_after("`ifdef A\nwire x;\n`endif\n"), 0);
for body in [
"class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n }\nendclass\n",
"covergroup cg;\n`ifdef FAKE\n cp: coverpoint x;\nendgroup\n",
"module m;\n property p;\n`ifdef FAKE\n a |-> b;\n endproperty\nendmodule\n",
"module m;\n assert property (\n`ifdef FAKE\n a |-> b);\nendmodule\n",
] {
assert_eq!(open_conds_after(body), 0, "an opaque body leaked: {body:?}");
}
}
#[test]
fn an_unbalanced_ifdef_inside_an_opaque_body_cannot_launder_a_later_stray_endif() {
// The end-to-end shape of the leak above: the polluted count used to
// make an unrelated stray `endif look like a live region's closer.
let msg = parse_err(
"class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n }\nendclass\nint y[] = \
{\n`endif\n1\n};\n",
);
assert!(msg.contains("`endif"), "{msg}");
let msg = parse_err(
"covergroup cg;\n`ifdef FAKE\n cp: coverpoint x;\nendgroup\nint y[] = \
{\n`endif\n1\n};\n",
);
assert!(msg.contains("`endif"), "{msg}");
let msg = parse_err(
"module m;\n property p;\n`ifdef FAKE\n a |-> b;\n endproperty\n int y[] = \
{\n`endif\n1\n};\nendmodule\n",
);
assert!(msg.contains("`endif"), "{msg}");
// Control: the same shape with the inner directive balanced. The tail
// is still a stray `endif with no live region, so it still refuses --
// the count was never the thing making the tail legal.
let msg = parse_err(
"class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n`endif\n }\nendclass\nint \
y[] = {\n`endif\n1\n};\n",
);
assert!(msg.contains("`endif"), "{msg}");
}
#[test]
fn suppressing_opaque_bodies_does_not_suppress_the_regions_around_them() {
// Over-suppression guard: balanced directives inside an opaque body,
// then a genuine split later in the same file.
let f = parse_ok(
"class c;\n constraint co {\n`ifdef X\n x < 10;\n`endif\n }\nendclass\n`ifdef \
DSIM\nint y[] = {\n`else\nconst int y[] = {\n`endif\n 1\n};\nparameter int AFTER = \
1;\n",
);
assert!(matches!(f.items[2].kind, ItemKind::Verbatim(_)), "{:?}", split_items(&f));
// Under-suppression guard: an earlier verbatim item (a constraint)
// inside the very region the split sits in.
let f = parse_ok(
"`ifdef OUTER\nclass c;\n constraint co {x < 10;}\nendclass\n`ifdef DSIM\nint y[] = \
{\n`else\nconst int y[] = {\n`endif\n 1\n};\n`endif\nparameter int AFTER = 1;\n",
);
let kinds = split_items(&f);
assert_eq!(kinds[3], "verbatim:int y[] = {\n`else\nconst int y[] = {\n`endif\n 1\n};");
assert_eq!(kinds[4], "directive:`endif");
assert_eq!(kinds[5], "param");
assert_eq!(open_conds_after(
"`ifdef OUTER\nclass c;\n constraint co {x < 10;}\nendclass\n`ifdef DSIM\nint y[] = \
{\n`else\nconst int y[] = {\n`endif\n 1\n};\n`endif\nparameter int AFTER = 1;\n"
), 0, "the recovered block accounted for the `endif it swallowed");
}
#[test]
fn a_recovered_block_leaves_the_right_nesting_behind_it() {
// The block swallows the region's own `endif, so the count has to come
// down with it -- otherwise the next `endif looks like it closes
// something and the stray after it gets laundered.
let src = "`ifdef OUTER\n`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n \
1\n};\n`endif\nparameter int AFTER = 1;\n";
assert_eq!(open_conds_after(src), 0);
let msg = parse_err(
"`ifdef OUTER\n`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n \
1\n};\n`endif\nint z[] = {\n`endif\n 1\n};\n",
);
assert!(msg.contains("`endif"), "{msg}");
// Two splits under one outer region both recover, and the outer region
// is still open between them.
let f = parse_ok(
"`ifdef OUTER\n`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n \
1\n};\n`ifdef B\nint y[] = {\n`else\nconst int y[] = {\n`endif\n \
2\n};\n`endif\nparameter int AFTER = 1;\n",
);
let kinds = split_items(&f);
assert_eq!(kinds.iter().filter(|k| k.starts_with("verbatim:")).count(), 2, "{kinds:?}");
assert_eq!(kinds[kinds.len() - 1], "param", "{kinds:?}");
}
#[test]
fn a_region_whose_arms_are_whole_items_still_parses_arm_by_arm() {
let f = parse_ok("`ifdef A\nwire x;\n`else\nwire y;\n`endif\n");
assert_eq!(
split_items(&f),
["directive:`ifdef A", "decl", "directive:`else", "decl", "directive:`endif"]
);
}
// ------------------------------------------------------------------
// directive-in-statements: a region opened *inside* a construct
// (`docs/features/directive-in-statements/README.md`)
// ------------------------------------------------------------------
#[test]
fn an_ifdef_splitting_an_assigns_rhs_is_captured_verbatim() {
// hw/top_earlgrey/dv/env/chip_if.sv:1189-1194, the anchor shape: each
// arm carries the construct's own `;`, so the block ends at the
// `endif -- there is no `;` after it to stop at.
let src = "module m;\n assign y =\n`ifdef GATE_LEVEL\n a.b.mr_rnd_ctr[3:0];\n`else\n a.b.rnd_ctr;\n`endif\n wire z;\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.starts_with("assign y ="), "{:?}", raw.text);
assert!(raw.text.ends_with("`endif"), "{:?}", raw.text);
assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived");
}
#[test]
fn an_ifdef_between_call_arguments_captures_the_statement_only() {
// hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:173. The region is
// balanced inside the call's parens, so the statement ends at its own
// `;` -- and the capture is the *statement*, not the enclosing
// function, which is what running the recovery at statement level
// buys.
let src = "module m;\n initial begin\n a.configure(\n .size(2),\n`ifdef USE_DMI\n .reset(32'h10),\n`else\n .reset(32'h07),\n`endif\n .has_reset(1));\n b = 1;\n end\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
let StmtKind::Verbatim(raw) = &stmts[0].kind else { panic!("expected a verbatim stmt") };
assert!(raw.text.starts_with("a.configure("), "{:?}", raw.text);
assert!(raw.text.ends_with(".has_reset(1));"), "{:?}", raw.text);
assert!(matches!(stmts[1].kind, StmtKind::Assign { .. }), "the next statement survived");
}
#[test]
fn an_ifdef_inside_an_instantiations_parameter_value_captures_the_instantiation() {
// hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv:621 -- a region
// between the elements of a concatenation, three brackets deep inside
// a parameter override. The `;` after the whole instantiation ends it.
let src = "module m;\n padring #(\n .PadType({\n A,\n`ifdef ANALOGSIM\n \
'0,\n`else\n CC2,\n`endif\n B\n })\n ) u_padring (\n \
.clk(c)\n );\n wire z;\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.starts_with("padring #("), "{:?}", raw.text);
assert!(raw.text.ends_with(");"), "{:?}", raw.text);
assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived");
}
#[test]
fn a_split_function_header_captures_through_endfunction() {
// hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:273. A `function`'s own
// `;` closes its *header*: stopping there left `super.new(...)` behind
// as an item and the file failed three lines into the body. The
// closing keyword, and the `: label` it may carry, end the block.
let src = "class c;\n function new(string name = \"\",\n`ifdef USE_DMI\n int unsigned n = 50,\n`else\n int unsigned n = 41,\n`endif\n int cov = 0);\n super.new(name, n, cov);\n endfunction : new\n int after;\nendclass\n";
let f = parse_ok(src);
let ItemKind::Class(c) = &f.items[0].kind else { panic!("expected a class") };
let ItemKind::Verbatim(raw) = &c.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.starts_with("function new("), "{:?}", raw.text);
assert!(raw.text.ends_with("endfunction : new"), "{:?}", raw.text);
assert!(matches!(c.items[1].kind, ItemKind::DataDecl(_)), "the next item survived");
}
#[test]
fn an_ifdef_that_splits_an_instantiation_head_is_still_the_closing_shape() {
// hw/top_earlgrey/dv/tb/tb.sv:113 (bucket 13): two instantiation heads
// behind one `ifdef sharing a connection list. The region opened
// *before* the item, so this is `at_split_conditional`'s shape -- what
// this round changed is that `take_list_directives` no longer harvests
// the `else as a list element and hides the seam.
let src = "module m;\n`ifdef DISABLE_ROM\n chip #(\n .Scramble(1'b1)\n ) dut \
(\n`else\n chip dut (\n`endif\n .POR_N(p),\n .USB_P(u)\n );\n wire \
z;\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
assert!(matches!(m.items[0].kind, ItemKind::Directive(_)), "the `ifdef stayed an item");
let ItemKind::Verbatim(raw) = &m.items[1].kind else { panic!("expected a verbatim block") };
assert!(raw.text.starts_with("chip #("), "{:?}", raw.text);
assert!(raw.text.ends_with(");"), "{:?}", raw.text);
assert!(matches!(m.items[2].kind, ItemKind::DataDecl(_)), "the next item survived");
}
#[test]
fn a_list_internal_region_is_still_harvested_as_list_elements() {
// The other side of the `take_list_directives` guard: a region opened
// *and* closed inside the connection list still conditions elements,
// and the instantiation still parses as an instantiation. Written
// inside an outer region, which is the state that arms the guard.
let src = "module m;\n`ifdef OUTER\n chip dut (\n .A(a),\n`ifdef ANALOGSIM\n \
.CC1(c1),\n`else\n .CC1(d1),\n`endif\n .B(b)\n );\n`endif\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Instantiation(inst) = &m.items[1].kind else {
panic!("expected an instantiation, got {:?}", split_items(&f))
};
assert_eq!(inst.instances[0].conn_directives.len(), 3, "`ifdef / `else / `endif harvested");
}
#[test]
fn an_opening_split_leaves_item_scope_nesting_alone() {
// Every exit of the extent scan has conditional nesting back at zero,
// so a captured block is conditional-balanced by construction.
assert_eq!(
open_conds_after(
"module m;\n assign y =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n"
),
0
);
assert_eq!(
open_conds_after(
"`ifdef OUTER\nmodule m;\n assign y =\n`ifdef A\n a;\n`else\n \
b;\n`endif\nendmodule\n"
),
1,
"the region around it is untouched"
);
}
#[test]
fn the_opening_split_refuses_everything_it_does_not_model() {
// Each of these reaches `at_opening_split` or `scan_opening_split_extent`
// and is handed its parse error back. Verified against the release
// binary on the real files as well; see the feature README.
for (why, src) in [
(
"a non-conditional directive is not a split",
"module m;\n assign y =\n`include \"x.vh\"\n a;\nendmodule\n",
),
("a stray closer opens nothing", "module m;\n assign y =\n`endif\n a;\nendmodule\n"),
("an unterminated region has no end", "module m;\n assign y =\n`ifdef A\n a;\n"),
(
"the construct never ends",
"module m;\n assign y =\n`ifdef A\n a\n`endif\nendmodule\n",
),
(
"a plain syntax error near a directive stays one",
"module m;\n`ifdef A\n assign y = ;\n`endif\nendmodule\n",
),
(
"brackets that do not balance across the arms",
"module m;\n assign y = (\n`ifdef A\n a;\n`else\n b);\n`endif\nendmodule\n",
),
(
"a body-opening head whose end is not modeled",
"module m;\n initial\n case (\n`ifdef A\n x\n`else\n \
y\n`endif\n )\n 1: a = 1;\n endcase\nendmodule\n",
),
] {
let toks = tokenize(src).expect("lex error");
assert!(parse(toks, src).is_err(), "should still refuse: {why}");
}
}
#[test]
fn a_comment_after_an_opening_bracket_is_not_stolen_by_an_inner_call() {
// The handshake `docs/features/formatter-bug-fixes/README.md` filed:
// `take_before_open` drained the whole pending queue, so a comment
// written after `if (` was printed between the condition's first
// callee and its own `(`. Both of the call's comment slots must now
// leave it queued for whoever owns the place it was written.
let src = "module m;\n initial begin\n if (// why\n !en() || b\n ) \
begin\n x = 1;\n end\n end\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
let StmtKind::If { cond, then, .. } = &stmts[0].kind else { panic!("expected an if") };
// Neither `before_open` (the `(` of `en(`) nor `dangling` (the inside
// of the empty `()`) may hold it.
let ExprKind::Binary { lhs, .. } = &cond.kind else { panic!("expected a binary") };
let ExprKind::Unary { expr, .. } = &lhs.kind else { panic!("expected a unary") };
let ExprKind::Call { comments, .. } = &expr.kind else { panic!("expected a call") };
assert!(comments.before_open.is_empty(), "{:?}", comments.before_open);
assert!(comments.dangling.is_empty(), "{:?}", comments.dangling);
// It stays queued and reaches the body's leading comments, which is
// where the formatter's `header_parens` takes it back from.
assert_eq!(then.meta.leading.len(), 1, "{:?}", then.meta.leading);
assert!(then.meta.leading[0].text.contains("why"));
}
#[test]
fn a_comment_actually_written_before_a_bracket_is_still_taken() {
// The other side of the same guard: `take_before_open` must keep
// doing its job for the comments written in the gap it owns.
let f = parse_ok("module m\n // why\n #(\n parameter int W = 1\n ) ();\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
assert_eq!(m.param_comments.len(), 1, "{:?}", m.param_comments);
assert!(m.param_comments[0].text.contains("why"));
let f = parse_ok("module m;\n initial x = f\n // why\n ();\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::Assign { rhs, .. } = &stmt.kind else { panic!("expected an assignment") };
let ExprKind::Call { comments, .. } = &rhs.kind else { panic!("expected a call") };
assert_eq!(comments.before_open.len(), 1, "{:?}", comments.before_open);
}
// ------------------------------------------------------------------
// QA (2026-08-29): adversarial coverage for directive-in-statements,
// none of which turned up a bug -- pinned so a future refactor of
// `scan_opening_split_extent`/`at_outer_arm_split` cannot silently
// regress any of them.
// ------------------------------------------------------------------
#[test]
fn a_nested_ifdef_with_its_own_elsif_survives_inside_an_opening_split_under_an_outer_region() {
// Three levels of conditional at once: an outer region already open
// when the item starts, an opening split inside the assign's RHS, and
// a *nested* `ifdef / `elsif / `else / `endif fully inside that
// split's first arm. The nested region's own arms must not be
// mistaken for the split's own `else / `endif, and `open_conds` must
// land back at 1 (the outer region only) once the whole thing is
// captured.
let src = "`ifdef OUTER\nmodule m;\n assign y =\n`ifdef A\n`ifdef NESTED\n a\n\
`elsif NESTED2\n a2\n`else\n a3\n`endif\n + 1;\n`elsif A2\n q;\n\
`else\n b;\n`endif\n wire z;\nendmodule\n";
let f = parse_ok(src);
assert_eq!(open_conds_after(src), 1, "the outer region is still open at eof");
// items[0] is the outer `ifdef OUTER` itself, a file-scope directive.
let ItemKind::Module(m) = &f.items[1].kind else { panic!("expected a module") };
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.starts_with("assign y ="), "{:?}", raw.text);
assert!(raw.text.contains("`ifdef NESTED"), "the nested region is inside the capture");
assert!(raw.text.ends_with("`endif"), "{:?}", raw.text);
assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived");
}
#[test]
fn an_elsif_chain_in_an_opening_split_is_captured_through_the_final_endif() {
// Only if/else was exercised elsewhere; a 4-arm chain must still end
// at the one closing `endif, not at an intermediate `elsif.
let src = "module m;\n assign y =\n`ifdef A\n a;\n`elsif B\n b;\n`elsif C\n \
c;\n`else\n d;\n`endif\n wire z;\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.contains("`elsif B") && raw.text.contains("`elsif C"), "{:?}", raw.text);
assert!(raw.text.ends_with("`endif"), "{:?}", raw.text);
assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived");
}
#[test]
fn a_block_comment_naming_endif_does_not_fool_the_extent_scan() {
// The extent scan walks tokens, not source text -- a comment is never
// a `TokenKind::Directive`, so text that merely *mentions* `endif
// inside a comment must not be mistaken for the real closer.
let src = "module m;\n assign y =\n`ifdef GATE_LEVEL\n /* not a real `endif here */ \
a;\n`else\n b;\n`endif\n wire z;\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.contains("not a real"), "{:?}", raw.text);
assert!(raw.text.ends_with("`endif"), "{:?}", raw.text);
assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived");
}
#[test]
fn an_opening_split_that_is_the_last_item_does_not_eat_the_closing_keyword() {
// No sibling item follows the split in either container -- the scan
// must stop at the split's own terminator and never wander into
// `endmodule`/`endclass`.
let module_src =
"module m;\n assign y =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n";
let f = parse_ok(module_src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
assert_eq!(m.items.len(), 1, "{:?}", split_items(&f));
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("`endif"), "{:?}", raw.text);
let class_src = "class c;\n function new();\n`ifdef A\n super.new(1);\n`else\n \
super.new(2);\n`endif\n endfunction\nendclass\n";
// The `ifdef here opens at a *statement-list* boundary (the function
// body's first statement), which is ordinary directive pass-through,
// not an opening split -- included as the sibling case that must
// stay a pass-through rather than being swept into this recovery.
let f = parse_ok(class_src);
let ItemKind::Class(c) = &f.items[0].kind else { panic!("expected a class") };
let ItemKind::Function(func) = &c.items[0].kind else { panic!("expected a function") };
assert!(
matches!(func.stmts[0].kind, StmtKind::Directive(_)),
"a directive starting a statement list is pass-through, not a split"
);
}
}