Files
lucisv/crates/vlog_parser/src/parser.rs
T
lucioandClaude Fable 5 4e62a14af6 Fragment mode and define continuation: the three .svh shapes that did not parse, and the define that was blamed on its class body
TODO section 22, coverage_gaps H4 corrected. Class-body and module-item
include fragments already parsed - the file-scope item loop is the
class-item loop. The three shapes that did not - a bare statement list,
an enum-member list (riscv-dv's CUSTOM_1, file, included between enum
members), a covergroup-item list - become SourceFile::fragment, detected
by a whole-file rule that cannot misfire on a valid file: the first
structural item failed (directives, macros and null items do not count;
a tolerant Ok that recorded a diagnostic counts as failed - an existing
parity test caught if/else reading as a generate-if to one parser and a
statement to the other), the file does not open with a design-unit
keyword, and a shape consumes the file to EOF, tried narrowest-first.
Each shape re-lexes a fresh token stream - Rewind does not restore the
tokens' comment buckets and the first draft lost comments on
non-fragment files. A fragment formats at indent zero through the
existing printers; its declarations bind; its enum variants are not
exported (pkg::CUSTOM_1 must not resolve to a name that does not
exist). FACTS stays 12.

The other .svh was never a fragment problem: a define whose formal
argument list spans two lines with no backslash. The lexer continues
such a directive until the list closes - incrementally, after QA found
the first cut quadratic on an unclosed list (20000 lines: 2.5 s ->
0.56 ms), pinned by a byte-visit counter.

Opentitan 12 -> 10 failing files, exactly the two predicted; corpus
813 -> 814 of 820; every remaining comment-gap failure proven to fail
identically outside a fragment.

docs/features/fragment-mode/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 07:34:31 -07:00

11674 lines
503 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",
"endprogram",
"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", "program", "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.
///
/// [`MAX_CHAIN_LENGTH`] is the other half of what has to fit: it bounds AST
/// depth the same way, and since 2026-08-29 it, not nesting, sets the peak.
///
/// Measured worst case for the full pipeline (tokenize → parse → analyze →
/// format → verify) over every nesting and chain family, on input sized to
/// trip a limit or to sit exactly at it: **~9.7 MiB unoptimized, ~0.8 MiB
/// optimized** — a maximal postfix chain inside statement nesting. 32 MiB is
/// that with 3.3× to spare, which is the margin this wants: unoptimized frame
/// sizes drift upward with the compiler — the nesting worst case measured
/// ~3.9 MiB in 2026-08 and ~5.9 MiB in 2026-08-28 on rustc 1.97 — and there
/// is no recoverable failure mode to fall back to.
///
/// Every thread that may reach a parse is spawned with at least this:
/// `std::thread::Builder::new().stack_size(PARSE_STACK_SIZE)`, or
/// `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 = 32 * 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 much larger than [`MAX_NESTING_DEPTH`] because a chain link is cheap
/// — ~9.2 KiB of stack per link in an unoptimized build against ~94 KiB for a
/// nested statement — and because long flat chains are the one deep shape real
/// RTL genuinely produces. 256 was not enough for real code: OpenTitan's
/// generated register files build one `|` chain per register file, and the
/// largest (`pinmux_reg_top.sv`) needs **567** links, so seven real files were
/// rejected. 1024 is 1.8× the largest chain the whole 3,943-file tree
/// contains, where only two files pass 512 and only seven pass 256.
///
/// Unlike raising [`MAX_NESTING_DEPTH`], raising this does not change which
/// *nesting* a file may use — but it is no longer free on the stack: at 1024
/// a maximal postfix chain peaks at ~9.4 MiB unoptimized, past the ~5.9 MiB
/// maximal nesting costs, so this limit now sets the worst case
/// [`PARSE_STACK_SIZE`] is measured against. See
/// `docs/features/recursion-limit/README.md`.
pub const MAX_CHAIN_LENGTH: u32 = 1024;
/// The three pieces a `#( parameter ... )` port list yields, so module and
/// class headers can share one parse.
#[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>,
/// Constraint bodies that did not fit the constraint grammar and were
/// captured verbatim instead; see [`SourceFile::constraint_fallbacks`].
constraint_fallbacks: u32,
/// Covergroups parsed into a [`ItemKind::Covergroup`], and covergroups
/// that did not fit the grammar and were captured verbatim instead; see
/// [`SourceFile::covergroups`].
covergroups: u32,
covergroup_fallbacks: u32,
/// While a covergroup bin's spec is being read, a postfix `with ( ... )`
/// is the **bin's** own filter (IEEE 1800 §19.5.1.1), not an array
/// method's iterator argument, so the expression parser must stop in
/// front of it. Set and cleared around that one operand, and never left
/// set on an error path.
no_with: bool,
}
/// Everything a speculative parse may move, so that a failed one can be put
/// back exactly where it started.
///
/// Only [`Parser::parse_constraint`], [`Parser::parse_with_constraint`] and
/// [`Parser::parse_covergroup`] use it, and only to retry the *same* bytes
/// down the pre-existing verbatim path. The token vector's own `leading` buckets are deliberately not
/// snapshotted: a retry that drained one has already decided to swallow those
/// bytes whole, and `verbatim_since` drops every comment that falls inside
/// the captured span.
struct Rewind {
pos: usize,
pending_leading: Vec<Comment>,
pending_trailing: Vec<Comment>,
depth: u32,
links: u32,
open_conds: u32,
diags: usize,
}
/// 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)
}
}
}
/// The three fragment shapes, in the order [`fragment_file`] tries them:
/// narrowest grammar first, so the shape that can only be one thing gets to
/// claim it before the shape that could read it as something else.
#[derive(Clone, Copy)]
enum Shape {
CoverItems,
EnumMembers,
Statements,
}
/// Design-unit keywords. A file that opens with one is a unit being written,
/// however broken the rest of it is, and is never re-read as a fragment — the
/// cheap guard that keeps mid-edit files off the retry path entirely.
const UNIT_OPENERS: &[&str] = &[
"module",
"macromodule",
"interface",
"program",
"package",
"class",
"primitive",
"checker",
"config",
"bind",
];
/// True for an item that says nothing about what kind of body it stands in: a
/// compiler directive, a macro invocation, a null `;`. All three are legal
/// wherever an item, a statement, an enum member or a cover item is, so a file
/// that has only these so far is still an open question.
fn is_prelude(kind: &ItemKind) -> bool {
matches!(kind, ItemKind::Directive(_) | ItemKind::MacroItem(_) | ItemKind::Empty)
}
/// Re-read `source` as a fragment: a whole file that is the bare middle of
/// some larger construct's body, `` `include``d at exactly that point.
///
/// Reached only when the file's **first** item failed to parse, so nothing
/// that is an item list today can change shape. A shape wins only if it
/// consumes the file to end of file, trailing comments included.
///
/// The shapes are tried narrowest first — cover items, enum members,
/// statements — because the wider grammars can read the narrower ones as
/// something else and would then bind the wrong symbols. `cp: coverpoint a;`
/// is a labelled `coverpoint a` declaration to the statement grammar and
/// `option.weight = 5;` is an assignment to it; an enum-member list is never a
/// statement list, because a statement ends at a `;` and a member list stops
/// in front of one. So the order is not a tie-break between equals: it is the
/// rule that the most specific reading of the same bytes wins.
///
/// Each shape gets its own freshly-lexed token stream rather than a rewind,
/// because a `Rewind` deliberately does not restore the tokens' own comment
/// buckets (see [`Rewind`]) and a fragment — unlike the verbatim captures the
/// rewind serves — has to print every comment back where it was written. The
/// re-lex costs nothing that matters: it only ever runs on a file whose first
/// item is already broken, and the guard above keeps design units out.
fn fragment_file(source: &str) -> Option<SourceFile> {
let tokens = crate::tokenize(source).ok()?;
if tokens
.first()
.is_some_and(|t| t.kind == TokenKind::Keyword && UNIT_OPENERS.contains(&t.text.as_str()))
{
return None;
}
for shape in [Shape::CoverItems, Shape::EnumMembers, Shape::Statements] {
// A clone rather than the same vector, for the reason above; strict in
// both modes, for the reason in [`Parser::read_fragment`].
if let Some(file) = Parser::new(tokens.clone(), source, false).read_fragment(shape) {
return Some(file);
}
}
None
}
/// 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,
constraint_fallbacks: 0,
covergroups: 0,
covergroup_fallbacks: 0,
fragment: None,
}
}
/// 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,
}
/// True when `t` is a plain identifier spelling exactly `word`.
///
/// The constraint sub-grammar's four operator words — `soft`, `dist`,
/// `solve`, `before` — are read through this rather than reserved in
/// `token.rs`, the way `restrict` is: see
/// `docs/features/constraint-bodies/README.md`.
fn word_at(t: &Token, word: &str) -> bool {
t.kind == TokenKind::Ident && t.text == word
}
/// Which of the three bins keywords `t` spells, if any. All three are matched
/// by text rather than reserved, for the reason [`word_at`] gives.
fn bin_kind_at(t: &Token) -> Option<BinKind> {
if t.kind != TokenKind::Ident {
return None;
}
match t.text.as_str() {
"bins" => Some(BinKind::Bins),
"ignore_bins" => Some(BinKind::IgnoreBins),
"illegal_bins" => Some(BinKind::IllegalBins),
_ => None,
}
}
/// 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(),
constraint_fallbacks: 0,
covergroups: 0,
covergroup_fallbacks: 0,
no_with: false,
}
}
/// Snapshot the state a speculative parse may move. See [`Rewind`].
fn rewind_mark(&self) -> Rewind {
Rewind {
pos: self.pos,
pending_leading: self.pending_leading.clone(),
pending_trailing: self.pending_trailing.clone(),
depth: self.depth,
links: self.links,
open_conds: self.open_conds,
diags: self.diagnostics.len(),
}
}
/// Put the parser back where [`Parser::rewind_mark`] was taken.
fn rewind_to(&mut self, mark: Rewind) {
self.pos = mark.pos;
self.pending_leading = mark.pending_leading;
self.pending_trailing = mark.pending_trailing;
self.depth = mark.depth;
self.links = mark.links;
self.open_conds = mark.open_conds;
self.diagnostics.truncate(mark.diags);
}
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();
// The first item that carries structure decides what kind of file this
// is. One that parses settles it: this is an item list — a design
// unit, a package, a class body, a run of module items — and nothing
// re-reads it as anything else. One that fails is the only door to
// fragment mode; see [`fragment_file`]. Directives, macro invocations
// and null items do not settle it, because they are legal in *every*
// body, and a fragment routinely opens with one (`` `ifdef `` around
// the enum members it contributes).
let mut prelude_only = true;
while !self.at_eof() {
let start_pos = self.pos;
let start = self.here();
let diags_before = self.diagnostics.len();
match self.parse_item() {
Ok(item) => {
// A tolerant parse that recovered *inside* the item did not
// read it, it patched it — and the strict parse of the same
// bytes failed outright. Both must ask the fragment
// question at the same point or the editor would report
// errors on a file the formatter formats: `if (a) begin x =
// 1; end` is a generate-if whose body holds a statement.
let patched = self.diagnostics.len() > diags_before;
if prelude_only && patched {
if let Some(file) = fragment_file(self.source) {
self.diagnostics.truncate(diags_before);
return Ok(file);
}
}
prelude_only &= is_prelude(&item.kind) && !patched;
items.push(item);
}
Err(e) => {
if prelude_only {
if let Some(file) = fragment_file(self.source) {
self.diagnostics.truncate(diags_before);
return Ok(file);
}
}
if !self.tolerant {
return Err(e);
}
// Exactly what `item_or_recover` would have done, on the
// cursor the failure left behind — re-running the item to
// get there would move the comments it already drained.
// Asked once: a file that is not a fragment stays one.
prelude_only = false;
let raw = self.recover(start_pos, start, e);
let span = raw.span;
items.push(Item { meta: Meta::default(), kind: ItemKind::Error(raw), span });
}
}
}
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,
constraint_fallbacks: self.constraint_fallbacks,
covergroups: self.covergroups,
covergroup_fallbacks: self.covergroup_fallbacks,
fragment: None,
})
}
/// Read the whole file as `shape`, and only accept it if the shape
/// consumed every token.
///
/// Nothing here recovers, in either mode: a shape that does not fit must
/// fail so the next one gets its turn, and a file that fits none keeps the
/// single error node — and the single diagnostic — a broken file has
/// always had.
fn read_fragment(&mut self, shape: Shape) -> Option<SourceFile> {
let fragment = match shape {
Shape::Statements => self.parse_stmts_to_eof().ok().map(Fragment::Statements)?,
Shape::EnumMembers => {
let (members, directives) = self.parse_enum_members(true).ok()?;
Fragment::EnumMembers { members, directives }
}
Shape::CoverItems => self.parse_cover_items(true).ok().map(Fragment::CoverItems)?,
};
if !self.at_eof() {
return None;
}
Some(SourceFile {
items: Vec::new(),
// Comments after the last element land in the slot they hold for
// every other file.
dangling: self.take_dangling(),
span: TextRange::new(0, self.cur().span.end),
constraint_fallbacks: self.constraint_fallbacks,
covergroups: self.covergroups,
covergroup_fallbacks: self.covergroup_fallbacks,
fragment: Some(fragment),
})
}
/// Statements up to end of file: the body of a statement fragment.
fn parse_stmts_to_eof(&mut self) -> PResult<Vec<Stmt>> {
let mut stmts = Vec::new();
while !self.at_eof() {
stmts.push(self.parse_stmt()?);
}
Ok(stmts)
}
/// 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()?));
}
// A null item. Nothing else in the item grammar starts with `;`, so
// one token settles it — and it is tested here rather than in the
// `TokenKind` match below because punctuation is matched by text
// everywhere in this file. See `ItemKind::Empty`.
if self.cur().is_sym(";") {
self.bump();
return Ok(ItemKind::Empty);
}
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)
}
// A `program` block is a module header over a module body with a
// different closer (IEEE 1800 §24.3) — the same node, the way an
// `interface` already is. Its stricter *legality* rules (no
// `always`, no instantiation of anything but interfaces) are a
// checker's business, not a formatter's.
"program" => self.parse_module("endprogram").map(ItemKind::Module),
"modport" => self.parse_modport().map(ItemKind::Modport),
"clocking" => self.parse_clocking(false).map(ItemKind::Clocking),
"default" if self.nth(1).is_kw("clocking") => {
self.bump();
self.parse_clocking(true).map(ItemKind::Clocking)
}
"default" if self.nth(1).is_kw("disable") => {
self.parse_default_disable().map(ItemKind::Verbatim)
}
"package" => self.parse_package(),
"import" => {
// A string right after `import` is a DPI linkage spec, not a
// 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(),
"covergroup" => self.parse_covergroup(),
"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(),
"covergroup" => self.parse_covergroup(),
_ => 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),
})
}
/// `[qualifiers] constraint [cls::]name { ... }` — or its `constraint c;`
/// prototype (IEEE 1800 §18.5).
///
/// The body is **parsed**: see [`Parser::parse_constraint_set`]. A body
/// that does not fit the constraint grammar rewinds and is captured
/// exactly as every constraint was before this round —
/// `skip_balanced` over the braces, source bytes copied out by span, an
/// [`ItemKind::Verbatim`] leaf whose `col` re-indent contract the
/// formatter already honours. That fallback is what keeps this round
/// tolerant by construction: the sub-grammar is large and half of it is
/// written through macros lucisv does not expand, so the shapes real DV
/// code writes are modelled and everything else still formats byte for
/// byte and round-trips.
///
/// The name may carry a `my_class::` scope — the out-of-block definition
/// of an `extern constraint` prototype (IEEE 1800 §18.5.2), written at
/// file or package scope, the constraint sibling of
/// `function my_class::method(...)` — so it reuses the same scoped-name
/// path. Unlike before, both halves are now kept.
fn parse_constraint(&mut self) -> PResult<ItemKind> {
let mark = self.rewind_mark();
match self.parse_constraint_decl() {
Ok(decl) => Ok(ItemKind::Constraint(decl)),
Err(_) => {
self.rewind_to(mark);
self.constraint_fallbacks += 1;
self.parse_constraint_verbatim().map(ItemKind::Verbatim)
}
}
}
fn parse_constraint_decl(&mut self) -> PResult<ConstraintDecl> {
let qualifiers = self.take_member_prefix();
self.expect_kw("constraint")?;
let before_name = self.take_gap();
let (scope, name) = self.parse_method_name()?;
let after_name = self.take_gap();
if self.eat_sym(";") {
return Ok(ConstraintDecl {
qualifiers,
scope,
name,
before_name,
after_name,
body: None,
before_semi: Vec::new(),
semi: true,
});
}
let body = self.parse_constraint_block()?;
// `constraint c { ... };` — a stray `;` is legal and belongs to the
// block, not to the item that follows it. The gap before it is only
// this item's when the `;` is really there; otherwise the comments
// belong to whatever comes next.
let before_semi = self.gap_before(";");
let semi = self.eat_sym(";");
Ok(ConstraintDecl {
qualifiers,
scope,
name,
before_name,
after_name,
body: Some(body),
before_semi,
semi,
})
}
/// [`Parser::take_gap`], but only when the cursor really is on `sym` —
/// the gap belongs to this construct only if the token that closes it was
/// written. [`Parser::take_before_open`] is the same idea; this is it
/// spelled for a closer rather than an opener.
fn gap_before(&mut self, sym: &str) -> Vec<Comment> {
if self.cur().is_sym(sym) {
self.take_gap()
} else {
Vec::new()
}
}
/// The pre-`constraint-bodies` capture, unchanged, byte for byte: the
/// fallback [`Parser::parse_constraint`] rewinds into, and the reason a
/// constraint the grammar does not know still parses, formats and
/// round-trips exactly as it did in v0.26.0.
fn parse_constraint_verbatim(&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("{", "}")?;
self.eat_sym(";");
}
Ok(self.verbatim_since(start, col))
}
/// A braced `{ constraint_item* }`. Gated, like every other body.
fn parse_constraint_block(&mut self) -> PResult<ConstraintSet> {
self.enter()?;
let out = self.parse_constraint_block_inner();
self.leave();
out
}
fn parse_constraint_block_inner(&mut self) -> PResult<ConstraintSet> {
let start = self.here();
self.expect_sym("{")?;
let mut items = Vec::new();
while !self.cur().is_sym("}") {
if self.at_eof() {
return self.error("expected `}`");
}
items.push(self.parse_constraint_item()?);
}
let dangling = self.take_dangling();
self.expect_sym("}")?;
Ok(ConstraintSet { braced: true, items, dangling, span: self.span_from(start) })
}
/// A `constraint_set` (IEEE 1800 A.1.10): `{ ... }`, or the single
/// unbraced item an implication's right-hand side and a constraint `if`
/// body may also be written as.
fn parse_constraint_set(&mut self) -> PResult<ConstraintSet> {
if self.cur().is_sym("{") {
return self.parse_constraint_block();
}
let start = self.here();
self.enter()?;
let item = self.parse_constraint_item();
self.leave();
Ok(ConstraintSet {
braced: false,
items: vec![item?],
dangling: Vec::new(),
span: self.span_from(start),
})
}
fn parse_constraint_item(&mut self) -> PResult<ConstraintItem> {
let start = self.here();
let mut meta = self.take_meta();
let kind = self.parse_constraint_item_kind()?;
// One place owns the terminating `;`, so one place owns the gap in
// front of it: a comment written there prints on the item's side of
// the `;`, which is where the source put it.
let mut before_semi = Vec::new();
if kind.takes_semi() {
before_semi = self.take_gap();
self.expect_sym(";")?;
}
let span = self.span_from(start);
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(ConstraintItem { meta, kind, before_semi, span })
}
fn parse_constraint_item_kind(&mut self) -> PResult<ConstraintItemKind> {
// A directive keeps the posture it keeps at item and statement
// position: passed through, never evaluated, both arms of an
// `` `ifdef `` left standing as ordinary items of the one set.
if self.cur().kind == TokenKind::Directive {
return Ok(ConstraintItemKind::Directive(self.take_raw_text()));
}
if self.eat_sym(";") {
return Ok(ConstraintItemKind::Empty);
}
if self.cur().is_kw("if") {
return self.parse_constraint_if();
}
if self.cur().is_kw("foreach") {
return self.parse_constraint_foreach();
}
if self.cur().is_kw("unique") && self.nth(1).is_sym("{") {
self.bump();
let comments = self.take_gap();
let items = self.parse_constraint_expr_set()?;
return Ok(ConstraintItemKind::Unique { items, comments });
}
// `disable soft x;` (IEEE 1800 §18.5.14.1). `disable` is a keyword;
// `soft` is matched by text, for the reason `parse_constraint_expr`
// gives.
if self.cur().is_kw("disable") && word_at(self.nth(1), "soft") {
self.bump();
let before = self.take_gap();
self.bump();
let after = self.take_gap();
let expr = self.parse_expr()?;
return Ok(ConstraintItemKind::DisableSoft {
expr,
comments: Box::new(BinaryComments { before, after }),
});
}
if self.at_solve_before() {
return self.parse_solve_before();
}
self.parse_constraint_expr()
}
/// `[soft ]expression_or_dist ;` and `expression -> constraint_set`.
///
/// `soft` and `dist` are matched **by text**, not as lexer keywords, for
/// the reason `restrict` is (`at_concurrent_assertion`): reserving four
/// more words would make every file that spells one as an identifier stop
/// parsing, and inside a constraint body their position leaves no other
/// reading. See `docs/features/constraint-bodies/README.md`.
fn parse_constraint_expr(&mut self) -> PResult<ConstraintItemKind> {
let soft = self.at_soft_constraint();
let mut after_soft = Vec::new();
if soft {
self.bump();
after_soft = self.take_gap();
}
let mark = self.pending_trailing.len();
let start = self.here();
// `parse_ternary`, not `parse_expr`: the implication level is read
// here, because a constraint `->`'s right-hand side may be a braced
// set, which is not an expression.
let mut expr = self.parse_ternary()?;
if self.at_dist() {
let before = self.take_gap();
expr = self.parse_dist(start, expr, before)?;
} else {
// `<->` is an ordinary operator whose right-hand side is always an
// expression, so it stays in the expression. Only `->` may take a
// set.
while self.cur().is_sym("<->") {
let before = self.take_around(mark);
let op = self.bump().text;
let after = self.take_around(mark);
let rhs = self.parse_ternary()?;
expr = self.expr_at(
start,
ExprKind::Binary {
lhs: Box::new(expr),
op,
rhs: Box::new(rhs),
comments: Box::new(BinaryComments { before, after }),
},
);
}
if !soft && self.cur().is_sym("->") {
let before = self.take_around(mark);
self.bump();
let after = self.take_around(mark);
let set = self.parse_constraint_set()?;
return Ok(ConstraintItemKind::Implication {
cond: expr,
comments: Box::new(BinaryComments { before, after }),
set,
});
}
}
Ok(ConstraintItemKind::Expr { soft, after_soft, expr })
}
/// `if ( expr ) constraint_set [ else constraint_set ]`.
fn parse_constraint_if(&mut self) -> PResult<ConstraintItemKind> {
self.expect_kw("if")?;
let mut comments = HeaderComments { after_kw: self.take_gap(), ..Default::default() };
self.expect_sym("(")?;
comments.after_open = self.take_gap();
let cond = self.parse_expr()?;
comments.before_close = self.gap_before(")");
self.expect_sym(")")?;
comments.before_body = self.gap_before("{");
let then = self.parse_constraint_set()?;
let mut else_comments = Vec::new();
let mut after_else = Vec::new();
let mut els = None;
if self.cur().is_kw("else") {
else_comments = self.take_dangling();
self.bump();
// The gap after `else` is this item's when the set it introduces
// opens with a token of its own — a `{`, or the `if` of a chain.
// A set written on the next line leaves it to that item's own
// leading comments, which is where the source's line break
// already put it.
after_else = if self.cur().is_sym("{") || self.cur().is_kw("if") {
self.take_gap()
} else {
Vec::new()
};
els = Some(Box::new(self.parse_constraint_set()?));
}
Ok(ConstraintItemKind::If {
cond,
comments: Box::new(comments),
then,
else_comments,
after_else,
els,
})
}
/// `foreach ( array [ i, j ] ) constraint_set`. The header is the
/// statement `foreach`'s, so it reuses that parse — a skipped dimension
/// is an empty-text `Name` there too.
fn parse_constraint_foreach(&mut self) -> PResult<ConstraintItemKind> {
self.expect_kw("foreach")?;
let mut comments = HeaderComments { after_kw: self.take_gap(), ..Default::default() };
self.expect_sym("(")?;
comments.after_open = self.take_gap();
let (array, vars) = self.parse_foreach_target()?;
comments.before_close = self.gap_before(")");
self.expect_sym(")")?;
comments.before_body = self.gap_before("{");
let set = self.parse_constraint_set()?;
Ok(ConstraintItemKind::Foreach { array, vars, comments: Box::new(comments), set })
}
/// True when the cursor opens `solve a, b before c, d;`. Both words are
/// matched by text; `solve` only counts when a name follows it, so a
/// signal called `solve` compared to something else is still an ordinary
/// expression.
fn at_solve_before(&self) -> bool {
word_at(self.cur(), "solve") && self.nth(1).kind == TokenKind::Ident
}
fn parse_solve_before(&mut self) -> PResult<ConstraintItemKind> {
self.bump(); // solve
let solve = self.parse_solve_operands()?;
if !word_at(self.cur(), "before") {
return self.error("expected `before`");
}
let before_comments = self.take_gap();
self.bump();
let before = self.parse_solve_operands()?;
Ok(ConstraintItemKind::SolveBefore { solve, before_comments, before })
}
/// The comma-separated operand list on either side of `before`.
///
/// It deliberately does **not** claim the gap in front of the item's
/// `;`: [`Parser::parse_constraint_item`] owns that for every kind, and
/// two owners would mean two places to get it wrong.
fn parse_solve_operands(&mut self) -> PResult<Vec<ExprItem>> {
let mut out: Vec<ExprItem> = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let expr = self.parse_ternary()?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
out.push(ExprItem { meta, expr, span });
if !more {
break;
}
}
Ok(out)
}
/// True when a `dist { ... }` set follows the expression just parsed.
/// Both the word and the brace are demanded, which is what makes reading
/// `dist` as an operator unambiguous without reserving it.
fn at_dist(&self) -> bool {
word_at(self.cur(), "dist") && self.nth(1).is_sym("{")
}
/// True when `soft` at the cursor opens a soft constraint rather than
/// naming something. It does exactly when a term follows it — a name, a
/// literal, a `(`, a `{`, or a unary `!`/`~` — which no infix position
/// can produce.
fn at_soft_constraint(&self) -> bool {
if !word_at(self.cur(), "soft") {
return false;
}
let next = self.nth(1);
match next.kind {
TokenKind::Ident | TokenKind::SystemIdent | TokenKind::Number | TokenKind::String => {
true
}
TokenKind::Symbol => matches!(next.text.as_str(), "(" | "{" | "!" | "~"),
_ => false,
}
}
/// `expr dist { value_range [ := | :/ weight ], ... }` (IEEE 1800 §18.5.4).
fn parse_dist(&mut self, start: u32, expr: Expr, before: Vec<Comment>) -> PResult<Expr> {
self.bump(); // dist
let after = self.take_gap();
self.expect_sym("{")?;
let mut weights: Vec<DistItem> = Vec::new();
loop {
let item_start = self.here();
let mut meta = self.take_meta();
let value = self.parse_range_or_expr()?;
let mut op = None;
let mut weight = None;
let mut op_comments = BinaryComments::default();
if let Some(spelling) = self.dist_weight_op() {
op_comments.before = self.take_gap();
self.bump();
self.bump();
op_comments.after = self.take_gap();
op = Some(spelling.to_string());
weight = Some(self.parse_ternary()?);
}
let span = self.span_from(item_start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
weights.push(DistItem {
meta,
value,
op,
op_comments: Box::new(op_comments),
weight,
span,
});
if !more {
break;
}
}
if let Some(last) = weights.last_mut() {
self.take_before_sep(&mut last.meta, "}");
}
self.expect_sym("}")?;
Ok(self.expr_at(
start,
ExprKind::Dist {
expr: Box::new(expr),
comments: Box::new(BinaryComments { before, after }),
weights,
},
))
}
/// The `:=` or `:/` of a `dist` weight, at the cursor.
///
/// Both are lexed as **two** tokens, because the lexer's operator table
/// deliberately does not join them: a `:/` entry would swallow the `/*`
/// of `cond ? a :/* why */ b`, and a `:=` entry would buy nothing
/// anywhere else in the language. Adjacency is checked by span, so a
/// `0 : = 5` written with a space is not one and falls back with the rest
/// of the body.
fn dist_weight_op(&self) -> Option<&'static str> {
if !self.cur().is_sym(":") {
return None;
}
let end = self.cur().span.end;
let next = self.nth(1);
if next.span.start != end {
return None;
}
match next.text.as_str() {
"=" if next.kind == TokenKind::Symbol => Some(":="),
"/" if next.kind == TokenKind::Symbol => Some(":/"),
_ => None,
}
}
/// The `{ a, [lo:hi], c }` element list an `inside`-style set is written
/// with: what `unique` takes, and what one `dist` weight's value may be.
fn parse_constraint_expr_set(&mut self) -> PResult<Vec<ExprItem>> {
self.expect_sym("{")?;
let mut items: Vec<ExprItem> = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let expr = self.parse_range_or_expr()?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
items.push(ExprItem { meta, expr, span });
if !more {
break;
}
}
if let Some(last) = items.last_mut() {
self.take_before_sep(&mut last.meta, "}");
}
self.expect_sym("}")?;
Ok(items)
}
/// `[lo:hi]` or an ordinary expression — the `value_range` of a `dist`
/// item or a `unique` list, spelled exactly as an `inside` set's is.
fn parse_range_or_expr(&mut self) -> PResult<Expr> {
if self.cur().is_sym("[") {
return self.parse_value_range();
}
self.parse_ternary()
}
/// The `{ ... }` of a `randomize() with { ... }` inline constraint
/// (IEEE 1800 §18.7).
///
/// It is a `constraint` body written inside an expression, so it gets
/// exactly the same treatment: the constraint grammar first, and the
/// pre-round byte-for-byte capture as the fallback. 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<ConstraintBody> {
let mark = self.rewind_mark();
if let Ok(set) = self.parse_constraint_block() {
return Ok(ConstraintBody::Items(set));
}
self.rewind_to(mark);
self.constraint_fallbacks += 1;
let start = self.here();
let col = self.cur().col;
self.expect_sym("{")?;
self.skip_balanced("{", "}")?;
Ok(ConstraintBody::Verbatim(self.verbatim_since(start, col)))
}
/// `[qualifiers] covergroup name [(args)] [coverage_event]; ... endgroup
/// [: label]` (IEEE 1800 §19.3).
///
/// The body is **parsed**, exactly as a constraint's is since round 1 of
/// this wave: coverpoints, crosses, bins and options become real nodes, so
/// a rename of a sampled property reaches `coverpoint addr` and `cg.cp` is
/// a name that resolves. A covergroup that does not fit the grammar
/// rewinds and is captured exactly as every covergroup was before this
/// round — the flat token scan to `endgroup`, source bytes copied out by
/// span, an [`ItemKind::Verbatim`] leaf whose `col` re-indent contract the
/// formatter already honours. See
/// `docs/features/covergroup-bodies/README.md`.
fn parse_covergroup(&mut self) -> PResult<ItemKind> {
let mark = self.rewind_mark();
match self.parse_covergroup_decl() {
Ok(decl) => {
self.covergroups += 1;
Ok(ItemKind::Covergroup(Box::new(decl)))
}
Err(_) => {
self.rewind_to(mark);
self.covergroup_fallbacks += 1;
self.parse_covergroup_verbatim().map(ItemKind::Verbatim)
}
}
}
/// The pre-`covergroup-bodies` capture, unchanged, byte for byte: the
/// fallback [`Parser::parse_covergroup`] rewinds into, and the reason a
/// covergroup the grammar does not know still parses, formats and
/// round-trips exactly as it did in v0.27.0.
fn parse_covergroup_verbatim(&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))
}
/// A covergroup body. Gated, like every other body.
fn parse_covergroup_decl(&mut self) -> PResult<CovergroupDecl> {
self.enter()?;
let out = self.parse_covergroup_decl_inner();
self.leave();
out
}
fn parse_covergroup_decl_inner(&mut self) -> PResult<CovergroupDecl> {
let qualifiers = self.take_member_prefix();
self.expect_kw("covergroup")?;
let before_name = self.take_gap();
let name = self.expect_name()?;
let before_args = self.take_before_open("(");
let args = if self.cur().is_sym("(") { Some(self.parse_tf_ports()?) } else { None };
let event = self.parse_coverage_event()?;
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
let items = self.parse_cover_items(false)?;
let dangling = self.take_dangling();
// Strict, not [`Parser::expect_closer`]: an unclosed covergroup must
// *fail* here so the rewind puts the old flat scan back, which is what
// records the tolerant diagnostic — one message, from one place, and
// the same one v0.27.0 wrote.
self.expect_kw("endgroup")?;
let end_label = self.parse_label()?;
let before_end_semi = self.gap_before(";");
let end_semi = self.eat_sym(";");
Ok(CovergroupDecl {
qualifiers,
before_name,
name,
before_args,
args,
event,
before_semi,
items,
dangling,
end_label,
before_end_semi,
end_semi,
})
}
/// A covergroup's item list — coverpoints, crosses, options, directives.
///
/// Stops on `endgroup`; end of file before one is an error, which is what
/// makes an unclosed covergroup rewind to the verbatim capture rather than
/// swallow the rest of the file. `to_eof` swaps that closer for end of
/// file, which is a cover-item fragment.
fn parse_cover_items(&mut self, to_eof: bool) -> PResult<Vec<CoverItem>> {
let mut items = Vec::new();
loop {
if self.at_eof() {
if to_eof {
break;
}
return self.error("expected `endgroup`");
}
if !to_eof && self.cur().is_kw("endgroup") {
break;
}
items.push(self.parse_cover_item()?);
}
Ok(items)
}
/// The `coverage_event` of a covergroup header: `with function sample
/// (...)` or a clocking event. `sample` is matched by text, for the
/// reason `soft` and `dist` are.
fn parse_coverage_event(&mut self) -> PResult<Option<CoverageEvent>> {
if self.cur().is_kw("with") {
let before_with = self.take_gap();
self.bump();
let after_with = self.take_gap();
self.expect_kw("function")?;
let after_function = self.take_gap();
if !word_at(self.cur(), "sample") {
return self.error("expected `sample`");
}
let name = Name { text: self.cur().text.clone(), span: self.cur().span };
self.bump();
let before_args = self.take_before_open("(");
let has_parens = self.cur().is_sym("(");
let args = self.parse_tf_ports()?;
return Ok(Some(CoverageEvent::Sample(Box::new(SampleFn {
before_with,
after_with,
after_function,
name,
before_args,
has_parens,
args,
}))));
}
if self.cur().is_sym("@") {
let before = self.take_gap();
self.bump();
let sens = self.parse_sens_list()?;
return Ok(Some(CoverageEvent::Clocking { before, sens }));
}
Ok(None)
}
fn parse_cover_item(&mut self) -> PResult<CoverItem> {
let start = self.here();
let mut meta = self.take_meta();
let kind = self.parse_cover_item_kind()?;
// One place owns the terminating `;`, so one place owns the gap in
// front of it — the rule `parse_constraint_item` states.
let mut before_semi = Vec::new();
if kind.takes_semi() {
before_semi = self.take_gap();
self.expect_sym(";")?;
}
let span = self.span_from(start);
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(CoverItem { meta, kind, before_semi, span })
}
fn parse_cover_item_kind(&mut self) -> PResult<CoverItemKind> {
if self.cur().kind == TokenKind::Directive || self.at_macro_item() {
return Ok(CoverItemKind::Directive(self.take_raw_text()));
}
if self.eat_sym(";") {
return Ok(CoverItemKind::Empty);
}
if self.at_option_assign() {
return Ok(CoverItemKind::Option(Box::new(self.parse_option_assign()?)));
}
// `name : coverpoint ...` / `name : cross ...`. Neither word is
// reserved, so the label is only a label when one of them follows the
// `:`; anything else is not a cover item and the covergroup falls back.
let label = if self.cur().kind == TokenKind::Ident
&& self.nth(1).is_sym(":")
&& (word_at(self.nth(2), "coverpoint") || word_at(self.nth(2), "cross"))
{
let name = Name { text: self.cur().text.clone(), span: self.cur().span };
self.bump();
let before = self.take_gap();
self.bump(); // :
let after = self.take_gap();
Some(CoverLabel { name, comments: Box::new(BinaryComments { before, after }) })
} else {
None
};
if word_at(self.cur(), "coverpoint") {
return Ok(CoverItemKind::Coverpoint(Box::new(self.parse_coverpoint(label)?)));
}
if word_at(self.cur(), "cross") {
return Ok(CoverItemKind::Cross(Box::new(self.parse_cross(label)?)));
}
self.error("expected a coverpoint, a cross or an option")
}
fn parse_coverpoint(&mut self, label: Option<CoverLabel>) -> PResult<CoverpointDecl> {
self.bump(); // coverpoint
let after_kw = self.take_gap();
let expr = self.parse_expr()?;
let iff = self.parse_cover_iff()?;
let before_body = self.gap_before("{");
let body = if self.cur().is_sym("{") { Some(self.parse_cover_body(false)?) } else { None };
Ok(CoverpointDecl { label, after_kw, expr, iff, before_body, body })
}
fn parse_cross(&mut self, label: Option<CoverLabel>) -> PResult<CrossDecl> {
self.bump(); // cross
let after_kw = self.take_gap();
let mut items: Vec<ExprItem> = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let expr = self.parse_expr()?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
items.push(ExprItem { meta, expr, span });
if !more {
break;
}
}
let iff = self.parse_cover_iff()?;
let before_body = self.gap_before("{");
let body = if self.cur().is_sym("{") { Some(self.parse_cover_body(true)?) } else { None };
Ok(CrossDecl { label, after_kw, items, iff, before_body, body })
}
/// The `iff ( expr )` guard of a coverpoint, a cross or a bin. The gap in
/// front of `iff` is claimed only when the keyword was really written.
fn parse_cover_iff(&mut self) -> PResult<Option<Box<CoverIff>>> {
if !self.cur().is_kw("iff") {
return Ok(None);
}
let before_kw = self.take_gap();
self.bump();
let after_kw = self.take_gap();
self.expect_sym("(")?;
let after_open = self.take_gap();
let expr = self.parse_expr()?;
let before_close = self.gap_before(")");
self.expect_sym(")")?;
Ok(Some(Box::new(CoverIff { before_kw, after_kw, after_open, before_close, expr })))
}
/// The `{ bins_or_options }` body of a coverpoint or a cross. Gated, like
/// every other body.
fn parse_cover_body(&mut self, in_cross: bool) -> PResult<CoverBody> {
self.enter()?;
let out = self.parse_cover_body_inner(in_cross);
self.leave();
out
}
fn parse_cover_body_inner(&mut self, in_cross: bool) -> PResult<CoverBody> {
let start = self.here();
self.expect_sym("{")?;
let mut items = Vec::new();
while !self.cur().is_sym("}") {
if self.at_eof() {
return self.error("expected `}`");
}
items.push(self.parse_bin_item(in_cross)?);
}
let dangling = self.take_dangling();
self.expect_sym("}")?;
Ok(CoverBody { items, dangling, span: self.span_from(start) })
}
fn parse_bin_item(&mut self, in_cross: bool) -> PResult<BinItem> {
let start = self.here();
let mut meta = self.take_meta();
let kind = self.parse_bin_item_kind(in_cross)?;
let mut before_semi = Vec::new();
if kind.takes_semi() {
before_semi = self.take_gap();
self.expect_sym(";")?;
}
let span = self.span_from(start);
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(BinItem { meta, kind, before_semi, span })
}
fn parse_bin_item_kind(&mut self, in_cross: bool) -> PResult<BinItemKind> {
if self.cur().kind == TokenKind::Directive || self.at_macro_item() {
return Ok(BinItemKind::Directive(self.take_raw_text()));
}
if self.eat_sym(";") {
return Ok(BinItemKind::Empty);
}
if self.at_option_assign() {
return Ok(BinItemKind::Option(Box::new(self.parse_option_assign()?)));
}
Ok(BinItemKind::Bin(Box::new(self.parse_bin_decl(in_cross)?)))
}
/// True when the cursor opens `option.x = v` / `type_option.x = v`.
/// Both words are matched by text and both demand the `.`, so a signal
/// named `option` compared to something else is not one.
fn at_option_assign(&self) -> bool {
(word_at(self.cur(), "option") || word_at(self.cur(), "type_option"))
&& self.nth(1).is_sym(".")
}
fn parse_option_assign(&mut self) -> PResult<OptionAssign> {
let target = self.parse_expr()?;
let before = self.gap_before("=");
self.expect_sym("=")?;
let after = self.take_gap();
let value = self.parse_expr()?;
Ok(OptionAssign { target, comments: Box::new(BinaryComments { before, after }), value })
}
/// `[wildcard] bins name[[expr]] = spec [with (expr)] [iff (expr)]`.
///
/// `wildcard`, `bins`, `ignore_bins` and `illegal_bins` are matched **by
/// text**, not reserved as keywords, for the reason `soft` and `dist` are:
/// reserving them would stop a file that spells one as an identifier from
/// parsing at all. Inside a coverpoint body their position leaves no other
/// reading. See `docs/features/covergroup-bodies/README.md`.
fn parse_bin_decl(&mut self, in_cross: bool) -> PResult<BinDecl> {
let wildcard = word_at(self.cur(), "wildcard") && bin_kind_at(self.nth(1)).is_some();
let mut after_wildcard = Vec::new();
if wildcard {
self.bump();
after_wildcard = self.take_gap();
}
let Some(kind) = bin_kind_at(self.cur()) else {
return self.error("expected `bins`, `ignore_bins` or `illegal_bins`");
};
self.bump();
let before_name = self.take_gap();
let name = self.expect_name()?;
let array = self.parse_bin_array()?;
let before = self.gap_before("=");
self.expect_sym("=")?;
let after = self.take_gap();
let spec = self.parse_bin_spec(in_cross)?;
let with_expr = self.parse_bin_with()?;
let iff = self.parse_cover_iff()?;
Ok(BinDecl {
wildcard,
after_wildcard,
kind,
before_name,
name,
array,
eq_comments: Box::new(BinaryComments { before, after }),
spec,
with_expr,
iff,
})
}
/// The `[]` / `[expr]` written after a bin name.
fn parse_bin_array(&mut self) -> PResult<Option<Box<BinArray>>> {
if !self.cur().is_sym("[") {
return Ok(None);
}
let before = self.take_gap();
self.bump();
let inner_before = self.take_gap();
let size = if self.cur().is_sym("]") { None } else { Some(self.parse_expr()?) };
let inner_after = self.gap_before("]");
self.expect_sym("]")?;
Ok(Some(Box::new(BinArray {
before,
comments: Box::new(BinaryComments { before: inner_before, after: inner_after }),
size,
})))
}
/// What a bin is defined as. `in_cross` says which grammar applies: a
/// coverpoint bin's `( ... )` is a **transition list** (IEEE 1800
/// §19.5.1.2) and a cross bin's is a parenthesized **select expression**
/// (§19.6.1). The two are told apart by where they are written, which is
/// what the LRM does — asking whether a `=>` happens to be inside gets
/// `bins b = (1'b1[*5]);` wrong.
fn parse_bin_spec(&mut self, in_cross: bool) -> PResult<BinSpec> {
if self.cur().is_kw("default") {
self.bump();
// `sequence` really is a lexer keyword (a `sequence ... endsequence`
// declaration), so this one is not matched by text.
if self.cur().is_kw("sequence") {
let comments = self.take_gap();
self.bump();
return Ok(BinSpec::DefaultSequence { comments });
}
return Ok(BinSpec::Default);
}
if self.cur().is_sym("{") {
return Ok(BinSpec::Values(self.parse_constraint_expr_set()?));
}
if self.cur().is_sym("(") && !in_cross {
return Ok(BinSpec::Transitions(self.parse_trans_list()?));
}
Ok(BinSpec::Select(self.parse_select_expr()?))
}
/// `( trans_set ) [ , ( trans_set ) ]*` (IEEE 1800 §19.5.1.2).
fn parse_trans_list(&mut self) -> PResult<Vec<TransSet>> {
let mut sets: Vec<TransSet> = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
self.expect_sym("(")?;
let mut ranges = Vec::new();
let mut arrow = BinaryComments::default();
loop {
ranges.push(self.parse_trans_range(Box::new(arrow))?);
if !self.cur().is_sym("=>") {
break;
}
let before = self.take_gap();
self.bump();
let after = self.take_gap();
arrow = BinaryComments { before, after };
}
let dangling = self.gap_before(")");
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();
}
sets.push(TransSet { meta, ranges, dangling, span });
if !more {
break;
}
}
Ok(sets)
}
fn parse_trans_range(&mut self, arrow_comments: Box<BinaryComments>) -> PResult<TransRange> {
let mut items: Vec<ExprItem> = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let expr = self.parse_range_or_expr()?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
items.push(ExprItem { meta, expr, span });
if !more {
break;
}
}
let repeat = self.parse_trans_repeat()?;
Ok(TransRange { arrow_comments, items, repeat })
}
/// `[* 3]`, `[* 1:$]`, `[-> 2]`, `[= 1]` — the repetition a transition
/// range may carry.
fn parse_trans_repeat(&mut self) -> PResult<Option<Box<TransRepeat>>> {
if !self.at_repeat_bracket() {
return Ok(None);
}
let before = self.take_gap();
self.bump(); // [
let after_open = self.take_gap();
let op = self.bump().text;
let inner_before = self.take_gap();
let lo = self.parse_expr()?;
let mut colon = BinaryComments::default();
let mut hi = None;
if self.cur().is_sym(":") {
colon.before = self.take_gap();
self.bump();
colon.after = self.take_gap();
hi = Some(self.parse_expr()?);
}
let inner_after = self.gap_before("]");
self.expect_sym("]")?;
Ok(Some(Box::new(TransRepeat {
before,
after_open,
op,
comments: Box::new(BinaryComments { before: inner_before, after: inner_after }),
lo,
hi,
colon_comments: Box::new(colon),
})))
}
/// A cross bin's `select_expression` (IEEE 1800 §19.6.1), and the bare
/// coverpoint name a coverpoint bin may be defined as.
fn parse_select_expr(&mut self) -> PResult<SelectExpr> {
let mut lhs = self.parse_select_primary()?;
while self.cur().is_sym("&&") || self.cur().is_sym("||") {
let before = self.take_gap();
let op = self.bump().text;
let after = self.take_gap();
let rhs = self.parse_select_primary()?;
lhs = SelectExpr::Binary {
lhs: Box::new(lhs),
op,
comments: Box::new(BinaryComments { before, after }),
rhs: Box::new(rhs),
};
}
Ok(lhs)
}
fn parse_select_primary(&mut self) -> PResult<SelectExpr> {
if self.cur().is_sym("!") {
self.bump();
let comments = self.take_gap();
let expr = self.parse_select_primary()?;
return Ok(SelectExpr::Not { comments, expr: Box::new(expr) });
}
if self.cur().is_sym("(") {
self.bump();
let before = self.take_gap();
let expr = self.parse_select_expr()?;
let after = self.gap_before(")");
self.expect_sym(")")?;
return Ok(SelectExpr::Paren {
comments: Box::new(BinaryComments { before, after }),
expr: Box::new(expr),
});
}
if word_at(self.cur(), "binsof") && self.nth(1).is_sym("(") {
return Ok(SelectExpr::Binsof(Box::new(self.parse_binsof()?)));
}
// A bare spec is a coverpoint name, possibly reached through a handle
// (`cfg.vif.x`), an index, or a call (`single_masks(n)`, which tools
// accept and the LRM does not). Read at the **postfix** level, so it
// stops in front of `&&`, `||` and everything else this grammar reads
// itself — and, with `no_with` set, in front of the bin's own
// `with ( ... )` filter, which is not an array method's iterator
// argument.
if self.cur().kind != TokenKind::Ident {
return self.error("expected a select expression");
}
self.no_with = true;
let out = self.parse_postfix();
self.no_with = false;
Ok(SelectExpr::Expr(out?))
}
fn parse_binsof(&mut self) -> PResult<BinsofSel> {
self.bump(); // binsof
let after_kw = self.take_gap();
self.expect_sym("(")?;
let after_open = self.take_gap();
let name = self.parse_expr()?;
let before_close = self.gap_before(")");
self.expect_sym(")")?;
let mut before_intersect = Vec::new();
let mut after_intersect = Vec::new();
let mut intersect = None;
if word_at(self.cur(), "intersect") {
before_intersect = self.take_gap();
self.bump();
after_intersect = self.take_gap();
intersect = Some(self.parse_constraint_expr_set()?);
}
Ok(BinsofSel {
after_kw,
after_open,
before_close,
name,
before_intersect,
after_intersect,
intersect,
})
}
/// The `with ( expr )` filter written after a bin's values.
fn parse_bin_with(&mut self) -> PResult<Option<Box<BinWith>>> {
if !(self.cur().is_kw("with") && self.nth(1).is_sym("(")) {
return Ok(None);
}
let before_kw = self.take_gap();
self.bump();
let after_kw = self.take_gap();
self.expect_sym("(")?;
let after_open = self.take_gap();
let expr = self.parse_expr()?;
let before_close = self.gap_before(")");
self.expect_sym(")")?;
Ok(Some(Box::new(BinWith { before_kw, after_kw, after_open, before_close, expr })))
}
/// 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;
// True while the next token would be the *first* of a statement — at
// the start, and again after an `else` continues one.
let mut at_stmt_start = true;
loop {
if self.at_eof() {
return self.error("expected `;`");
}
// A statement that *is* a macro invocation ends with the
// invocation, whether or not a `;` follows it:
// `assert property (p) else `ASSERT_ERROR(A)` (OpenTitan
// `adc_ctrl/dv/sva/adc_ctrl_fsm_sva_if.sv:35`).
//
// Whether it is the whole statement is decided by what *follows*
// the call, never by the macro standing first — a macro's
// expansion is just as often a signal name that the rest of the
// statement goes on to assign to or read (`` `SIG = 1'b1; ``,
// `` `CNT <= `CNT + 1; ``, `` `MSG(x) + 1; ``). When anything
// that could continue a statement follows, this falls through to
// the ordinary token-by-token scan, which is what ran before this
// case existed (QA finding, `docs/features/clocking-wave`).
if depth == 0 && at_stmt_start && self.cur().is_macro() {
let call = self.parse_macro_call()?;
if call.semi || !self.at_statement_tail() {
// Its own `;`, or nothing that could continue it: done,
// unless an `else` chains a second action onto it.
if !self.eat_kw("else") {
return Ok(());
}
continue;
}
// The macro was a name, not a statement. Scan on.
at_stmt_start = false;
continue;
}
at_stmt_start = false;
let t = self.cur();
if t.is_sym("(") {
self.bump();
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(());
}
at_stmt_start = true;
}
} else if depth == 0 && self.eat_sym(";") {
return Ok(());
} else {
self.bump();
}
}
}
/// True when the token at the cursor could *continue* a statement whose
/// first token has already been consumed — an assignment, an operator, a
/// postfix segment. Used to tell `` else `ASSERT_ERROR(A) `` (the macro is
/// the whole action) from `` else `SIG = 1'b1; `` (the macro was a name).
///
/// Every such continuation is spelled with a symbol: `=`, `<=`, `+`,
/// `++`, `.`, `[`, `::`. What can stand after a *complete* action instead
/// is a keyword (`assign`, `end`, `endmodule`), an identifier or another
/// macro (the next item or label), a directive, or the end of the file —
/// none of which continue an expression.
///
/// Deliberately generous in one direction: guessing "continues" when the
/// statement was in fact complete only falls back to the brute-force scan
/// that ran before the macro case existed, while guessing "complete" when
/// it was not is the regression this predicate exists to prevent.
fn at_statement_tail(&self) -> bool {
self.cur().kind == TokenKind::Symbol
}
/// `property name [( ... )]; ... endproperty [: name]`, and its
/// `sequence` / `endsequence` twin, kept as verbatim source for the reason
/// [`Parser::parse_concurrent_assertion`] gives — the body is written in
/// 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))
}
/// `default disable iff <expression_or_dist>;` (IEEE 1800 §16.12), kept as
/// verbatim source.
///
/// It is the standing `disable iff` clause of every concurrent assertion
/// in the scope, so what it holds is a property-grammar operand — `dist`
/// included — and the assertions it governs are already verbatim. Copying
/// it out by span keeps the whole assertion story in one bucket instead of
/// modelling half of it. Only the item spelling exists; there is no
/// statement form.
fn parse_default_disable(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
self.bump(); // default
self.expect_kw("disable")?;
self.expect_kw("iff")?;
// Scan to the terminating `;`, skipping bracketed runs whole so a `;`
// written inside a `dist { ... }` set does not end the item early.
loop {
if self.at_eof() {
return self.error("expected `;`");
}
let t = self.cur();
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
let (open, close) = match t.text.as_str() {
"(" => ("(", ")"),
"[" => ("[", "]"),
_ => ("{", "}"),
};
self.bump();
self.skip_balanced(open, close)?;
} else if self.eat_sym(";") {
break;
} else {
self.bump();
}
}
Ok(self.verbatim_since(start, col))
}
// ------------------------------------------------------------------
// Conditional-directive split recovery
//
// 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 signals = vec![self.parse_clocking_signal()?];
while self.eat_sym(",") {
signals.push(self.parse_clocking_signal()?);
}
ClockingItemKind::Signals { dir, skew, signals }
};
let span = self.span_from(start);
self.expect_sym(";")?;
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(ClockingItem { meta, kind, span })
}
/// One `signal [= expression]` of a clocking direction group — IEEE 1800
/// §14.4's `clocking_decl_assign`. The expression names what the clocking
/// signal is really bound to (`output tms = _tms_internal;`), and it is an
/// ordinary expression rather than a second grammar.
fn parse_clocking_signal(&mut self) -> PResult<ClockingSignal> {
let name = self.expect_name()?;
let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
Ok(ClockingSignal { name, value })
}
/// True when the cursor is on a clocking skew rather than on the first
/// signal name: `#2`, `#1step`, `posedge`, `negedge`, `edge`.
fn at_clocking_skew(&self) -> bool {
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 });
// `virtual spi_if.tb sif` — a modport-qualified virtual interface
// type (IEEE 1800 §25.9, `spi_device/pre_dv/tb/spid_common.sv:563`).
// Glued onto the interface name exactly as an interface *port*'s
// modport is, so every consumer still sees one type-name string.
if self.at_modport_port() {
ty.name = self.parse_modport_port_type()?.name;
return Ok(ty);
}
}
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
};
// A declaration reaches here with its `virtual` already in
// `qualifiers`, so `parse_opt_data_type`'s own modport branch cannot
// fire: `virtual spi_if.tb tb_sif = sif.tb;`
// (`spi_device/pre_dv/tb/spid_jedec_tb.sv:32`) is recognized here
// instead, the way `parse_ansi_port` recognizes an interface port's.
let ty = if qualifiers.iter().any(|q| q == "virtual") && self.at_modport_port() {
self.parse_modport_port_type()?
} else {
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 (members, directives) = self.parse_enum_members(false)?;
let dangling = self.take_dangling();
self.expect_sym("}")?;
Ok(EnumType { base, members, directives, dangling })
}
/// An `enum`'s member list, with the `` `ifdef``-style directives written
/// between the members.
///
/// The cursor starts just past the `{` and stops on the `}` that closes
/// it. `to_eof` swaps that closer for end of file, which is the only
/// difference between an enum body and an enum-member fragment — one
/// grammar, read by both (`docs/features/fragment-mode/README.md`).
fn parse_enum_members(
&mut self,
to_eof: bool,
) -> PResult<(Vec<EnumMember>, Vec<ListDirective>)> {
let mut members = Vec::new();
let mut directives = Vec::new();
self.take_list_directives(&mut directives, 0);
loop {
if to_eof && self.at_eof() {
break;
}
let start = self.here();
let mut meta = self.take_meta();
let Name { text: name, span: name_span } = self.expect_name()?;
// `ReqPeriResetIdx[0:1]`, `OtbnDmem[16]` — the enum name range of
// IEEE 1800 §6.19 (`rstmgr_pkg.sv:72`, `chip_env_pkg.sv:88`).
let range = self.parse_dims()?;
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, range, value, comma, span });
let dirs = self.take_list_directives(&mut directives, members.len());
let at_close = if to_eof { self.at_eof() } else { self.cur().is_sym("}") };
if (!comma && !dirs.any) || (dirs.any && at_close) {
break;
}
}
Ok((members, directives))
}
/// `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 mut qualifiers = Vec::new();
while self.cur().is_kw("rand") || self.cur().is_kw("randc") {
qualifiers.push(self.bump().text);
}
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, qualifiers, 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`),
/// or of a gate — where a pull gate may also write one strength on its
/// own, `pullup (weak1) p (x);` (§28.3's `pullup_strength`).
///
/// Both orders are accepted, as the grammar allows; the `(` only opens a
/// strength when a strength keyword follows it, so a parenthesized
/// left-hand side — and a gate whose first argument is an expression — is
/// untouched.
fn parse_opt_drive_strength(&mut self) -> PResult<Option<DriveStrength>> {
if !self.cur().is_sym("(") || !is_drive_strength(self.nth(1)) {
return Ok(None);
}
self.bump(); // (
let first = self.bump().text;
if self.eat_sym(")") {
return Ok(Some(DriveStrength { first, second: None }));
}
self.expect_sym(",")?;
if !is_drive_strength(self.cur()) {
return self.error("expected a drive strength");
}
let second = Some(self.bump().text);
self.expect_sym(")")?;
Ok(Some(DriveStrength { first, second }))
}
/// The value after a `#`: a bare primary, or a parenthesized delay —
/// one value, `min:typ:max`, or the `(rise, fall[, turn-off])` list of
/// IEEE 1800 §28.14.
///
/// A single value keeps the [`ExprKind::Paren`] node the one-value
/// spelling has always produced, so `#(5)` and `#(1:2:3)` still print
/// exactly as written; only a real comma list yields more than one
/// element.
fn parse_delay_values(&mut self) -> PResult<Vec<Expr>> {
if !self.cur().is_sym("(") {
return Ok(vec![self.parse_primary()?]);
}
let start = self.here();
self.bump(); // (
let mut out = Vec::new();
loop {
let inner_start = self.here();
let first = self.parse_expr()?;
out.push(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
});
if !self.eat_sym(",") {
break;
}
}
self.expect_sym(")")?;
if out.len() == 1 {
let inner = out.remove(0);
return Ok(vec![self.expr_at(
start,
ExprKind::Paren { inner: Box::new(inner), before: Vec::new(), after: Vec::new() },
)]);
}
Ok(out)
}
/// The single delay value a net declaration or a continuous assignment
/// takes. The multi-value list is a gate-instantiation spelling only —
/// see [`Parser::parse_delay_values`].
fn parse_delay_value(&mut self) -> PResult<Expr> {
let mut values = self.parse_delay_values()?;
if values.len() > 1 {
return self.error("a multi-value delay list is only allowed on a gate instantiation");
}
Ok(values.remove(0))
}
/// 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.parse_bind_instance()?);
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 })
}
/// One entry of a `bind`'s `: instance_list`. The LRM spells these as bare
/// instance names, but vendor tools accept — and OpenTitan writes — a
/// hierarchical path: `bind prim_packer_fifo :
/// dut.u_entropy_src_core.u_prim_packer_fifo_precon ...`
/// (`entropy_src/dv/tb/tb.sv:94`). The dots are glued into the one name
/// the list already carries, exactly as `bind`'s own target path is.
fn parse_bind_instance(&mut self) -> PResult<Name> {
let start = self.here();
let mut text = self.expect_ident()?;
while self.cur().is_sym(".") {
self.bump();
text.push('.');
text.push_str(&self.expect_ident()?);
}
Ok(Name { text, span: self.span_from(start) })
}
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;
// `pullup (weak1) p (x);` — the strength stands where an unnamed
// instance's argument list would, and only a strength keyword after
// the `(` tells the two apart.
let strength = self.parse_opt_drive_strength()?;
let delay = if self.cur().is_sym("#") {
self.bump();
self.parse_delay_values()?
} else {
Vec::new()
};
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, strength, 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()?)),
// A block-scoped type (IEEE 1800 §6.18), e.g.
// `spi_host/dv/env/seq_lib/spi_host_base_vseq.sv:577`. Same
// grammar and same layout as the item-level `typedef`.
"typedef" => Ok(StmtKind::Typedef(self.parse_typedef()?)),
"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.parse_foreach_var()?);
while self.eat_sym(",") {
vars.push(self.parse_foreach_var()?);
}
}
self.expect_sym("]")?;
Ok((expr, vars))
}
/// One loop-variable slot of a `foreach`'s bracket list. A dimension may
/// be **skipped** (IEEE 1800 §12.7.3) by writing nothing in its slot —
/// `foreach (cfg.mem_bkdr_util_h[, bank])`
/// (`ip_templates/flash_ctrl/dv/env/flash_ctrl_env.sv:43`) iterates only
/// the second dimension. A skipped slot is an empty name at the point it
/// was written: it declares nothing, and it prints as nothing.
fn parse_foreach_var(&mut self) -> PResult<Name> {
if self.cur().is_sym(",") || self.cur().is_sym("]") {
let here = self.here();
return Ok(Name { text: String::new(), span: self.span_from(here) });
}
self.expect_name()
}
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))
}
}
/// The `hierarchical_identifier` of a paren-less event control:
/// `.`-separated names, each with an optional bit-select
/// (IEEE 1800 §A.9.3) — `@cfg.agents["ping"].vif.sender_cb`. Both segment
/// openers are safe to take greedily, because the statement that follows
/// an event control cannot begin with `.` or `[`.
///
/// One link per segment: the loop wraps what it has already built, which
/// is the shape `docs/features/recursion-limit/README.md` requires the
/// chain budget for. The caller restores the count it started from.
fn parse_bare_event_name(&mut self) -> PResult<Expr> {
let start = self.here();
let name = self.expect_ident()?;
let mut expr = self.expr_at(start, ExprKind::Ident(name));
loop {
if self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident {
self.link()?;
self.bump();
let member = self.expect_ident()?;
expr = self.expr_at(start, ExprKind::Member { base: Box::new(expr), name: member });
} else if self.cur().is_sym("[") {
self.link()?;
self.bump();
let index = self.parse_expr()?;
self.expect_sym("]")?;
expr = self.expr_at(
start,
ExprKind::Index { base: Box::new(expr), index: Box::new(index) },
);
} else {
return Ok(expr);
}
}
}
fn parse_sens_list(&mut self) -> PResult<SensList> {
if self.cur().is_sym("*") {
// `@*` without parens.
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.
// A chain, so it carries the chain budget and releases it the way
// `parse_postfix` does — by restoring the count it started from.
let outer_links = self.links;
let out = self.parse_bare_event_name();
self.links = outer_links;
return out.map(SensList::Bare);
}
if self.cur().is_sym("(") && self.nth(1).is_sym("*") {
// `@( /* c */ * /* d */ )`: the comments belong to the star, not
// 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()?;
// `@(posedge clk iff enable)` — IEEE 1800 §9.4.2 lets each term
// carry its own gating condition. `iff` is a keyword, so the
// expression above stops in front of it on its own.
let iff = if self.eat_kw("iff") { Some(self.parse_expr()?) } else { None };
// Comments written before the separator — either spelling — or
// before the closing `)` stay on this item's side of it.
if self.cur().is_sym(",") || self.cur().is_kw("or") || self.cur().is_sym(")") {
self.take_before(&mut meta);
}
items.push(SensItem { meta, sep, edge, expr, iff });
// Both separators are legal in the same list; each is kept as
// written so the formatter never rewrites one as the other.
sep = if self.eat_sym(",") {
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("[") && !self.at_repeat_bracket())
|| t.is_sym("(")
|| (t.is_sym("'") && self.nth(1).is_sym("("))
// `ty'{...}` — a cast over an assignment pattern. Only a base
// that may stand left of a cast opens one, so a bare `'{...}`
// literal still reaches `parse_primary` as the whole expression.
|| (t.is_sym("'{") && self.is_cast_base(base))
|| 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.no_with
&& (self.nth(1).is_sym("(") || self.nth(1).is_sym("{")))
}
/// True when the `[` at the cursor opens a transition repetition —
/// `[* 3]`, `[-> 2]`, `[= 1]` (IEEE 1800 §19.5.1.2) — rather than an
/// index or a part select.
///
/// No index expression can start with `*`, `->` or `=`, so this needs no
/// context: it says "that `[` is not an index" everywhere, which was
/// already true and is now acted on. Without it `1'b0[*1:10]` would send
/// the whole covergroup down the verbatim fallback, because
/// [`Parser::parse_postfix_inner`] would take the `[` and then fail on
/// the `*`.
fn at_repeat_bracket(&self) -> bool {
if !self.cur().is_sym("[") {
return false;
}
let next = self.nth(1);
next.kind == TokenKind::Symbol && matches!(next.text.as_str(), "*" | "->" | "=")
}
/// 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 = Box::new(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("(")) || t.is_sym("'{") {
// Cast: `expr'(x)`, or `expr'{...}` over an assignment
// pattern (IEEE 1800 §10.9.1). The casting type is a
// `constant_primary` (IEEE 1800 §6.24.1): a name, a
// package-scoped or hierarchical name, a size, a
// parenthesized constant expression —
// `(NumLevels)'(unsigned'(j))` (corpus
// `common_cells/src/lzc.sv:67`) — or a system function call,
// `$bits(x)'(y)` / `$clog2(N)'(y)`.
if !self.is_cast_base(&expr) {
return self.error("unsupported cast base expression");
}
if t.is_sym("'{") {
let pattern_start = self.here();
let inner = self.parse_assign_pattern(pattern_start)?;
expr = self.expr_at(
start,
ExprKind::Cast { ty: Box::new(expr), expr: Box::new(inner), pattern: true },
);
} else {
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),
pattern: false,
},
);
}
} 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 `e` may stand left of a cast's `'` — the `constant_primary`
/// of IEEE 1800 §6.24.1's `casting_type`.
///
/// A **system function call** is one of those primaries, and the only
/// call shape accepted here: `$bits(periph_data_mux)'({...})`
/// (`top_earlgrey/ip_autogen/pinmux/rtl/pinmux.sv:490`) and
/// `$clog2(RomSize)'(RomSize)` (`vendor/pulp_riscv_dbg/debug_rom/
/// debug_rom.sv:67`). An ordinary call is left out: a constant function
/// call is legal SV there, but nothing in either corpus writes one, and
/// admitting `f(x)'(y)` would also admit a mis-parse of a method call
/// followed by an unrelated sized literal.
fn is_cast_base(&self, e: &Expr) -> bool {
match &e.kind {
ExprKind::Ident(_)
| ExprKind::Number(_)
| ExprKind::Scope { .. }
| ExprKind::Member { .. }
| ExprKind::Paren { .. } => true,
ExprKind::Call { callee, .. } => {
matches!(&callee.kind, ExprKind::Ident(n) if n.starts_with('$'))
}
_ => false,
}
}
/// 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
}
/// An assignment pattern, the cursor on its `'{` (IEEE 1800 §10.9.1):
/// `'{a, b}`, `'{key: v}`, `'{default: 0}` and the replication form
/// `'{N{0}}`. `start` is the `'{`'s own position — a cast over a pattern
/// (`ty'{...}`) keeps the type outside the pattern's span, in the `Cast`
/// node that wraps it.
fn parse_assign_pattern(&mut self, start: u32) -> PResult<Expr> {
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)))
}
/// `'{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), pattern: false },
));
}
// 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.parse_assign_pattern(start),
_ => 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 chain of a fifth of the budget is over
// the limit even though no single chain is.
let per_level = MAX_CHAIN_LENGTH as usize / 5;
let level = format!("a{}(", ".b".repeat(per_level));
assert_chain_too_long(format!(
"module m;\nassign x = {}z{};\nendmodule\n",
level.repeat(7),
")".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 it does it on purpose
// (docs/features/ansi-first-port/README.md, Status): the generic
// `interface` port is a different production wanting an "any
// interface" DataType.
assert!(parse_err("module m (interface bus);\nendmodule\n").contains("expected"));
// The second shape that round left open, `virtual bus_if.mp v;`, is
// closed by docs/features/testbench-mopup/README.md — but only
// after `virtual`, so a `.` after a bare identifier still reads as a
// member access everywhere else, which is what that round was
// protecting.
assert!(parse_err("module m;\n 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 a_property_declaration_is_still_captured_verbatim() {
// What is left in the verbatim bucket after two rounds of this wave:
// a `property`/`sequence` declaration and a concurrent assertion.
let src = "class c;\n property p;\n a |-> b;\n endproperty : p\nendclass\n";
let f = parse_ok(src);
let items = &class_of(&f).items;
let ItemKind::Verbatim(b) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(b.text, "property p;\n a |-> b;\n endproperty : p");
assert_eq!(b.text, src[b.span.as_range()]);
}
#[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 property p;\n a |-> b;\n endproperty // why\n int b;\nendclass\n",
);
let items = &class_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(!raw.text.contains("why"), "the capture swallowed the comment: {:?}", raw.text);
assert_eq!(items[0].meta.trailing.as_ref().expect("the comment survived").text, "// why");
}
#[test]
fn a_comment_after_a_covergroup_stays_outside_it_too() {
let f = parse_ok(
"class c;\n covergroup g;\n coverpoint a;\n endgroup // why\n int b;\nendclass\n",
);
let items = &class_of(&f).items;
assert!(matches!(items[0].kind, ItemKind::Covergroup(_)));
assert_eq!(items[0].meta.trailing.as_ref().expect("the comment survived").text, "// why");
}
// ------------------------------------------------------------------
// Constraint bodies (`docs/features/constraint-bodies/README.md`)
// ------------------------------------------------------------------
fn constraint_of(f: &SourceFile) -> &ConstraintDecl {
match &class_of(f).items[0].kind {
ItemKind::Constraint(c) => c,
other => panic!("expected a constraint, got {other:?}"),
}
}
/// The items of `constraint c { ... }` written alone in a class.
fn constraint_items(f: &SourceFile) -> &[ConstraintItem] {
&constraint_of(f).body.as_ref().expect("a body").items
}
fn in_class(body: &str) -> String {
format!("class k;\n constraint c {{\n{body}\n }}\nendclass\n")
}
#[test]
fn a_constraint_keeps_its_name_and_its_items() {
let src = "class k;\n constraint c_len {\n a == 0;\n b < 4;\n }\nendclass\n";
let f = parse_ok(src);
let c = constraint_of(&f);
assert_eq!(c.name.text, "c_len");
assert_eq!(&src[c.name.span.as_range()], "c_len", "the name span slices the name");
assert!(c.scope.is_none());
assert!(!c.semi);
let items = &c.body.as_ref().expect("a body").items;
assert_eq!(items.len(), 2);
assert!(matches!(items[0].kind, ConstraintItemKind::Expr { soft: false, .. }));
}
#[test]
fn a_constraint_prototype_has_no_body() {
let f = parse_ok("class k;\n extern constraint c;\nendclass\n");
let c = constraint_of(&f);
assert_eq!(c.qualifiers, vec!["extern".to_string()]);
assert_eq!(c.name.text, "c");
assert!(c.body.is_none());
}
#[test]
fn a_pure_static_constraint_keeps_every_qualifier() {
let f = parse_ok("class k;\n pure static constraint c;\nendclass\n");
assert_eq!(constraint_of(&f).qualifiers, vec!["pure".to_string(), "static".to_string()]);
}
#[test]
fn a_stray_semicolon_after_the_block_is_recorded() {
let f = parse_ok("class k;\n constraint c { a == 0; };\nendclass\n");
assert!(constraint_of(&f).semi);
}
#[test]
fn a_soft_constraint_is_flagged_and_a_signal_named_soft_is_not() {
let f = parse_ok(&in_class(" soft a == 0;"));
assert!(matches!(
constraint_items(&f)[0].kind,
ConstraintItemKind::Expr { soft: true, .. }
));
// `soft` as an ordinary name: no term follows it, so it is the
// expression's own head. Reserving the word would have broken this.
let f = parse_ok(&in_class(" soft == 0;"));
let ConstraintItemKind::Expr { soft, expr, .. } = &constraint_items(&f)[0].kind else {
panic!("expected an expression item")
};
assert!(!soft);
assert!(matches!(expr.kind, ExprKind::Binary { .. }));
}
#[test]
fn a_dist_set_keeps_both_weight_operators_apart() {
let f = parse_ok(&in_class(" n dist { 0 := 5, [1:20] :/ 20, 99 };"));
let ConstraintItemKind::Expr { expr, .. } = &constraint_items(&f)[0].kind else {
panic!("expected an expression item")
};
let ExprKind::Dist { weights, .. } = &expr.kind else { panic!("expected a dist") };
assert_eq!(weights.len(), 3);
assert_eq!(weights[0].op.as_deref(), Some(":="));
assert_eq!(weights[1].op.as_deref(), Some(":/"));
assert!(matches!(weights[1].value.kind, ExprKind::ValueRange { .. }));
// A weightless item is legal and keeps no operator.
assert!(weights[2].op.is_none());
assert!(weights[2].weight.is_none());
}
#[test]
fn a_soft_dist_is_both() {
let f = parse_ok(&in_class(" soft n dist { 0 :/ 5 };"));
let ConstraintItemKind::Expr { soft, expr, .. } = &constraint_items(&f)[0].kind else {
panic!("expected an expression item")
};
assert!(soft);
assert!(matches!(expr.kind, ExprKind::Dist { .. }));
}
#[test]
fn a_spaced_dist_weight_operator_falls_back() {
// `0 : / 5` is not `:/`: the two tokens are not adjacent, so the body
// does not fit the grammar and the whole item rewinds.
let f = parse_ok("class k;\n constraint c { n dist { 0 : / 5 }; }\nendclass\n");
assert!(matches!(class_of(&f).items[0].kind, ItemKind::Verbatim(_)));
assert_eq!(f.constraint_fallbacks, 1);
}
#[test]
fn an_inside_set_inside_a_constraint_is_an_ordinary_expression() {
let f = parse_ok(&in_class(" n inside {[1:10], 20};"));
let ConstraintItemKind::Expr { expr, .. } = &constraint_items(&f)[0].kind else {
panic!("expected an expression item")
};
assert!(matches!(expr.kind, ExprKind::Inside { .. }));
}
#[test]
fn an_implication_takes_a_set_and_a_bare_item_alike() {
let f = parse_ok(&in_class(" a > 0 -> { b == 1; c == 2; }\n d -> e == 3;"));
let items = constraint_items(&f);
let ConstraintItemKind::Implication { set, .. } = &items[0].kind else {
panic!("expected an implication")
};
assert!(set.braced);
assert_eq!(set.items.len(), 2);
let ConstraintItemKind::Implication { set, .. } = &items[1].kind else {
panic!("expected an implication")
};
assert!(!set.braced, "an unbraced set holds exactly one item");
assert_eq!(set.items.len(), 1);
}
#[test]
fn an_equivalence_operator_stays_inside_the_expression() {
// `<->` is an operator, not an implication: its right-hand side can
// never be a braced set, so it must not become one.
let f = parse_ok(&in_class(" a <-> b;"));
let ConstraintItemKind::Expr { expr, .. } = &constraint_items(&f)[0].kind else {
panic!("expected an expression item")
};
let ExprKind::Binary { op, .. } = &expr.kind else { panic!("expected a binary") };
assert_eq!(op, "<->");
}
#[test]
fn a_constraint_if_chains_through_else_if() {
let f = parse_ok(&in_class(
" if (a == 0) b == 1;\n else if (a == 1) { b == 2; }\n else b == 3;",
));
let ConstraintItemKind::If { els, .. } = &constraint_items(&f)[0].kind else {
panic!("expected an if")
};
let els = els.as_ref().expect("an else");
assert!(!els.braced);
assert!(matches!(els.items[0].kind, ConstraintItemKind::If { .. }), "the else-if chain");
}
#[test]
fn a_constraint_foreach_keeps_its_skipped_dimensions() {
let f = parse_ok(&in_class(" foreach (arr[, j]) { arr[j] < 4; }"));
let ConstraintItemKind::Foreach { vars, set, .. } = &constraint_items(&f)[0].kind else {
panic!("expected a foreach")
};
assert_eq!(vars.len(), 2);
assert!(vars[0].text.is_empty(), "a skipped dimension is an empty name");
assert_eq!(vars[1].text, "j");
assert!(set.braced);
}
#[test]
fn a_solve_before_keeps_both_operand_lists_in_order() {
let f = parse_ok(&in_class(" solve a, b before c, d;"));
let ConstraintItemKind::SolveBefore { solve, before, .. } = &constraint_items(&f)[0].kind
else {
panic!("expected a solve/before")
};
assert_eq!(solve.len(), 2);
assert_eq!(before.len(), 2);
// A signal named `solve` compared to something is not a solve item.
let f = parse_ok(&in_class(" solve == 1;"));
assert!(matches!(constraint_items(&f)[0].kind, ConstraintItemKind::Expr { .. }));
}
#[test]
fn unique_and_disable_soft_are_their_own_items() {
let f = parse_ok(&in_class(" unique {a, b};\n disable soft c;"));
let items = constraint_items(&f);
let ConstraintItemKind::Unique { items: set, .. } = &items[0].kind else {
panic!("expected unique")
};
assert_eq!(set.len(), 2);
assert!(matches!(items[1].kind, ConstraintItemKind::DisableSoft { .. }));
}
#[test]
fn a_null_constraint_item_is_its_semicolon() {
let f = parse_ok(&in_class(" a == 0;\n ;"));
assert!(matches!(constraint_items(&f)[1].kind, ConstraintItemKind::Empty));
}
#[test]
fn a_directive_inside_a_constraint_body_is_a_directive_item() {
let f = parse_ok(&in_class(" `ifdef FOO\n a == 0;\n `endif"));
let items = constraint_items(&f);
assert_eq!(items.len(), 3);
assert!(matches!(items[0].kind, ConstraintItemKind::Directive(_)));
assert!(matches!(items[1].kind, ConstraintItemKind::Expr { .. }));
assert!(matches!(items[2].kind, ConstraintItemKind::Directive(_)));
assert_eq!(f.constraint_fallbacks, 0);
}
#[test]
fn comments_survive_every_slot_of_a_constraint_body() {
let src = "class k;\n // head\n constraint c { // open\n // before\n \
a == 0; // after\n // dangling\n }\nendclass\n";
let f = parse_ok(src);
let item = &class_of(&f).items[0];
assert_eq!(item.meta.leading[0].text, "// head");
let set = constraint_of(&f).body.as_ref().expect("a body");
// `// open` and `// before` both lead the one item; `// after`
// trails it and `// dangling` sits before the `}`.
let leading: Vec<&str> = set.items[0].meta.leading.iter().map(|c| &*c.text).collect();
assert_eq!(leading, ["// open", "// before"]);
assert_eq!(set.items[0].meta.trailing.as_ref().expect("trailing").text, "// after");
assert_eq!(set.dangling.len(), 1);
assert_eq!(set.dangling[0].text, "// dangling");
}
#[test]
fn an_unrecognised_constraint_body_rewinds_to_exactly_the_old_capture() {
// A macro standing where a constraint item belongs — the macro
// supplies the `;`, or half the constraint — is the shape the
// grammar cannot know, and the one real DV code writes. The rewind
// must produce byte-for-byte what `parse_constraint` produced before
// there was a constraint grammar at all: the whole item, its `col`,
// and its own source slice, double spaces and all.
let src = "class k;\n constraint c {\n `MY_HALF\n b == 1;\n }\nendclass\n";
let f = parse_ok(src);
let ItemKind::Verbatim(raw) = &class_of(&f).items[0].kind else {
panic!("expected the verbatim fallback, got {:?}", class_of(&f).items[0].kind)
};
assert_eq!(raw.text, "constraint c {\n `MY_HALF\n b == 1;\n }");
assert_eq!(raw.text, src[raw.span.as_range()], "the capture is the source bytes");
assert_eq!(raw.col, 3, "the column the re-indent contract needs");
assert_eq!(f.constraint_fallbacks, 1);
}
#[test]
fn a_fallback_keeps_the_comments_written_around_it() {
// The speculative parse harvests comments into metas it then throws
// away; the rewind must put them back, or hard invariant #3 breaks.
let f = parse_ok(
"class k;\n // head\n constraint c { `MY_HALF b == 1; } // tail\n int b;\nendclass\n",
);
let item = &class_of(&f).items[0];
assert!(matches!(item.kind, ItemKind::Verbatim(_)));
assert_eq!(item.meta.leading[0].text, "// head");
assert_eq!(item.meta.trailing.as_ref().expect("trailing").text, "// tail");
}
// ------------------------------------------------------------------
// Comment slots (the 2026-09-02 rework)
//
// Every keyword and punctuation position this round introduced must own
// the comments written in front of it. A comment the AST loses is a
// comment the formatter cannot print, and `format_source`'s own token
// check then refuses the file — hard invariant #3 by way of #1. These
// assert the *text is in the node*, which the `.cases` table then proves
// is printed back in place.
// ------------------------------------------------------------------
/// Every comment text the constraint at the head of `src`'s class holds,
/// in the slots this round owns — not the item metas, which the ordinary
/// leading/trailing plumbing already covered.
fn slot_comments(c: &ConstraintDecl) -> Vec<String> {
let mut out = Vec::new();
let mut push = |cs: &[Comment]| out.extend(cs.iter().map(|c| c.text.clone()));
push(&c.before_name);
push(&c.after_name);
push(&c.before_semi);
let Some(set) = &c.body else { return out };
for item in &set.items {
match &item.kind {
ConstraintItemKind::Expr { after_soft, .. } => push(after_soft),
ConstraintItemKind::If { comments, after_else, .. } => {
push(&comments.after_kw);
push(&comments.after_open);
push(&comments.before_close);
push(&comments.before_body);
push(after_else);
}
ConstraintItemKind::Foreach { comments, .. } => {
push(&comments.after_kw);
push(&comments.after_open);
push(&comments.before_close);
push(&comments.before_body);
}
ConstraintItemKind::SolveBefore { before_comments, .. } => push(before_comments),
ConstraintItemKind::Unique { comments, .. } => push(comments),
ConstraintItemKind::DisableSoft { comments, .. } => {
push(&comments.before);
push(&comments.after);
}
_ => {}
}
push(&item.before_semi);
}
out
}
#[test]
fn the_header_keeps_the_comments_written_around_its_name() {
let f =
parse_ok("class k;\n constraint /*a*/ c /*b*/ {\n x < 1;\n } /*c*/ ;\nendclass\n");
let c = constraint_of(&f);
assert_eq!(c.before_name.len(), 1);
assert_eq!(c.before_name[0].text, "/*a*/");
assert_eq!(c.after_name[0].text, "/*b*/");
assert_eq!(c.before_semi[0].text, "/*c*/");
assert!(c.semi);
}
#[test]
fn a_prototype_keeps_the_comment_written_before_its_semicolon() {
let f = parse_ok("class k;\n extern constraint /*a*/ c /*b*/ ;\nendclass\n");
let c = constraint_of(&f);
assert_eq!(c.before_name[0].text, "/*a*/");
assert_eq!(c.after_name[0].text, "/*b*/");
}
#[test]
fn every_constraint_item_slot_keeps_its_comment() {
let f = parse_ok(&in_class(
" soft /*soft*/ n dist /*dist2*/ { 0 /*w1*/ := /*w2*/ 5 } /*semi1*/ ;\n\
\x20 if /*if1*/ ( /*if2*/ m /*if3*/ ) /*if4*/ { a == 1; }\n\
\x20 else /*else2*/ { a == 2; }\n\
\x20 foreach /*fe1*/ ( /*fe2*/ q[i] /*fe3*/ ) /*fe4*/ { q[i] < 2; }\n\
\x20 solve a /*solve*/ before b /*semi2*/ ;\n\
\x20 unique /*uniq*/ {a, b} /*semi3*/ ;\n\
\x20 disable /*ds1*/ soft /*ds2*/ n /*semi4*/ ;",
));
let got = slot_comments(constraint_of(&f));
assert_eq!(
got,
vec![
"/*soft*/",
"/*semi1*/",
"/*if1*/",
"/*if2*/",
"/*if3*/",
"/*if4*/",
"/*else2*/",
"/*fe1*/",
"/*fe2*/",
"/*fe3*/",
"/*fe4*/",
"/*solve*/",
"/*semi2*/",
"/*uniq*/",
"/*semi3*/",
"/*ds1*/",
"/*ds2*/",
"/*semi4*/",
],
"a slot lost its comment"
);
}
#[test]
fn a_dist_keeps_the_comments_around_its_word_and_its_weight_operators() {
let f = parse_ok(&in_class(" n /*before*/ dist /*after*/ { 0 /*b1*/ := /*a1*/ 5, 9 };"));
let ConstraintItemKind::Expr { expr, .. } = &constraint_items(&f)[0].kind else {
panic!("expected an expression item")
};
let ExprKind::Dist { comments, weights, .. } = &expr.kind else {
panic!("expected a dist")
};
assert_eq!(comments.before[0].text, "/*before*/");
assert_eq!(comments.after[0].text, "/*after*/");
assert_eq!(weights[0].op_comments.before[0].text, "/*b1*/");
assert_eq!(weights[0].op_comments.after[0].text, "/*a1*/");
// A weightless item holds no operator and therefore no operator
// comments — the empty case must stay empty, not inherit the last.
assert!(weights[1].op_comments.before.is_empty());
}
#[test]
fn the_gap_before_a_semicolon_that_was_not_written_belongs_to_what_follows() {
// `takes_semi` is false for an implication, so nothing may claim the
// comment in front of the next item; it must lead that item instead.
let f = parse_ok(&in_class(" m -> { a == 1; }\n /*next*/\n b == 2;"));
let items = constraint_items(&f);
assert!(matches!(items[0].kind, ConstraintItemKind::Implication { .. }));
assert!(items[0].before_semi.is_empty());
assert_eq!(items[1].meta.leading[0].text, "/*next*/");
}
#[test]
fn an_else_on_its_own_line_leaves_its_comment_to_the_body_item() {
// The gap after `else` is only this item's when the set opens with a
// `{` or a chained `if`; otherwise the source's own line break has
// already made it the body's leading comment.
let f = parse_ok(&in_class(" if (m) a == 1;\n else\n // why\n a == 2;"));
let ConstraintItemKind::If { after_else, els, .. } = &constraint_items(&f)[0].kind else {
panic!("expected an if")
};
assert!(after_else.is_empty());
let els = els.as_ref().expect("an else");
assert_eq!(els.items[0].meta.leading[0].text, "// why");
}
// ------------------------------------------------------------------
// Out-of-block constraints
// (`docs/features/out-of-class-constraints/README.md`)
// ------------------------------------------------------------------
fn file_constraint(f: &SourceFile) -> &ConstraintDecl {
match &f.items[0].kind {
ItemKind::Constraint(c) => c,
other => panic!("expected a constraint, got {other:?}"),
}
}
#[test]
fn an_out_of_block_constraint_keeps_its_scope_apart_from_its_name() {
let src = "constraint my_item::delay_c {\n soft delay dist {0 :/ 5};\n}\n";
let f = parse_ok(src);
let c = file_constraint(&f);
assert_eq!(c.scope.as_deref(), Some("my_item"));
assert_eq!(c.name.text, "delay_c");
assert_eq!(&src[c.name.span.as_range()], "delay_c");
}
#[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.
let f = parse_ok("constraint pkg::cls::deep_c { x < 4; }\n");
assert_eq!(file_constraint(&f).scope.as_deref(), Some("pkg::cls"));
}
#[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::Constraint(_)), "{:?}", 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 it.
let f = parse_ok("// head\nconstraint c::x { a == 0; }; // tail\nint b;\n");
assert!(file_constraint(&f).semi);
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. The
// fallback re-runs the same header parse, so the message is the one
// it always was.
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, signals } if dir == "input" && signals.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);
}
// ------------------------------------------------------------------
// The clocking wave (`docs/features/clocking-wave/README.md`)
// ------------------------------------------------------------------
#[test]
fn a_clocking_signal_may_be_bound_to_an_expression() {
// OpenTitan hw/dv/sv/jtag_agent/jtag_if.sv:51 — IEEE 1800 §14.4's
// `clocking_decl_assign`.
let f = parse_ok(
"interface i;\n clocking cb @(negedge tck);\n output tms = _tms_internal, tdi = _tdi[0];\n input tdo;\n endclocking\nendinterface\n",
);
let ItemKind::Clocking(c) = &module_of(&f).items[0].kind else {
panic!("expected a clocking block")
};
let ClockingItemKind::Signals { signals, .. } = &c.items[0].kind else {
panic!("expected a signal group")
};
assert_eq!(signals.len(), 2);
assert_eq!(signals[0].name.text, "tms");
assert!(matches!(
signals[0].value.as_ref().map(|e| &e.kind),
Some(ExprKind::Ident(n)) if n == "_tms_internal"
));
assert_eq!(signals[1].name.text, "tdi");
assert!(matches!(signals[1].value.as_ref().map(|e| &e.kind), Some(ExprKind::Index { .. })));
let ClockingItemKind::Signals { signals, .. } = &c.items[1].kind else {
panic!("expected a signal group")
};
assert!(signals[0].value.is_none(), "a plain signal binds nothing");
}
#[test]
fn a_clocking_item_still_needs_a_signal_name() {
assert_eq!(
parse_err(
"interface i;\n clocking cb @(a);\n output = x;\n endclocking\nendinterface\n"
),
"expected identifier (found \"=\")"
);
}
#[test]
fn a_default_disable_iff_is_captured_verbatim() {
// OpenTitan hw/ip/tlul/rtl/tlul_assert.sv:36 — IEEE 1800 §16.12.
let f = parse_ok(
"module m;\n default disable iff disable_sva || !rst_ni;\n wire w;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "default disable iff disable_sva || !rst_ni;");
// The item after it is still read normally.
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)), "{:?}", items[1].kind);
}
#[test]
fn a_default_disable_iff_stops_at_its_own_semicolon() {
// A `;` inside a bracketed run does not end the item; a missing one
// is still an error rather than a swallowed rest-of-file.
let f = parse_ok(
"module m;\n default disable iff x dist {1 := 1, 2 := 2};\n wire w;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "default disable iff x dist {1 := 1, 2 := 2};");
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)));
assert!(parse_err("module m;\n default disable iff a\nendmodule\n")
.starts_with("expected `;`"));
// `default disable` without `iff` is not the item: the dispatch is on
// the two keywords, and the third is required.
assert!(
parse_err("module m;\n default disable a;\nendmodule\n").starts_with("expected `iff`")
);
}
// QA (2026-08-29, `docs/features/clocking-wave/README.md`): a `;` inside a
// string literal or a comment must not end the item early, and two
// `default disable iff`s in a row must not merge into one capture. The
// scan only special-cases `(`/`[`/`{`, so both rely on the lexer already
// treating strings as one token and comments as trivia rather than tokens
// — verified directly rather than assumed.
#[test]
fn a_default_disable_iff_is_not_ended_by_a_semicolon_inside_a_string() {
let f = parse_ok("module m;\n default disable iff x == \"a;b\";\n wire w;\nendmodule\n");
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "default disable iff x == \"a;b\";");
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)));
}
#[test]
fn a_default_disable_iff_is_not_ended_by_a_semicolon_inside_a_comment() {
let f = parse_ok("module m;\n default disable iff /* ; */ x;\n wire w;\nendmodule\n");
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "default disable iff /* ; */ x;");
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)));
}
#[test]
fn two_default_disable_iffs_in_a_row_are_captured_separately() {
let f = parse_ok(
"module m;\n default disable iff a;\n default disable iff b;\n wire w;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(first) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(first.text, "default disable iff a;");
let ItemKind::Verbatim(second) = &items[1].kind else {
panic!("expected a verbatim block")
};
assert_eq!(second.text, "default disable iff b;");
assert!(matches!(items[2].kind, ItemKind::DataDecl(_)));
}
#[test]
fn an_event_control_term_may_carry_an_iff_condition() {
// OpenTitan hw/ip/spi_device/pre_dv/tb/spid_common.sv:1042 —
// IEEE 1800 §9.4.2.
let f = parse_ok(
"module m;\n always @(posedge clk iff rvalid or negedge rst_n) x <= 1;\nendmodule\n",
);
let ItemKind::Always { stmt, .. } = &module_of(&f).items[0].kind else {
panic!("expected an always block")
};
let StmtKind::Timing { control: TimingControl::Event(SensList::List(items)), .. } =
&stmt.kind
else {
panic!("expected an event control")
};
assert_eq!(items.len(), 2);
assert!(matches!(
items[0].iff.as_ref().map(|e| &e.kind),
Some(ExprKind::Ident(n)) if n == "rvalid"
));
assert!(items[1].iff.is_none(), "the gate belongs to one term, not to the list");
}
#[test]
fn a_bare_event_control_may_name_an_indexed_hierarchical_path() {
// OpenTitan .../rstmgr/dv/env/seq_lib/rstmgr_leaf_rst_cnsty_vseq.sv:200.
let f = parse_ok(
"module m;\n initial forever @cfg.cfgs[\"a\"].vif.sender_cb x <= 1;\nendmodule\n",
);
let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else {
panic!("expected an initial block")
};
let StmtKind::Forever { body } = &stmt.kind else { panic!("expected a forever loop") };
let StmtKind::Timing { control: TimingControl::Event(SensList::Bare(e)), .. } = &body.kind
else {
panic!("expected a bare event control")
};
let ExprKind::Member { base, name } = &e.kind else { panic!("expected a member access") };
assert_eq!(name, "sender_cb");
let ExprKind::Member { base, .. } = &base.kind else { panic!("expected a member access") };
assert!(matches!(base.kind, ExprKind::Index { .. }), "the bit-select is part of the path");
}
#[test]
fn a_bare_event_control_charges_the_chain_budget() {
// The loop wraps what it has built, so it must charge `link()` — the
// standing requirement in `docs/features/recursion-limit/README.md`.
let long = format!(
"module m;\n initial @a{} x <= 1;\nendmodule\n",
".b".repeat(MAX_CHAIN_LENGTH as usize + 10)
);
assert_chain_too_long(long);
}
#[test]
fn a_gate_may_carry_a_drive_strength() {
// OpenTitan hw/ip/spi_host/dv/tb.sv:101 — IEEE 1800 §28.3's
// single-strength `pullup_strength`, beside the ordinary pair.
let f = parse_ok(
"module m;\n pullup (weak1) pd (x);\n and (strong0, strong1) g (o, a, b);\n buf b1 ((a & b), c);\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::GateInstantiation(pull) = &items[0].kind else { panic!("expected a gate") };
let s = pull.strength.as_ref().expect("the single strength was parsed");
assert_eq!((s.first.as_str(), s.second.as_deref()), ("weak1", None));
let ItemKind::GateInstantiation(and) = &items[1].kind else { panic!("expected a gate") };
let s = and.strength.as_ref().expect("the strength pair was parsed");
assert_eq!((s.first.as_str(), s.second.as_deref()), ("strong0", Some("strong1")));
// A `(` that does not open a strength still opens an argument list.
let ItemKind::GateInstantiation(buf) = &items[2].kind else { panic!("expected a gate") };
assert!(buf.strength.is_none());
assert_eq!(buf.instances[0].args.len(), 2);
}
#[test]
fn a_program_is_a_module_with_a_different_closer() {
// OpenTitan hw/ip/spi_device/pre_dv/program/spiflash.sv:7 —
// IEEE 1800 §24.3.
let f = parse_ok(
"program p #(parameter int W = 1) (input logic csb);\n logic [7:0] cmd;\nendprogram : p\n",
);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a program") };
assert_eq!(m.kw, "program");
assert_eq!(m.end_kw(), "endprogram");
assert_eq!(m.name, "p");
assert_eq!(m.end_label.as_deref(), Some("p"));
assert_eq!(m.items.len(), 1);
assert!(parse_err("program p;\n wire w;\nendinterface\n")
.starts_with("unsupported construct starting with keyword `endinterface`"));
}
#[test]
fn a_macro_may_be_a_concurrent_assertions_whole_action_statement() {
// OpenTitan hw/ip/adc_ctrl/dv/sva/adc_ctrl_fsm_sva_if.sv:35 — the
// `else` arm is a macro invocation with no `;` after it.
let f = parse_ok(
"module m;\n A_A: assert property (a |=> b)\n else `ASSERT_ERROR(A_A)\n assign x = 1;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("`ASSERT_ERROR(A_A)"), "{:?}", raw.text);
assert!(matches!(items[1].kind, ItemKind::ContAssign(_)), "{:?}", items[1].kind);
}
#[test]
fn a_macro_inside_an_action_statement_is_an_operand_not_a_terminator() {
// Only a macro *starting* a statement ends it; one standing mid-way
// through an expression is a value, and the `;` still terminates.
let f = parse_ok(
"module m;\n A_A: assert property (a) else x = `VAL + 1;\n assign y = 1;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("`VAL + 1;"), "{:?}", raw.text);
assert!(matches!(items[1].kind, ItemKind::ContAssign(_)), "{:?}", items[1].kind);
}
// QA (2026-08-29, `docs/features/clocking-wave/README.md` round 2) —
// QA round-2 finding, fixed by the rework (`docs/features/clocking-wave/
// README.md`, work log 2026-08-29 rework): `skip_action_stmt` used to
// treat a macro standing first in an action as *always* the whole action.
// That is false whenever the macro's expansion is a signal name and the
// statement goes on to assign to, read or increment it — ordinary
// RTL/testbench idiom, and a parse error on input trunk accepts. The scan
// now decides by what *follows* the call (`Parser::at_statement_tail`),
// so all four shapes below parse exactly as they do on trunk while
// `` else `ASSERT_ERROR(A) `` still ends where it ends.
#[test]
fn a_macro_used_as_an_lvalue_is_not_the_whole_action_statement() {
// A macro standing for a signal name, assigned to from an `else` arm.
let f = parse_ok(
"module m;\n A_A: assert property (a) else `SOME_SIGNAL = 1'b1;\n assign y = 1;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("`SOME_SIGNAL = 1'b1;"), "{:?}", raw.text);
assert!(matches!(items[1].kind, ItemKind::ContAssign(_)), "{:?}", items[1].kind);
}
#[test]
fn a_macro_used_as_an_operand_before_an_operator_is_not_the_whole_action_statement() {
// `` `MSG(x) + 1; `` — the macro is an operand, and the `+ 1;` that
// follows it is the rest of the same statement.
let f = parse_ok(
"module m;\n A_A: assert property (a) else `MSG(x) + 1;\n assign y = 1;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("`MSG(x) + 1;"), "{:?}", raw.text);
assert!(matches!(items[1].kind, ItemKind::ContAssign(_)), "{:?}", items[1].kind);
}
#[test]
fn a_macro_counter_increment_is_not_the_whole_action_statement() {
// A common RTL/testbench idiom: a macro standing for a counter
// register, incremented from the `else` arm.
let f = parse_ok(
"module m;\n A_A: assert property (a) else `CNT <= `CNT + 1;\n assign y = 1;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("`CNT <= `CNT + 1;"), "{:?}", raw.text);
assert!(matches!(items[1].kind, ItemKind::ContAssign(_)), "{:?}", items[1].kind);
}
#[test]
fn a_macro_postfix_increment_is_not_the_whole_action_statement() {
// The fourth shape of the same finding: the macro is the operand of a
// postfix `++`, so the statement runs on past the call.
let f = parse_ok(
"module m;\n A_A: assert property (a) else `CNT++;\n assign y = 1;\nendmodule\n",
);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("`CNT++;"), "{:?}", raw.text);
assert!(matches!(items[1].kind, ItemKind::ContAssign(_)), "{:?}", items[1].kind);
}
#[test]
fn a_macro_action_still_ends_where_no_statement_tail_follows() {
// The other side of the same decision, in each shape that can stand
// after a complete macro action: the next item's keyword, an
// identifier opening a label, another macro, and a directive.
for next in ["assign y = 1;", "B_B: assert property (b);", "`ASSERT_INIT(C, 1)", "`endif"] {
let src = format!(
"module m;\n A_A: assert property (a)\n else `ASSERT_ERROR(A_A)\n {next}\nendmodule\n"
);
let f = parse_ok(&src);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else {
panic!("expected a verbatim block for {next:?}")
};
assert!(raw.text.ends_with("`ASSERT_ERROR(A_A)"), "{next:?}: {:?}", raw.text);
assert_eq!(items.len(), 2, "{next:?}: {:?}", items.len());
}
}
#[test]
fn the_clocking_waves_shapes_survive_tolerant_recovery() {
// The language server parses every buffer tolerantly, so each new
// shape has to stay addressable next to a genuine error rather than
// swallowing the rest of the file.
let src = "interface i;\n clocking cb @(posedge clk);\n output tms = _tms;\n endclocking\n default disable iff !rst_n;\n wire ] broken;\n wire w;\nendinterface\n";
let (file, diags) = crate::parse_source_tolerant(src);
assert!(!diags.is_empty(), "the broken declaration is still an error");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected an interface") };
let kinds: Vec<&str> = m
.items
.iter()
.map(|i| match &i.kind {
ItemKind::Clocking(_) => "clocking",
ItemKind::Verbatim(_) => "verbatim",
ItemKind::DataDecl(_) => "decl",
ItemKind::Error(_) => "error",
_ => "other",
})
.collect();
assert!(
kinds.contains(&"clocking") && kinds.contains(&"verbatim") && kinds.contains(&"error"),
"the good items on either side of the broken one survive: {kinds:?}"
);
// An unterminated `default disable iff` does not eat the file either.
let (file, diags) =
crate::parse_source_tolerant("module m;\n default disable iff a\nendmodule\n");
assert!(!diags.is_empty());
assert!(!file.items.is_empty(), "and the file is still addressable");
}
#[test]
fn a_virtual_interface_type_stands_in_every_type_position() {
// corpus/ibex/dv/uvm/icache/dv/env/ibex_icache_env_pkg.sv:28 (typedef)
// 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_deref()), ("weak0", Some("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_parsed_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)
};
let ConstraintBody::Items(set) = &**block else { panic!("expected a parsed body") };
assert!(set.braced);
assert_eq!(set.items.len(), 1);
assert!(matches!(base.kind, ExprKind::Call { .. }), "the call is still structural");
assert_eq!(f.constraint_fallbacks, 0);
}
#[test]
fn an_unrecognised_randomize_with_block_keeps_the_old_verbatim_capture() {
let src = "module m;\n initial begin\n x = req.randomize() with {\n `MY_HALF\n a == 2;\n };\n end\nendmodule\n";
let f = parse_ok(src);
let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else {
panic!("expected an assignment")
};
let ExprKind::WithConstraint { block, .. } = &rhs.kind else {
panic!("expected a with-constraint")
};
let ConstraintBody::Verbatim(raw) = &**block else { panic!("expected the fallback") };
// The `with` keyword is outside the capture; the braces are inside.
assert_eq!(raw.text, "{\n `MY_HALF\n a == 2;\n }");
assert_eq!(raw.text, src[raw.span.as_range()]);
assert_eq!(f.constraint_fallbacks, 1);
}
#[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"
);
}
// ------------------------------------------------------------------
// The mop-up round: docs/features/testbench-mopup/README.md
// ------------------------------------------------------------------
/// The statements of the first module item, which every mop-up statement
/// test wants.
fn block_stmts(f: &SourceFile) -> &[Stmt] {
let m = module_of(f);
let stmt = match &m.items[0].kind {
ItemKind::Initial(s) | ItemKind::Always { stmt: s, .. } => s,
other => panic!("expected an initial/always, got {other:?}"),
};
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
stmts
}
#[test]
fn a_typedef_is_a_statement_inside_a_block() {
// hw/ip/spi_host/dv/env/seq_lib/spi_host_base_vseq.sv:577 and the
// three other spellings the sweep contains, all in one block.
let f = parse_ok(
"module m;\n initial begin\n typedef enum bit {WRITE = 1'b1} rdwr_e;\n \
typedef bit data_result[];\n typedef struct {int a;} s_t;\n \
typedef class fwd;\n end\nendmodule\n",
);
let stmts = block_stmts(&f);
let names: Vec<&str> = stmts
.iter()
.map(|s| match &s.kind {
StmtKind::Typedef(t) => t.name.as_str(),
other => panic!("expected a typedef statement, got {other:?}"),
})
.collect();
assert_eq!(names, ["rdwr_e", "data_result", "s_t", "fwd"]);
}
#[test]
fn a_typedef_statement_carries_the_same_payload_as_the_item() {
// Same node type, so nothing downstream needs a second shape.
let f = parse_ok(
"module m;\n initial begin\n typedef enum bit {A, B} e_t;\n end\nendmodule\n",
);
let StmtKind::Typedef(t) = &block_stmts(&f)[0].kind else { panic!("expected a typedef") };
let TypedefKind::Enum(e) = &t.kind else { panic!("expected an enum") };
assert_eq!(e.members.iter().map(|m| m.name.as_str()).collect::<Vec<_>>(), ["A", "B"]);
}
#[test]
fn a_system_function_call_may_be_a_casting_type() {
// hw/top_earlgrey/ip_autogen/pinmux/rtl/pinmux.sv:490 and
// hw/vendor/pulp_riscv_dbg/debug_rom/debug_rom.sv:67.
for src in [
"module m;\n assign y = $bits(x)'({a, b});\nendmodule\n",
"module m;\n assign y = $clog2(RomSize)'(RomSize);\nendmodule\n",
] {
let f = parse_ok(src);
let m = module_of(&f);
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
let ExprKind::Cast { ty, pattern, .. } = &a.assigns[0].rhs.kind else {
panic!("expected a cast in {src:?}")
};
assert!(!pattern, "the `'(...)` spelling");
assert!(matches!(&ty.kind, ExprKind::Call { .. }), "the casting type is the call");
}
// An *ordinary* call is still not a casting type: the net stays as
// narrow as the corpus needs it.
assert!(parse_err("module m;\n assign y = f(x)'(z);\nendmodule\n")
.contains("unsupported cast base expression"));
}
#[test]
fn an_enum_member_may_carry_a_name_range() {
// hw/top_earlgrey/ip_autogen/rstmgr/rtl/rstmgr_pkg.sv:101 (`[hi:lo]`)
// and hw/top_earlgrey/dv/env/chip_env_pkg.sv:88 (`[N]`).
let f = parse_ok("typedef enum {A[0:1], B, C[16] = 5} e_t;\n");
let ItemKind::Typedef(t) = &f.items[0].kind else { panic!("expected a typedef") };
let TypedefKind::Enum(e) = &t.kind else { panic!("expected an enum") };
assert!(matches!(
e.members[0].range.as_slice(),
[Dim { kind: DimKind::Range { b: Some(_), .. }, .. }]
));
assert!(e.members[1].range.is_empty(), "a plain member has no range");
assert!(matches!(
e.members[2].range.as_slice(),
[Dim { kind: DimKind::Range { b: None, .. }, .. }]
));
assert!(e.members[2].value.is_some(), "the range does not swallow the `= 5`");
}
#[test]
fn a_cast_may_be_applied_to_an_assignment_pattern() {
// hw/dv/sv/cip_lib/cip_base_scoreboard.sv:442.
let f = parse_ok("module m;\n assign y = expected_alert_t'{1, is_fatal};\nendmodule\n");
let m = module_of(&f);
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
let ExprKind::Cast { ty, expr, pattern } = &a.assigns[0].rhs.kind else {
panic!("expected a cast")
};
assert!(*pattern, "the `'{{...}}` spelling");
assert!(matches!(&ty.kind, ExprKind::Ident(n) if n == "expected_alert_t"));
assert!(matches!(&expr.kind, ExprKind::AssignPattern(items) if items.len() == 2));
}
#[test]
fn the_two_cast_spellings_over_a_pattern_stay_distinct() {
// `ty'('{...})` and `ty'{...}` are different token streams; only the
// `pattern` flag keeps the printer from collapsing one into the other.
let f = parse_ok("module m;\n assign y = bar_t'('{a: 1});\nendmodule\n");
let m = module_of(&f);
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
let ExprKind::Cast { expr, pattern, .. } = &a.assigns[0].rhs.kind else {
panic!("expected a cast")
};
assert!(!pattern, "the parens are the cast's, not the pattern's");
assert!(matches!(&expr.kind, ExprKind::AssignPattern(_)));
// And a bare pattern is still a whole expression, not a cast.
let f = parse_ok("module m;\n assign y = '{a: 1};\nendmodule\n");
let m = module_of(&f);
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
assert!(matches!(&a.assigns[0].rhs.kind, ExprKind::AssignPattern(_)));
}
#[test]
fn a_gate_takes_a_multi_value_delay_list() {
// hw/top_earlgrey/ip/ast/rtl/aon_osc.sv:41.
let f = parse_ok(
"module m;\n buf #(RDLY, 0) b0 (o, a);\n and #(1, 2, 3) g (o, a, b);\n \
buf #(5) b1 (o, a);\n buf #5 b2 (o, a);\n buf b3 (o, a);\nendmodule\n",
);
let m = module_of(&f);
let lens: Vec<usize> = m
.items
.iter()
.map(|i| match &i.kind {
ItemKind::GateInstantiation(g) => g.delay.len(),
other => panic!("expected a gate, got {other:?}"),
})
.collect();
assert_eq!(lens, [2, 3, 1, 1, 0]);
// The one-value parenthesized spelling keeps its `Paren` node, which
// is what makes `#(5)` print back as `#(5)` and not as `#5`.
let ItemKind::GateInstantiation(g) = &m.items[2].kind else { panic!("expected a gate") };
assert!(matches!(g.delay[0].kind, ExprKind::Paren { .. }));
}
#[test]
fn a_multi_value_delay_is_refused_where_only_a_gate_may_write_one() {
// A net declaration and a continuous assignment take one delay; the
// message says which construct the list belongs to.
assert!(parse_err("module m;\n wire #(1, 2) w;\nendmodule\n")
.contains("only allowed on a gate instantiation"));
assert!(parse_err("module m;\n assign #(1, 2) y = x;\nendmodule\n")
.contains("only allowed on a gate instantiation"));
}
#[test]
fn a_virtual_interface_type_may_name_a_modport() {
// hw/ip/spi_device/pre_dv/tb/spid_jedec_tb.sv:32 (a declaration) and
// .../spid_common.sv:563 (a task argument).
let f = parse_ok("module m;\n virtual spi_if.tb tb_sif = sif.tb;\nendmodule\n");
let m = module_of(&f);
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") };
assert_eq!(d.qualifiers, ["virtual"]);
assert_eq!(d.ty.name, "spi_if.tb");
assert_eq!(d.declarators[0].name, "tb_sif");
let f = parse_ok("module m;\n task t(virtual spi_if.tb sif);\n endtask\nendmodule\n");
let m = module_of(&f);
let ItemKind::Task(t) = &m.items[0].kind else { panic!("expected a task") };
assert_eq!(t.args[0].ty.name, "spi_if.tb");
assert!(t.args[0].ty.virt.is_some(), "still a virtual interface type");
}
#[test]
fn a_dot_after_a_plain_type_name_is_still_not_a_modport() {
// The widening is scoped to `virtual`, which is what keeps a `.`
// after an identifier reading as a member access everywhere else
// (docs/features/ansi-first-port/README.md, Status).
assert!(parse_err("module m;\n bus_if.mp v;\nendmodule\n").contains("expected"));
}
#[test]
fn a_struct_member_may_be_declared_rand() {
// hw/ip/spi_host/dv/env/spi_host_env_pkg.sv:64 — not LRM-legal, but
// real, vendor-accepted code.
let f = parse_ok("typedef struct {\n rand bit cpol;\n randc int n;\n bit p;\n} c_t;\n");
let ItemKind::Typedef(t) = &f.items[0].kind else { panic!("expected a typedef") };
let TypedefKind::Struct(s) = &t.kind else { panic!("expected a struct") };
assert_eq!(s.members[0].qualifiers, ["rand"]);
assert_eq!(s.members[1].qualifiers, ["randc"]);
assert!(s.members[2].qualifiers.is_empty());
assert_eq!(s.members[0].declarators[0].name, "cpol");
}
#[test]
fn a_foreach_may_skip_a_dimension() {
// hw/ip_templates/flash_ctrl/dv/env/flash_ctrl_env.sv:43. A skipped
// slot is an empty name at the point the source wrote nothing.
let f = parse_ok(
"module m;\n initial begin\n foreach (h[, bank]) x = 1;\n \
foreach (h[i, , k]) y = 2;\n end\nendmodule\n",
);
let stmts = block_stmts(&f);
let StmtKind::Foreach { vars, .. } = &stmts[0].kind else { panic!("expected a foreach") };
assert_eq!(vars.iter().map(|v| v.text.as_str()).collect::<Vec<_>>(), ["", "bank"]);
assert!(vars[0].span.is_empty(), "a skipped slot occupies no source");
let StmtKind::Foreach { vars, .. } = &stmts[1].kind else { panic!("expected a foreach") };
assert_eq!(vars.iter().map(|v| v.text.as_str()).collect::<Vec<_>>(), ["i", "", "k"]);
}
#[test]
fn a_bind_instance_may_be_a_hierarchical_path() {
// hw/ip/entropy_src/dv/tb/tb.sv:94.
let f =
parse_ok("bind prim_packer_fifo : dut.u_core.u_fifo fifo_if #(.P(1)) u (.clk_i);\n");
let ItemKind::Bind(b) = &f.items[0].kind else { panic!("expected a bind") };
assert_eq!(b.target, "prim_packer_fifo");
assert_eq!(
b.instances.iter().map(|i| i.text.as_str()).collect::<Vec<_>>(),
["dut.u_core.u_fifo"]
);
// A bare name and a path may share one list.
let f = parse_ok("bind foo : a.b, plain bar u (.x);\n");
let ItemKind::Bind(b) = &f.items[0].kind else { panic!("expected a bind") };
assert_eq!(
b.instances.iter().map(|i| i.text.as_str()).collect::<Vec<_>>(),
["a.b", "plain"]
);
}
// ------------------------------------------------------------------
// Covergroup bodies (`docs/features/covergroup-bodies/README.md`)
// ------------------------------------------------------------------
fn covergroup_of(f: &SourceFile) -> &CovergroupDecl {
match &class_of(f).items[0].kind {
ItemKind::Covergroup(c) => c,
other => panic!("expected a covergroup, got {other:?}"),
}
}
/// A covergroup body wrapped in the class the corpus always writes it in.
fn cg(body: &str) -> SourceFile {
parse_ok(&format!("class c;\n covergroup g;\n{body}\n endgroup\nendclass\n"))
}
fn cover_items(f: &SourceFile) -> &[CoverItem] {
&covergroup_of(f).items
}
fn coverpoint_of(f: &SourceFile) -> &CoverpointDecl {
match &cover_items(f)[0].kind {
CoverItemKind::Coverpoint(cp) => cp,
other => panic!("expected a coverpoint, got {other:?}"),
}
}
fn cross_of(f: &SourceFile) -> &CrossDecl {
match &cover_items(f)[0].kind {
CoverItemKind::Cross(c) => c,
other => panic!("expected a cross, got {other:?}"),
}
}
/// The bins of the first coverpoint or cross in `f`.
fn bins_of(f: &SourceFile) -> &[BinItem] {
let body = match &cover_items(f)[0].kind {
CoverItemKind::Coverpoint(cp) => cp.body.as_ref(),
CoverItemKind::Cross(c) => c.body.as_ref(),
other => panic!("expected a coverpoint or a cross, got {other:?}"),
};
&body.expect("the body was parsed").items
}
fn bin_of(f: &SourceFile) -> &BinDecl {
match &bins_of(f)[0].kind {
BinItemKind::Bin(b) => b,
other => panic!("expected a bin, got {other:?}"),
}
}
#[test]
fn a_covergroup_header_keeps_its_name_its_args_and_its_end_label() {
let f = parse_ok(
"class c;\n covergroup g (bit [3:0] a, int n);\n coverpoint a;\n endgroup : g\nendclass\n",
);
let g = covergroup_of(&f);
assert_eq!(g.name.text, "g");
assert_eq!(&f.span.as_range().start, &0);
let args = g.args.as_ref().expect("the formal list was parsed");
assert_eq!(args.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["a", "n"]);
assert_eq!(g.end_label.as_ref().expect("the label was kept").text, "g");
assert!(!g.end_semi);
assert_eq!(f.covergroups, 1);
assert_eq!(f.covergroup_fallbacks, 0);
}
#[test]
fn a_header_with_no_parens_records_none_rather_than_an_empty_list() {
// Printing an invented `()` back would change the token stream.
let f = cg(" coverpoint a;");
assert!(covergroup_of(&f).args.is_none());
let f = parse_ok("class c;\n covergroup g ();\n coverpoint a;\n endgroup\nendclass\n");
assert_eq!(covergroup_of(&f).args.as_ref().map(Vec::len), Some(0));
}
#[test]
fn a_sample_function_header_keeps_the_word_and_its_arguments() {
let f = parse_ok(
"class c;\n covergroup g (string n) with function sample (bit [31:0] addr, bit rw);\n coverpoint addr;\n endgroup\nendclass\n",
);
let Some(CoverageEvent::Sample(s)) = &covergroup_of(&f).event else {
panic!("expected a sample function")
};
assert_eq!(s.name.text, "sample");
assert!(s.has_parens);
assert_eq!(s.args.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["addr", "rw"]);
}
#[test]
fn a_clocking_event_header_is_read_by_the_always_at_parser() {
let f = parse_ok(
"class c;\n covergroup g @(posedge clk);\n coverpoint a;\n endgroup\nendclass\n",
);
let Some(CoverageEvent::Clocking { sens: SensList::List(items), .. }) =
&covergroup_of(&f).event
else {
panic!("expected a clocking event")
};
assert_eq!(items.len(), 1);
assert_eq!(items[0].edge.as_deref(), Some("posedge"));
// The bare `@ev` spelling keeps its lack of parentheses.
let f =
parse_ok("class c;\n covergroup g @ev;\n coverpoint a;\n endgroup\nendclass\n");
let Some(CoverageEvent::Clocking { sens: SensList::Bare(_), .. }) =
&covergroup_of(&f).event
else {
panic!("expected a bare event name")
};
}
#[test]
fn a_coverpoint_keeps_its_label_its_expression_and_its_iff() {
let f = cg(" cp_a: coverpoint a + 1 iff (en);");
let cp = coverpoint_of(&f);
assert_eq!(cp.label.as_ref().expect("a label").name.text, "cp_a");
assert!(matches!(cp.expr.kind, ExprKind::Binary { .. }));
assert!(cp.iff.is_some());
assert!(cp.body.is_none());
// An unlabelled coverpoint declares nothing and says so.
let f = cg(" coverpoint a;");
assert!(coverpoint_of(&f).label.is_none());
}
#[test]
fn a_cross_keeps_every_operand_in_order() {
let f = cg(" cr: cross cp_a, cp_b, cp_c;");
let cr = cross_of(&f);
assert_eq!(cr.label.as_ref().expect("a label").name.text, "cr");
assert_eq!(cr.items.len(), 3);
assert!(cr.iff.is_none());
}
#[test]
fn an_option_assignment_is_its_own_item_in_both_places() {
let f = cg(" option.per_instance = 1;\n type_option.weight = 5;\n cp: coverpoint a { option.weight = 2; }");
let items = cover_items(&f);
assert!(matches!(items[0].kind, CoverItemKind::Option(_)));
assert!(matches!(items[1].kind, CoverItemKind::Option(_)));
let CoverItemKind::Coverpoint(cp) = &items[2].kind else { panic!("expected a coverpoint") };
let body = cp.body.as_ref().expect("the body was parsed");
assert!(matches!(body.items[0].kind, BinItemKind::Option(_)));
}
#[test]
fn every_bin_keyword_and_the_wildcard_prefix_are_kept_apart() {
let f = cg(
" cp: coverpoint a {\n bins one = {1};\n wildcard bins w = {4'b1??1};\n ignore_bins ig = {2};\n illegal_bins bad = {3};\n }",
);
let bins = bins_of(&f);
let kinds: Vec<(BinKind, bool)> = bins
.iter()
.map(|b| match &b.kind {
BinItemKind::Bin(b) => (b.kind, b.wildcard),
other => panic!("expected a bin, got {other:?}"),
})
.collect();
assert_eq!(
kinds,
[
(BinKind::Bins, false),
(BinKind::Bins, true),
(BinKind::IgnoreBins, false),
(BinKind::IllegalBins, false),
]
);
}
#[test]
fn a_bin_array_keeps_the_sized_and_unsized_spellings_apart() {
let f = cg(" cp: coverpoint a {\n bins sized[4] = {1};\n bins open[] = {2};\n bins plain = {3};\n }");
let bins = bins_of(&f);
let arrays: Vec<Option<bool>> = bins
.iter()
.map(|b| match &b.kind {
BinItemKind::Bin(b) => b.array.as_ref().map(|a| a.size.is_some()),
other => panic!("expected a bin, got {other:?}"),
})
.collect();
assert_eq!(arrays, [Some(true), Some(false), None]);
}
#[test]
fn a_value_bin_keeps_its_ranges_and_the_dollar_bound() {
let f = cg(" cp: coverpoint a {\n bins v = {0, [1:3], [4:$]};\n }");
let BinSpec::Values(items) = &bin_of(&f).spec else { panic!("expected values") };
assert_eq!(items.len(), 3);
assert!(matches!(items[1].expr.kind, ExprKind::ValueRange { .. }));
assert!(matches!(items[2].expr.kind, ExprKind::ValueRange { .. }));
}
#[test]
fn the_two_default_spellings_are_never_normalized_into_each_other() {
let f = cg(" cp: coverpoint a {\n bins d = default;\n bins s = default sequence;\n }");
let bins = bins_of(&f);
let specs: Vec<&str> = bins
.iter()
.map(|b| match &b.kind {
BinItemKind::Bin(b) => match &b.spec {
BinSpec::Default => "default",
BinSpec::DefaultSequence { .. } => "default sequence",
other => panic!("expected a default, got {other:?}"),
},
other => panic!("expected a bin, got {other:?}"),
})
.collect();
assert_eq!(specs, ["default", "default sequence"]);
}
#[test]
fn a_transition_bin_keeps_every_arrow_comma_and_repetition() {
let f = cg(" cp: coverpoint a {\n bins t = (0 => 1, 2 => 3), (4 => 5);\n bins r = (1'b0[*1:10] => 1'b1[->2] => 1'b0[=1]);\n }");
let bins = bins_of(&f);
let BinItemKind::Bin(first) = &bins[0].kind else { panic!("expected a bin") };
let BinSpec::Transitions(sets) = &first.spec else { panic!("expected transitions") };
assert_eq!(sets.len(), 2);
assert_eq!(sets[0].ranges.len(), 3, "`0 => 1, 2 => 3` is three ranges");
assert_eq!(sets[0].ranges[1].items.len(), 2, "`1, 2` is one range of two items");
assert_eq!(sets[1].ranges.len(), 2);
let BinItemKind::Bin(second) = &bins[1].kind else { panic!("expected a bin") };
let BinSpec::Transitions(sets) = &second.spec else { panic!("expected transitions") };
let ops: Vec<&str> = sets[0]
.ranges
.iter()
.map(|r| r.repeat.as_ref().expect("a repetition").op.as_str())
.collect();
assert_eq!(ops, ["*", "->", "="]);
let first = sets[0].ranges[0].repeat.as_ref().expect("a repetition");
assert!(first.hi.is_some(), "`[*1:10]` has both bounds");
}
#[test]
fn a_single_transition_set_needs_no_arrow_to_be_one() {
// opentitan `hw/ip/rom_ctrl/dv/cov/rom_ctrl_cov_if.sv`:
// `bins zero_delay_5 = (1'b1[*5]);` is a transition list of one range
// with a repetition, not a parenthesized select expression. Which
// grammar a `(` opens is decided by *where it is written* — a
// coverpoint bin or a cross bin — exactly as the LRM decides it.
let f = cg(" cp: coverpoint a {\n bins z = (1'b1[*5]);\n }");
let BinSpec::Transitions(sets) = &bin_of(&f).spec else { panic!("expected transitions") };
assert_eq!(sets.len(), 1);
assert_eq!(sets[0].ranges.len(), 1);
assert_eq!(sets[0].ranges[0].repeat.as_ref().expect("a repetition").op, "*");
// The same parentheses in a *cross* bin are a select expression.
let f = cg(" cr: cross a, b {\n bins z = (binsof(a) || binsof(b));\n }");
assert!(matches!(bin_of(&f).spec, BinSpec::Select(SelectExpr::Paren { .. })));
}
#[test]
fn a_call_may_stand_as_a_bin_spec() {
// opentitan `hw/ip/csrng/dv/cov/csrng_cov_if.sv`:
// `bins single_exc[] = single_masks(num_hw_apps);`. Tools accept it;
// the LRM does not spell it, and reading it costs nothing.
let f = cg(" cp: coverpoint a {\n bins v[] = single_masks(n);\n }");
let BinSpec::Select(SelectExpr::Expr(e)) = &bin_of(&f).spec else {
panic!("expected a call")
};
assert!(matches!(e.kind, ExprKind::Call { .. }));
}
#[test]
fn a_bins_with_filter_is_never_read_as_an_array_method() {
// `with (` is a postfix segment everywhere else in the language; in a
// bin spec it introduces the bin's own filter, and the expression
// parser has to stop in front of it. The flag that says so must not
// survive the operand.
let f = cg(" cp: coverpoint a {\n bins v[] = cp_x with (item > 0);\n }");
let b = bin_of(&f);
assert!(matches!(b.spec, BinSpec::Select(SelectExpr::Expr(_))));
assert!(b.with_expr.is_some(), "the `with` is the bin's, not the expression's");
// And an array method's `with` still parses as one, in the same file.
let f = parse_ok(
"class c;\n covergroup g;\n cp: coverpoint a { bins v[] = cp_x with (item > 0); }\n endgroup\n function int f();\n return q.find with (item > 0);\n endfunction\nendclass\n",
);
assert!(matches!(class_of(&f).items[1].kind, ItemKind::Function(_)));
}
#[test]
fn a_with_filter_and_a_coverpoint_name_spec_are_both_read() {
let f = cg(" cp: coverpoint a {\n bins e[] = cp_x with (item % 2 == 0);\n bins v = {[0:$]} with ($countones(item) != 1);\n }");
let bins = bins_of(&f);
let BinItemKind::Bin(first) = &bins[0].kind else { panic!("expected a bin") };
assert!(matches!(first.spec, BinSpec::Select(SelectExpr::Expr(_))));
assert!(first.with_expr.is_some());
let BinItemKind::Bin(second) = &bins[1].kind else { panic!("expected a bin") };
assert!(matches!(second.spec, BinSpec::Values(_)));
assert!(second.with_expr.is_some());
}
#[test]
fn a_cross_bin_reads_binsof_intersect_and_the_boolean_operators() {
let f = cg(" cr: cross a, b {\n bins sel = binsof(a.x) intersect {0, [1:2]} && !binsof(b);\n }");
let BinSpec::Select(SelectExpr::Binary { lhs, op, rhs, .. }) = &bin_of(&f).spec else {
panic!("expected a select expression")
};
assert_eq!(op, "&&");
let SelectExpr::Binsof(b) = lhs.as_ref() else { panic!("expected a binsof") };
assert_eq!(b.intersect.as_ref().expect("an intersect set").len(), 2);
let SelectExpr::Not { expr, .. } = rhs.as_ref() else { panic!("expected a negation") };
assert!(matches!(**expr, SelectExpr::Binsof(_)));
}
#[test]
fn a_bin_may_carry_its_own_iff() {
let f = cg(" cp: coverpoint a {\n bins v = {1} iff (en);\n }");
assert!(bin_of(&f).iff.is_some());
}
#[test]
fn a_directive_and_a_null_item_stand_where_a_cover_item_belongs() {
let f = cg(" `ifdef FOO\n cp: coverpoint a;\n `endif\n ;");
let items = cover_items(&f);
assert!(matches!(items[0].kind, CoverItemKind::Directive(_)));
assert!(matches!(items[1].kind, CoverItemKind::Coverpoint(_)));
assert!(matches!(items[2].kind, CoverItemKind::Directive(_)));
assert!(matches!(items[3].kind, CoverItemKind::Empty));
// And inside a coverpoint body too.
let f = cg(" cp: coverpoint a {\n `ifdef FOO\n bins v = {1};\n `endif\n ;\n }");
let bins = bins_of(&f);
assert!(matches!(bins[0].kind, BinItemKind::Directive(_)));
assert!(matches!(bins[2].kind, BinItemKind::Directive(_)));
assert!(matches!(bins[3].kind, BinItemKind::Empty));
}
#[test]
fn an_unrecognised_covergroup_rewinds_to_exactly_the_old_capture() {
// A macro supplying a coverpoint's whole bin body, `;` included —
// opentitan `hw/ip/otbn/dv/uvm/env/otbn_env_cov.sv`. Irreducible
// without expanding macros, and the shape the fallback exists for.
let src = "class c;\n covergroup g;\n cp: coverpoint a `GPR_BIN_TYPES\n endgroup : g\nendclass\n";
let f = parse_ok(src);
let item = &class_of(&f).items[0];
let ItemKind::Verbatim(b) = &item.kind else { panic!("expected a verbatim block") };
assert_eq!(b.text, "covergroup g;\n cp: coverpoint a `GPR_BIN_TYPES\n endgroup : g");
assert_eq!(b.text, src[b.span.as_range()], "the capture slices back to its span");
assert_eq!(b.col, 3, "the re-indent column is the covergroup's own");
assert_eq!(f.covergroups, 0);
assert_eq!(f.covergroup_fallbacks, 1);
}
#[test]
fn a_covergroup_fallback_keeps_the_comments_written_around_it() {
// The speculative parse harvests comments into nodes it then throws
// away; the rewind must put both pending buckets back.
let f = parse_ok(
"class k;\n // head\n covergroup g;\n cp: coverpoint a `GPR_BINS\n endgroup // tail\n int b;\nendclass\n",
);
let item = &class_of(&f).items[0];
assert!(matches!(item.kind, ItemKind::Verbatim(_)));
assert_eq!(item.meta.leading[0].text, "// head");
assert_eq!(item.meta.trailing.as_ref().expect("trailing").text, "// tail");
}
#[test]
fn a_covergroup_with_no_endgroup_falls_back_and_reports_it_once() {
let src = "class c;\n covergroup g;\n coverpoint a;\n";
let (f, diags) = parse_tolerant(tokenize(src).expect("lex error"), src);
assert_eq!(f.covergroups, 0);
assert_eq!(f.covergroup_fallbacks, 1);
assert_eq!(
diags.iter().filter(|d| d.message.contains("endgroup")).count(),
1,
"one diagnostic, from the verbatim path: {diags:?}"
);
}
#[test]
fn a_stray_semicolon_after_endgroup_is_reproduced() {
let f =
parse_ok("class c;\n covergroup g;\n coverpoint a;\n endgroup : g;\nendclass\n");
let g = covergroup_of(&f);
assert_eq!(g.end_label.as_ref().expect("a label").text, "g");
assert!(g.end_semi);
}
#[test]
fn a_repeat_bracket_never_steals_an_ordinary_index() {
// The `[`-guard `at_repeat_bracket` installs must not change how any
// other expression parses.
let f = parse_ok("module m;\n assign y = q[3] + r[a:b] + s[i +: 2];\nendmodule\n");
assert!(matches!(f.items[0].kind, ItemKind::Module(_)));
}
/// Every comment text a covergroup at the head of `src`'s class holds,
/// in one flat list — what the slot pins assert against.
fn covergroup_comments(src: &str) -> Vec<String> {
let f = parse_ok(src);
let g = covergroup_of(&f);
let mut out: Vec<String> = Vec::new();
macro_rules! push {
($cs:expr) => {
out.extend($cs.iter().map(|c| c.text.clone()))
};
}
push!(&g.before_name);
push!(&g.before_args);
match &g.event {
Some(CoverageEvent::Sample(s)) => {
push!(&s.before_with);
push!(&s.after_with);
push!(&s.after_function);
push!(&s.before_args);
}
Some(CoverageEvent::Clocking { before, .. }) => push!(before),
None => {}
}
push!(&g.before_semi);
push!(&g.before_end_semi);
for item in &g.items {
push!(&item.before_semi);
match &item.kind {
CoverItemKind::Coverpoint(cp) => {
if let Some(l) = &cp.label {
push!(&l.comments.before);
push!(&l.comments.after);
}
push!(&cp.after_kw);
push_iff(&mut out, cp.iff.as_deref());
push!(&cp.before_body);
push_body(&mut out, cp.body.as_ref());
}
CoverItemKind::Cross(cr) => {
if let Some(l) = &cr.label {
push!(&l.comments.before);
push!(&l.comments.after);
}
push!(&cr.after_kw);
push_iff(&mut out, cr.iff.as_deref());
push!(&cr.before_body);
push_body(&mut out, cr.body.as_ref());
}
CoverItemKind::Option(o) => {
push!(&o.comments.before);
push!(&o.comments.after);
}
CoverItemKind::Directive(_) | CoverItemKind::Empty => {}
}
}
out
}
fn push_iff(out: &mut Vec<String>, iff: Option<&CoverIff>) {
let Some(i) = iff else { return };
for cs in [&i.before_kw, &i.after_kw, &i.after_open, &i.before_close] {
out.extend(cs.iter().map(|c| c.text.clone()));
}
}
fn push_body(out: &mut Vec<String>, body: Option<&CoverBody>) {
let Some(body) = body else { return };
for item in &body.items {
out.extend(item.before_semi.iter().map(|c| c.text.clone()));
let BinItemKind::Bin(b) = &item.kind else { continue };
for cs in
[&b.after_wildcard, &b.before_name, &b.eq_comments.before, &b.eq_comments.after]
{
out.extend(cs.iter().map(|c| c.text.clone()));
}
if let Some(a) = &b.array {
for cs in [&a.before, &a.comments.before, &a.comments.after] {
out.extend(cs.iter().map(|c| c.text.clone()));
}
}
if let BinSpec::DefaultSequence { comments } = &b.spec {
out.extend(comments.iter().map(|c| c.text.clone()));
}
if let Some(w) = &b.with_expr {
for cs in [&w.before_kw, &w.after_kw, &w.after_open, &w.before_close] {
out.extend(cs.iter().map(|c| c.text.clone()));
}
}
push_iff(out, b.iff.as_deref());
}
}
#[test]
fn every_covergroup_header_slot_keeps_its_comment() {
let got = covergroup_comments(
"class c;\n covergroup /*a*/ g /*b*/ (int n) /*c*/ with /*d*/ function /*e*/ sample /*f*/ (int x) /*g*/ ;\n coverpoint x;\n endgroup : g /*h*/ ;\nendclass\n",
);
assert_eq!(got, ["/*a*/", "/*b*/", "/*c*/", "/*d*/", "/*e*/", "/*f*/", "/*g*/", "/*h*/"]);
}
#[test]
fn every_coverpoint_slot_keeps_its_comment() {
let got = covergroup_comments(
"class c;\n covergroup g;\n cp /*a*/ : /*b*/ coverpoint /*c*/ x /*d*/ iff /*e*/ ( /*f*/ en /*g*/ ) /*h*/ {\n }\n endgroup\nendclass\n",
);
assert_eq!(got, ["/*a*/", "/*b*/", "/*c*/", "/*d*/", "/*e*/", "/*f*/", "/*g*/", "/*h*/"]);
}
#[test]
fn every_bin_slot_keeps_its_comment() {
let got = covergroup_comments(
"class c;\n covergroup g;\n cp: coverpoint x {\n wildcard /*a*/ bins /*b*/ v /*c*/ [ /*d*/ 4 /*e*/ ] /*f*/ = /*g*/ {1} /*h*/ with /*i*/ ( /*j*/ item /*k*/ ) /*l*/ iff /*m*/ ( /*n*/ en /*o*/ ) /*p*/ ;\n }\n endgroup\nendclass\n",
);
assert_eq!(
got,
[
"/*p*/", "/*a*/", "/*b*/", "/*f*/", "/*g*/", "/*c*/", "/*d*/", "/*e*/", "/*h*/",
"/*i*/", "/*j*/", "/*k*/", "/*l*/", "/*m*/", "/*n*/", "/*o*/"
]
);
}
#[test]
fn the_option_assignment_slots_keep_their_comments() {
let got = covergroup_comments(
"class c;\n covergroup g;\n option.per_instance /*a*/ = /*b*/ 1 /*c*/ ;\n endgroup\nendclass\n",
);
assert_eq!(got, ["/*c*/", "/*a*/", "/*b*/"]);
}
#[test]
fn the_gap_before_a_cover_items_semicolon_that_was_not_written_belongs_to_what_follows() {
// A comment on the line after a coverpoint's `}` is the *next*
// item's leading comment, not the closed item's `before_semi`.
let f = cg(" cp: coverpoint x {\n }\n // why\n cr: cross a, b;");
let items = cover_items(&f);
assert!(items[0].before_semi.is_empty());
assert_eq!(items[1].meta.leading[0].text, "// why");
}
}