Decomposition, lane A: vlog_parser's parser.rs and ast.rs become twenty-seven modules, a pure move

TODO section 28, lane A (the file-size rule in CLAUDE.md).
parser.rs (8 786 production + 5 044 test lines) becomes parser/{mod,
cursor, recover, directive, split, verbatim, item, module, decl, tf,
instance, stmt, keyword_stmt, expr, primary, class, covergroup,
assertion, sva}.rs with the tests regrouped into parser/tests/ (14
files, 309 tests, same names and bodies); ast.rs (3 313) becomes
ast/{mod, module, decl, stmt, expr, class, covergroup, sva}.rs, every
type re-exported so vlog_parser::ast::X is unchanged. Nothing over 800
production lines; the two keyword dispatch tables kept whole and
documented as such, parse_keyword_stmt in a file of its own. Carved by
a line-range manifest that had to concatenate back to the original
byte for byte before writing; 149 methods and 18 items pub(super) as
the compiler demanded. Proof: per-binary test counts identical
(workspace 3 215 / 48), 4 807 corpus + opentitan files byte-identical
to the v0.33.0 binary, cargo doc item list unchanged, and a multiset +
signature census done by the dev, redone by QA, re-run by the lead.

docs/features/decomposition-parser/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-09-02 21:13:32 -07:00
1 parent 159f6a0bd8
commit 9b93f33ae3
45 files changed
+17999 -17241

No files matched your search

+2 -1
View File
@@ -3002,8 +3002,9 @@ lane a subsection with its module map, line-range table and pinned
counts), `docs/topo.md` §3.1 primary-home matrix updated to the new
module names, `README.md`'s architecture section updated. Runs AFTER
§27 (every lane touches its files).
- [ ] Lane A `vlog_parser` — parser/ and ast/ module maps; tests moved;
- [x] Lane A `vlog_parser` — parser/ and ast/ module maps; tests moved;
counts pinned; byte-identity proven
(`docs/features/decomposition-parser/README.md`)
- [ ] Lane B `vlog_formatter` — format/ module map; counts; byte-identity
- [ ] Lane C `lucisv_server` — server/ and completion/ module maps;
tests out of server.rs first; counts; e2e unchanged; vsix smoke
File diff suppressed because it is too large. Load diff
+294
View File
@@ -0,0 +1,294 @@
//! Classes and their constraint blocks (IEEE 1800 §8, §18.5).
use super::*;
/// A `class` declaration. Its body is an ordinary item list, so every item
/// kind that already works at module or package scope — declarations,
/// `typedef`, `localparam`, `import`, compiler directives, macro invocations
/// — works inside a class without any per-site code.
#[derive(Debug)]
pub struct ClassDecl {
/// Keywords written before `class`: `virtual`, the class-member
/// qualifiers, and the `interface` of an `interface class` (IEEE 1800
/// §8.26). Kept as a list so the source order is reproduced verbatim —
/// see [`ClassDecl::is_interface_class`].
pub prefix: Vec<Qualifier>,
/// Comments written between the qualifier run, the `class` keyword and
/// the name — the header's own `class /*c*/ c` slot.
pub before_name: Vec<Comment>,
/// `static`/`automatic` lifetime written after `class`, if any.
pub lifetime: Option<String>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// Comments written between the class name and the `#` of its parameter
/// port list.
pub param_comments: Vec<Comment>,
/// Comments written between that `#` and its `(`.
pub param_after_hash: Vec<Comment>,
/// `None` when the header wrote no `#( ... )`; an empty `Some` is a
/// written-but-empty `#()`.
pub param_ports: Option<Vec<ParamPort>>,
/// Directives written between the parameter ports, in source order.
pub param_directives: Vec<ListDirective>,
/// Comments written after the last parameter port and before its `)`.
pub param_dangling: Vec<Comment>,
/// The `extends Base #( ... )` clause, if written.
pub extends: Option<ClassExtends>,
/// Interface classes named by `implements A, B`.
pub implements: Vec<Name>,
/// Comments written between the header's last token and its `;`.
pub before_semi: Vec<Comment>,
pub items: Vec<Item>,
pub dangling: Vec<Comment>,
/// Comments written in the two gaps of `endclass : c`.
pub end_label_comments: Box<LabelComments>,
/// Label after `endclass :`.
pub end_label: Option<String>,
/// Byte range of `end_label`.
pub end_label_span: Option<TextRange>,
}
impl ClassDecl {
/// True for an `interface class` (IEEE 1800 §8.26) — a class whose body
/// may hold only pure virtual prototypes, parameters and typedefs, and
/// which other classes name in an `implements` clause rather than
/// `extends`. It is an ordinary [`ClassDecl`] everywhere else: same
/// header, same `endclass`, same symbol.
pub fn is_interface_class(&self) -> bool {
self.prefix.iter().any(|q| q.text == "interface")
}
}
/// The `extends Base #( ... )` clause of a class header. The overrides are
/// [`Connection`]s — the same node an instantiation's `#( ... )` uses, because
/// both spell named (`.CFG_T(cfg_t)`) and ordered (`cfg_t`) overrides the same
/// way.
#[derive(Debug)]
pub struct ClassExtends {
/// Comments written between the `#` of an override list and its `(`.
pub after_hash: Vec<Comment>,
/// The base-class name as written, package scope included (`pkg::base`).
pub name: String,
/// Byte range covering `name`, its `::` chain included.
pub name_span: TextRange,
/// Comments written between the base-class name and the `#`.
pub param_comments: Vec<Comment>,
/// `None` when no `#( ... )` was written.
pub params: Option<Vec<Connection>>,
/// Directives written between the overrides, in source order.
pub param_directives: Vec<ListDirective>,
/// Code extent of the clause, from `extends` through its last token.
pub span: TextRange,
}
// ----------------------------------------------------------------------
// Constraints (IEEE 1800 §18.5)
// ----------------------------------------------------------------------
/// A `constraint` declaration: `constraint c { ... }`, the out-of-block
/// `constraint my_class::c { ... }` definition of an `extern` prototype
/// (IEEE 1800 §18.5.2), or the prototype itself.
#[derive(Debug)]
pub struct ConstraintDecl {
/// The member qualifiers written before the keyword — `static`,
/// `extern`, `pure`, `local`, `protected` — in source order.
pub qualifiers: Vec<Qualifier>,
/// The `my_class::` of an out-of-block definition, as written and
/// without the trailing `::`. `None` for the ordinary in-class form.
pub scope: Vec<ScopeSeg>,
pub name: Name,
/// Comments written between the `constraint` keyword and the name.
pub before_name: Vec<Comment>,
/// Comments written between the name and whatever closes the header: the
/// `{` of a body, or a prototype's `;`.
pub after_name: Vec<Comment>,
/// `None` for a prototype (`constraint c;`), which has no braces.
pub body: Option<ConstraintSet>,
/// Comments written between the closing `}` and the stray `;`.
pub before_semi: Vec<Comment>,
/// True when a stray `;` followed the closing `}`. Both spellings occur
/// in real code, so the formatter reproduces whichever was written.
pub semi: bool,
}
/// The `{ ... }` of a `randomize() with { ... }` inline constraint
/// (IEEE 1800 §18.7).
///
/// Unlike a `constraint` declaration — whose unrecognised bodies rewind to a
/// whole-item [`ItemKind::Verbatim`] — a `with` block sits inside an
/// expression, so its fallback has to live here.
#[derive(Debug, Clone)]
pub enum ConstraintBody {
Items(ConstraintSet),
/// A body the constraint grammar did not recognise, copied byte for byte
/// exactly as every `with` block was before this round.
Verbatim(RawText),
}
/// A `constraint_set` (IEEE 1800 A.1.10): either a braced list of items or a
/// single unbraced item, which is what an implication's right-hand side and a
/// constraint `if` body may be written as.
#[derive(Debug, Clone)]
pub struct ConstraintSet {
/// True when the source wrote the `{ ... }`. A set written without braces
/// holds exactly one item, and printing it back without them is what
/// keeps the token stream equal.
pub braced: bool,
pub items: Vec<ConstraintItem>,
/// Comments written after the last item and before the closing `}`.
pub dangling: Vec<Comment>,
/// Code extent of the set, its braces included.
pub span: TextRange,
}
/// One `constraint_expression` of a [`ConstraintSet`].
#[derive(Debug, Clone)]
pub struct ConstraintItem {
pub meta: Meta,
pub kind: ConstraintItemKind,
/// Comments written between the item's last token and the `;` that ends
/// it. They print on the item's side of the `;`, which is where the
/// source put them — printing them after it moves a comment across a
/// token and the safety net rejects the output, exactly as
/// [`Meta::before_sep`] documents for a list element. Always empty for a
/// kind [`ConstraintItemKind::takes_semi`] is false for.
pub before_semi: Vec<Comment>,
/// Code extent of the item, its `;` included.
pub span: TextRange,
}
/// Comments written in the fixed slots of a constraint `if` or `foreach`
/// header, kept per slot so none of them drifts across a token.
#[derive(Debug, Clone, Default)]
pub struct HeaderComments {
/// Between the keyword and the `(`.
pub after_kw: Vec<Comment>,
/// Just inside the `(`.
pub after_open: Vec<Comment>,
/// Just before the `)`.
pub before_close: Vec<Comment>,
/// Between the `)` and a **braced** body. A body written without braces
/// leaves them to its own item's leading comments, which is where the
/// source's own line break already puts them.
pub before_body: Vec<Comment>,
}
#[derive(Debug, Clone)]
pub enum ConstraintItemKind {
/// `[soft ]expression_or_dist ;`. A `dist` is part of `expr`
/// ([`ExprKind::Dist`]), because `soft x dist { ... };` applies `soft` to
/// the whole of it.
Expr {
soft: bool,
/// Comments written between `soft` and the expression. Empty unless
/// `soft` is true.
after_soft: Vec<Comment>,
expr: Expr,
},
/// `expression -> constraint_set` (IEEE 1800 §18.5.6).
///
/// The `->` of an implication is *not* the `->` operator
/// [`Parser::parse_implication`](crate::parser::Parser) reads, because its
/// right-hand side may be a braced set; the constraint item parser takes
/// the operand with the implication level switched off and reads the arrow
/// itself.
Implication {
cond: Expr,
/// Comments written on either side of the `->`, kept per side so
/// neither drifts across it.
comments: Box<BinaryComments>,
set: ConstraintSet,
},
/// `if (expr) constraint_set [else constraint_set]` (IEEE 1800 §18.5.6).
If {
cond: Expr,
/// Comments written in the `if ( ... )` header's four slots.
comments: Box<HeaderComments>,
then: ConstraintSet,
/// Comments written between the `then` set and the `else`.
else_comments: Vec<Comment>,
/// Comments written between the `else` and the set it introduces,
/// when that set opens with a `{` or with the `if` of a chain.
after_else: Vec<Comment>,
els: Option<Box<ConstraintSet>>,
},
/// `foreach (array[i, j]) constraint_set` (IEEE 1800 §18.5.8). A skipped
/// dimension is an empty-text [`Name`], exactly as
/// [`StmtKind::Foreach`] spells one.
Foreach {
array: Expr,
vars: Vec<ForeachVar>,
/// Comments written around the loop-variable bracket, as
/// [`StmtKind::Foreach`] keeps them.
var_comments: Box<SegmentComments>,
/// Comments written in the `foreach ( ... )` header's four slots.
comments: Box<HeaderComments>,
set: ConstraintSet,
},
/// `solve a, b before c, d;` (IEEE 1800 §18.5.10).
SolveBefore {
solve: Vec<ExprItem>,
/// Comments written between the last `solve` operand and the
/// `before` keyword. The ones written *after* `before` need no slot:
/// the first operand past it harvests them as its own leading
/// comments, which prints them in the same place.
before_comments: Vec<Comment>,
before: Vec<ExprItem>,
},
/// `unique { a, b };` (IEEE 1800 §18.5.5).
Unique {
items: Vec<ExprItem>,
/// Comments written between `unique` and the `{`.
comments: Vec<Comment>,
},
/// `disable soft x;` (IEEE 1800 §18.5.14.1).
DisableSoft {
expr: Expr,
/// Comments written on either side of the `soft`.
comments: Box<BinaryComments>,
},
/// A compiler directive, or a macro invocation, standing where a
/// constraint item belongs — the same posture directives keep at item and
/// statement position: passed through, never evaluated.
Directive(RawText),
/// A lone `;`.
Empty,
}
impl ConstraintItemKind {
/// True for the kinds a `;` terminates.
///
/// [`ConstraintItemKind::Empty`] *is* its `;`, a directive carries none,
/// and an implication, an `if` and a `foreach` end in a constraint set
/// whose own last item owns whatever `;` there is. One answer, read by
/// the parser (which consumes the `;`) and by the formatter (which
/// writes it back), so the two can never disagree about who owns it.
pub fn takes_semi(&self) -> bool {
matches!(
self,
ConstraintItemKind::Expr { .. }
| ConstraintItemKind::SolveBefore { .. }
| ConstraintItemKind::Unique { .. }
| ConstraintItemKind::DisableSoft { .. }
)
}
}
/// One `value_range [ := | :/ weight ]` of a [`ExprKind::Dist`] set
/// (IEEE 1800 §18.5.4).
#[derive(Debug, Clone)]
pub struct DistItem {
pub meta: Meta,
/// The value or `[lo:hi]` range ([`ExprKind::ValueRange`]).
pub value: Expr,
/// `:=` or `:/`; `None` when no weight was written. The two mean
/// different things — `:=` weights every value in the range, `:/` splits
/// one weight across it — so they are never normalized into each other.
pub op: Option<String>,
/// Comments written on either side of that operator.
pub op_comments: Box<BinaryComments>,
pub weight: Option<Expr>,
/// Code extent of the element.
pub span: TextRange,
}
+407
View File
@@ -0,0 +1,407 @@
//! Covergroups (IEEE 1800 §19): the declaration, coverpoints and crosses,
//! and the bins sub-grammar.
use super::*;
/// A `covergroup g (args) with function sample (args); ... endgroup : g`
/// declaration and everything inside it (IEEE 1800 §19.3).
#[derive(Debug)]
pub struct CovergroupDecl {
/// The member qualifiers written before the keyword (`local`, `static`,
/// `protected`), in source order.
pub qualifiers: Vec<Qualifier>,
/// Comments written between the `covergroup` keyword and the name.
pub before_name: Vec<Comment>,
pub name: Name,
/// Comments written between the name and the `(` of the formal list.
/// Claimed only when that `(` was really written.
pub before_args: Vec<Comment>,
/// The `(bit [3:0] a)` formal argument list. `None` when the source wrote
/// no parens at all — printing an empty `()` back would be a token-stream
/// change the safety net refuses.
pub args: Option<Vec<TfArg>>,
/// The `coverage_event` of the header. IEEE 1800 §19.3 makes the two
/// spellings alternatives, so one field holds whichever was written.
pub event: Option<CoverageEvent>,
/// Comments written between the header's last token and its `;`.
pub before_semi: Vec<Comment>,
pub items: Vec<CoverItem>,
/// Comments written after the last item and before `endgroup`.
pub dangling: Vec<Comment>,
/// Comments written in the two gaps of `endgroup : g`.
pub end_label_comments: Box<LabelComments>,
/// The label of `endgroup : g`.
pub end_label: Option<Name>,
/// Comments written between `endgroup` (or its label) and a stray `;`.
pub before_end_semi: Vec<Comment>,
/// A stray `;` written after `endgroup`. Both spellings occur in real
/// code, so the formatter reproduces whichever was written.
pub end_semi: bool,
}
/// The `coverage_event` of a covergroup header (IEEE 1800 §19.3).
#[derive(Debug)]
pub enum CoverageEvent {
/// `with function sample ( tf_port_list )` — the covergroup is sampled by
/// an explicit call rather than by an event.
Sample(Box<SampleFn>),
/// `@(posedge clk)`, `@ev` — an ordinary clocking event, read by the very
/// parser an `always @(...)` uses.
Clocking {
/// Comments written between the header and the `@`.
before: Vec<Comment>,
sens: SensList,
},
}
/// The `with function sample (...)` half of a covergroup header.
///
/// `sample` is matched **by text**, not reserved: see
/// `docs/features/covergroup-bodies/README.md`.
#[derive(Debug)]
pub struct SampleFn {
/// Comments written between the header and the `with`.
pub before_with: Vec<Comment>,
/// Comments written between `with` and `function`.
pub after_with: Vec<Comment>,
/// Comments written between `function` and `sample`.
pub after_function: Vec<Comment>,
/// The word `sample`, with its span — a method of the covergroup, so it
/// gets a name of its own.
pub name: Name,
/// Comments written between `sample` and the `(`.
pub before_args: Vec<Comment>,
/// True when the source wrote `( ... )` at all.
pub has_parens: bool,
pub args: Vec<TfArg>,
}
/// One `coverage_spec_or_option` of a covergroup body.
#[derive(Debug)]
pub struct CoverItem {
pub meta: Meta,
pub kind: CoverItemKind,
/// Comments written between the item's last token and the `;` that ends
/// it. Always empty for a kind [`CoverItemKind::takes_semi`] is false for.
pub before_semi: Vec<Comment>,
/// Code extent of the item, its `;` or `}` included.
pub span: TextRange,
}
#[derive(Debug)]
pub enum CoverItemKind {
Coverpoint(Box<CoverpointDecl>),
Cross(Box<CrossDecl>),
/// `option.per_instance = 1;` / `type_option.weight = 5;`
Option(Box<OptionAssign>),
/// A compiler directive, or a macro invocation, standing where a cover
/// item belongs — the same posture directives keep at item and statement
/// position: passed through, never evaluated.
Directive(RawText),
/// A lone `;`.
Empty,
}
impl CoverItemKind {
/// True for the items a `;` terminates.
///
/// A coverpoint or a cross that wrote a `{ ... }` body ends at the brace;
/// one that did not ends at a `;`. One answer, read by the parser (which
/// consumes the `;`) and by the formatter (which writes it back), so the
/// two can never disagree about who owns it — the rule
/// [`ConstraintItemKind::takes_semi`] states for constraints.
pub fn takes_semi(&self) -> bool {
match self {
CoverItemKind::Coverpoint(cp) => cp.body.is_none(),
CoverItemKind::Cross(c) => c.body.is_none(),
CoverItemKind::Option(_) => true,
CoverItemKind::Directive(_) | CoverItemKind::Empty => false,
}
}
}
/// `[label :] coverpoint expr [iff (expr)] [{ bins }]` (IEEE 1800 §19.5).
#[derive(Debug)]
pub struct CoverpointDecl {
/// The `cp_name :` label. `None` for an unlabelled coverpoint, which
/// declares nothing.
pub label: Option<CoverLabel>,
/// Comments written between the `coverpoint` keyword and the expression.
pub after_kw: Vec<Comment>,
pub expr: Expr,
pub iff: Option<Box<CoverIff>>,
/// Comments written between the header and the `{` of a body.
pub before_body: Vec<Comment>,
pub body: Option<CoverBody>,
}
/// `[label :] cross a, b [iff (expr)] [{ bins }]` (IEEE 1800 §19.6).
#[derive(Debug)]
pub struct CrossDecl {
pub label: Option<CoverLabel>,
/// Comments written between the `cross` keyword and the first operand.
pub after_kw: Vec<Comment>,
/// The crossed coverpoints, named or written as expressions.
pub items: Vec<ExprItem>,
pub iff: Option<Box<CoverIff>>,
/// Comments written between the header and the `{` of a body.
pub before_body: Vec<Comment>,
pub body: Option<CoverBody>,
}
/// The `name :` in front of a coverpoint or a cross — the name the covergroup
/// declares for it, and what `cg.cp` reaches.
#[derive(Debug)]
pub struct CoverLabel {
pub name: Name,
/// Comments written on either side of the `:`.
pub comments: Box<BinaryComments>,
}
/// The `iff ( expr )` guard a coverpoint, a cross or a bin may carry.
#[derive(Debug)]
pub struct CoverIff {
/// Comments written between the construct and the `iff`.
pub before_kw: Vec<Comment>,
/// Comments written between `iff` and the `(`.
pub after_kw: Vec<Comment>,
/// Comments written just inside the `(`.
pub after_open: Vec<Comment>,
/// Comments written just before the `)`.
pub before_close: Vec<Comment>,
pub expr: Expr,
}
/// The `{ ... }` body of a coverpoint or a cross: bins and options.
#[derive(Debug)]
pub struct CoverBody {
pub items: Vec<BinItem>,
/// Comments written after the last item and before the closing `}`.
pub dangling: Vec<Comment>,
/// Code extent of the body, its braces included.
pub span: TextRange,
}
/// One `bins_or_options` of a coverpoint or cross body.
#[derive(Debug)]
pub struct BinItem {
pub meta: Meta,
pub kind: BinItemKind,
/// Comments written between the item's last token and its `;`.
pub before_semi: Vec<Comment>,
/// Code extent of the item, its `;` included.
pub span: TextRange,
}
#[derive(Debug)]
pub enum BinItemKind {
Bin(Box<BinDecl>),
Option(Box<OptionAssign>),
Directive(RawText),
Empty,
}
impl BinItemKind {
/// True for the items a `;` terminates — everything but a directive,
/// which carries none, and a null item, which *is* its `;`.
pub fn takes_semi(&self) -> bool {
matches!(self, BinItemKind::Bin(_) | BinItemKind::Option(_))
}
}
/// `option.per_instance = 1;` / `type_option.weight = 5;` (IEEE 1800 §19.7).
///
/// The target is kept as the expression it is written as, rather than split
/// into a keyword and a path: an option name resolves to nothing lucisv
/// models, and the expression printer already writes a dotted chain back
/// exactly as it was written. See `docs/features/covergroup-bodies/README.md`.
#[derive(Debug)]
pub struct OptionAssign {
/// `option.per_instance` / `type_option.weight`, as written.
pub target: Expr,
/// Comments written on either side of the `=`.
pub comments: Box<BinaryComments>,
pub value: Expr,
}
/// `[wildcard] bins name[[expr]] = spec [with (expr)] [iff (expr)];`
/// (IEEE 1800 §19.5.1) — and the `bins name = select_expression` of a cross
/// body (§19.6.1), which differs only in what the spec may be.
#[derive(Debug)]
pub struct BinDecl {
pub wildcard: bool,
/// Comments written between `wildcard` and the bins keyword.
pub after_wildcard: Vec<Comment>,
pub kind: BinKind,
/// Comments written between the bins keyword and the name.
pub before_name: Vec<Comment>,
pub name: Name,
/// The `[]` or `[expr]` written after the name — an array of bins.
pub array: Option<Box<BinArray>>,
/// Comments written on either side of the `=`.
pub eq_comments: Box<BinaryComments>,
pub spec: BinSpec,
/// `with ( expr )` written after the spec.
pub with_expr: Option<Box<BinWith>>,
pub iff: Option<Box<CoverIff>>,
}
/// Which of the three bins keywords was written. They mean different things,
/// so they are never normalized into each other.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinKind {
Bins,
IgnoreBins,
IllegalBins,
}
impl BinKind {
/// The keyword as written.
pub fn as_str(self) -> &'static str {
match self {
BinKind::Bins => "bins",
BinKind::IgnoreBins => "ignore_bins",
BinKind::IllegalBins => "illegal_bins",
}
}
}
/// The `[]` or `[expr]` after a bin name: an array of bins, sized or not.
#[derive(Debug)]
pub struct BinArray {
/// Comments written between the bin name and the `[`.
pub before: Vec<Comment>,
/// Comments written just inside the `[` and just before the `]`.
pub comments: Box<BinaryComments>,
/// `None` for the unsized `[]` spelling.
pub size: Option<Expr>,
}
/// What a bin is defined as.
#[derive(Debug)]
pub enum BinSpec {
/// `= { 0, [1:3], $ }` — a covergroup range list.
Values(Vec<ExprItem>),
/// `= (a => b), (c => d)` — one or more transition sets
/// (IEEE 1800 §19.5.1.2).
Transitions(Vec<TransSet>),
/// `= default`.
Default,
/// `= default sequence`.
DefaultSequence {
/// Comments written between `default` and `sequence`.
comments: Vec<Comment>,
},
/// `= cp_name`, and the `binsof(a) intersect {0} && !binsof(b)` select
/// expression of a cross body (IEEE 1800 §19.6.1).
Select(SelectExpr),
}
/// The `with ( expr )` filter written after a bin's values
/// (IEEE 1800 §19.5.1.1). `item` inside it is the implicit iteration
/// variable, which declares nothing.
#[derive(Debug)]
pub struct BinWith {
/// Comments written between the spec and the `with`.
pub before_kw: Vec<Comment>,
/// Comments written between `with` and the `(`.
pub after_kw: Vec<Comment>,
/// Comments written just inside the `(`.
pub after_open: Vec<Comment>,
/// Comments written just before the `)`.
pub before_close: Vec<Comment>,
pub expr: Expr,
}
/// One `( trans_set )` of a transition bin: `(a => b, c => d)`.
#[derive(Debug)]
pub struct TransSet {
pub meta: Meta,
/// The `=>`-separated ranges. Always at least one.
pub ranges: Vec<TransRange>,
/// Comments written after the last range and before the `)`.
pub dangling: Vec<Comment>,
/// Code extent of the set, its parens included.
pub span: TextRange,
}
/// One `trans_range_list` of a [`TransSet`]: a comma-separated value list
/// with an optional repetition.
#[derive(Debug)]
pub struct TransRange {
/// Comments written before the `=>` that introduces this range, and after
/// it. Both empty on the first range of a set, which no `=>` precedes.
pub arrow_comments: Box<BinaryComments>,
pub items: Vec<ExprItem>,
pub repeat: Option<Box<TransRepeat>>,
}
/// `[* 3]`, `[* 1:$]`, `[-> 2]`, `[= 1]` — a transition's repetition
/// (IEEE 1800 §19.5.1.2). The three operators mean different things, so each
/// is printed back exactly as written.
#[derive(Debug)]
pub struct TransRepeat {
/// Comments written between the range and the `[`.
pub before: Vec<Comment>,
/// Comments written just inside the `[`, in front of the operator.
pub after_open: Vec<Comment>,
/// `*`, `->` or `=`, without the brackets.
pub op: String,
/// Comments written just after that operator (`before`) and just before
/// the `]` (`after`).
pub comments: Box<BinaryComments>,
pub lo: Expr,
/// The `hi` of a `[* lo:hi]` range.
pub hi: Option<Expr>,
/// Comments written on either side of the `:` of that range.
pub colon_comments: Box<BinaryComments>,
}
/// A cross bin's `select_expression` (IEEE 1800 §19.6.1).
#[derive(Debug)]
pub enum SelectExpr {
/// `binsof ( name ) [ intersect { ranges } ]`.
Binsof(Box<BinsofSel>),
/// `! select_condition`.
Not {
/// Comments written between the `!` and its operand.
comments: Vec<Comment>,
expr: Box<SelectExpr>,
},
/// `a && b`, `a || b`. Read left-associatively with one precedence
/// level: lucisv evaluates neither operator and prints no parentheses of
/// its own, so the shape of the tree cannot reach the output.
Binary {
lhs: Box<SelectExpr>,
op: String,
/// Comments written on either side of the operator.
comments: Box<BinaryComments>,
rhs: Box<SelectExpr>,
},
/// `( select_expression )`.
Paren {
/// Comments written just inside either paren.
comments: Box<BinaryComments>,
expr: Box<SelectExpr>,
},
/// A plain coverpoint name: the `= cp_name` spelling of a coverpoint bin,
/// and a cross bin's bare cross-set expression.
Expr(Expr),
}
/// `binsof ( name ) [ intersect { ranges } ]` — one `select_condition`.
#[derive(Debug)]
pub struct BinsofSel {
/// Comments written between `binsof` and the `(`.
pub after_kw: Vec<Comment>,
/// Comments written just inside the `(`.
pub after_open: Vec<Comment>,
/// Comments written just before the `)`.
pub before_close: Vec<Comment>,
pub name: Expr,
/// Comments written between the `)` and `intersect`.
pub before_intersect: Vec<Comment>,
/// Comments written between `intersect` and its `{`.
pub after_intersect: Vec<Comment>,
pub intersect: Option<Vec<ExprItem>>,
}
+416
View File
@@ -0,0 +1,416 @@
//! Data types, dimensions and the declarations that carry them: variables and
//! nets, parameters, typedefs, enums and structs, and function/task/let
//! declarations with their port lists.
use super::*;
/// A data type: keyword or user-defined name, plus signing and packed dims.
/// `name` may be empty for implicit types (`input [7:0] x`).
#[derive(Debug, Clone, Default)]
pub struct DataType {
/// The `virtual` / `virtual interface` prefix of a virtual interface type
/// reference, as written (IEEE 1800 §25.9): `virtual clk_rst_if`,
/// `virtual interface bus_if`. Legal in every type position — a typedef's
/// base type, a task/function argument, a variable declaration.
///
/// A *declaration* keeps it in [`DataDecl::qualifiers`] instead, where the
/// rest of the member qualifiers already live; this field carries the
/// positions that have no qualifier list of their own.
///
/// A one-byte enum rather than the text, for the same reason `extra` is
/// boxed: every `Expr` carries a `DataType` through [`ExprKind::Type`],
/// so a rare field must not widen the common case.
pub virt: Option<VirtualKw>,
pub name: String,
/// The rare tail of a type: parameterization or an anonymous aggregate
/// body. See [`TypeExtra`]; read it through [`DataType::params`] /
/// [`DataType::inline`].
///
/// Boxed — and the two spellings share the one box — to keep `DataType`,
/// and through [`ExprKind::Type`] every `Expr`, small.
pub extra: Option<Box<TypeExtra>>,
pub signing: Option<String>,
pub packed: Vec<Dim>,
}
impl DataType {
pub fn is_implicit(&self) -> bool {
self.virt.is_none()
&& self.name.is_empty()
&& self.extra.is_none()
&& self.signing.is_none()
&& self.packed.is_empty()
}
/// The `#( ... )` of a parameterized type reference, if one was written.
pub fn params(&self) -> Option<&RawText> {
match self.extra.as_deref() {
Some(TypeExtra::Params(p)) => Some(p),
_ => None,
}
}
/// The anonymous aggregate that *is* this type, if one was written.
pub fn inline(&self) -> Option<&TypeExtra> {
match self.extra.as_deref() {
Some(e @ (TypeExtra::Enum(_) | TypeExtra::Struct(_))) => Some(e),
_ => None,
}
}
}
/// What a type carries beyond its name, signing and packed dimensions. A type
/// never has two of these at once — an anonymous aggregate has no name to
/// parameterize — so they share one box on [`DataType`].
#[derive(Debug, Clone)]
pub enum TypeExtra {
/// The `#( ... )` of a parameterized type reference, verbatim:
/// `uvm_analysis_port #(bit [31:0]) port;`. Its arguments are types as
/// often as expressions (`#(virtual bus_if)`, `#(item #(A, B))`), so lucisv
/// reproduces them as written instead of modelling a second grammar.
Params(RawText),
/// An anonymous enum standing where a type name would:
/// `enum logic [1:0] {IDLE, STOP} state;`.
Enum(EnumType),
/// An anonymous struct or union standing where a type name would:
/// `struct packed { ... } s;`.
Struct(StructType),
}
/// How a virtual interface type reference is spelled. The `interface` keyword
/// is optional (IEEE 1800 §25.9) and both spellings occur, so which one was
/// written is recorded and printed back.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VirtualKw {
/// `virtual bus_if h;`
Bare,
/// `virtual interface bus_if h;`
Interface,
}
impl VirtualKw {
/// The prefix as it is written, `interface` keyword included.
pub fn text(self) -> &'static str {
match self {
VirtualKw::Bare => "virtual",
VirtualKw::Interface => "virtual interface",
}
}
}
/// A dimension: `[expr]`, `[a:b]`, `[]`, or `[*]`.
#[derive(Debug, Clone)]
pub struct Dim {
pub kind: DimKind,
/// Comments written in the dimension's own slots — before the `[`, just
/// inside it, around the `:` and before the `]`. Boxed for the reason
/// [`SegmentComments`] gives.
pub comments: Box<SegmentComments>,
/// Code extent including the brackets.
pub span: TextRange,
}
/// What stands between a dimension's brackets.
#[derive(Debug, Clone)]
pub enum DimKind {
/// `[expr]` or `[a:b]` — also `[$]`, `[$:N]` (a bare `$` is an ordinary
/// expression) and `[string]` / `[key_t]` (a type or name used as an
/// associative-array key parses as an expression).
Range { a: Expr, b: Option<Expr> },
/// `[]` — a dynamic array.
Dynamic,
/// `[*]` — a wildcard-keyed associative array.
Wildcard,
}
#[derive(Debug)]
pub struct Typedef {
/// Comments written between the `typedef` keyword and the base type
/// (`typedef /*c*/ struct packed { … } w_t;`).
pub after_kw: Vec<Comment>,
/// Comments written between the base type and the new type's name
/// (`… } /*c*/ w_t;`).
pub before_name: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
pub unpacked: Vec<Dim>,
/// Comments written between the name and the `;`.
pub before_semi: Vec<Comment>,
pub kind: TypedefKind,
}
#[derive(Debug)]
pub enum TypedefKind {
Alias(DataType),
Enum(EnumType),
Struct(StructType),
/// A forward declaration: `typedef class my_class;`
ForwardClass,
}
#[derive(Debug, Clone)]
pub struct EnumType {
/// Comments written between the `enum` keyword and its base type
/// (`enum /*c*/ logic [1:0] { … }`).
pub after_kw: Vec<Comment>,
pub base: Option<DataType>,
/// Comments written between the base type and the `{`.
pub before_open: Vec<Comment>,
pub members: Vec<EnumMember>,
/// Directives written between the members, in source order.
pub directives: Vec<ListDirective>,
pub dangling: Vec<Comment>,
}
#[derive(Debug, Clone)]
pub struct EnumMember {
pub meta: Meta,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// The enum name range of IEEE 1800 §6.19 — `Name[N]` or `Name[hi:lo]`,
/// which declares a run of sequentially-valued members. One dimension is
/// all the LRM allows; it is kept as an ordinary [`Dim`] so the existing
/// dimension parser and printer serve it, and it is printed back tight
/// against the name because it is part of the name, not a layout choice.
pub range: Vec<Dim>,
/// Comments written on either side of the `=` of a member's value
/// (`B /*c*/ = /*c*/ 2`).
pub eq_comments: Box<BinaryComments>,
pub value: Option<Expr>,
/// True when a `,` followed this element in the source; see
/// [`NonAnsiPort::comma`].
pub comma: bool,
/// Code extent of the member.
pub span: TextRange,
}
#[derive(Debug, Clone)]
pub struct StructType {
/// "struct" or "union"
pub kw: String,
/// Comments written between each word of the `struct packed signed`
/// header run and the next, and between the last of them and the `{`.
/// One entry per gap, in source order: after the keyword, after
/// `tagged`, after `packed`, after the signing word.
pub header_comments: Box<StructHeaderComments>,
/// The `tagged` of `union tagged { ... }` (IEEE 1800 §7.3.2) — a
/// discriminated union. Carried and printed; lucisv models no tag
/// semantics, and the `tagged Valid 5` expression form that goes with it
/// is a pattern grammar the parser still rejects.
pub tagged: bool,
pub packed: bool,
pub signing: Option<String>,
pub members: Vec<StructMember>,
pub dangling: Vec<Comment>,
}
#[derive(Debug, Clone)]
pub struct StructMember {
pub meta: Meta,
/// `rand` / `randc` written before the member's type. The LRM allows the
/// randomization qualifiers only on a class property, but vendor tools
/// accept them on a plain struct member and real code uses them
/// (`spi_host/dv/env/spi_host_env_pkg.sv:64`); lucisv models no
/// randomization semantics, so the words are simply carried and printed.
pub qualifiers: Vec<Qualifier>,
pub ty: DataType,
pub declarators: Vec<Declarator>,
/// Code extent of the member, its `;` included.
pub span: TextRange,
}
#[derive(Debug)]
pub struct ParamDecl {
/// `parameter` or `localparam`
pub kw: String,
/// Comments written between that keyword and the type
/// (`localparam /*c*/ int N = 4;`).
pub after_kw: Vec<Comment>,
/// A type parameter: `localparam type payload_t = logic [7:0];`. The
/// declarator's `init` is then an [`ExprKind::Type`], not a value.
pub is_type: bool,
pub ty: DataType,
pub declarators: Vec<Declarator>,
}
#[derive(Debug)]
pub struct DataDecl {
/// Net type (`wire`, `tri`, ...) if any.
pub net: Option<String>,
/// Net delay: the `5` in `wire #5 w;`
pub delay: Option<Expr>,
/// Qualifiers written before the type, in source order: `var`,
/// `automatic`, `static`, `const`, and — inside a class body — `rand`,
/// `randc`, `local`, `protected`, and the `virtual [interface]` of a
/// virtual-interface property.
pub qualifiers: Vec<Qualifier>,
pub ty: DataType,
pub declarators: Vec<Declarator>,
}
#[derive(Debug)]
pub struct PortDecl {
pub dir: String,
pub net: Option<String>,
pub ty: DataType,
pub declarators: Vec<Declarator>,
}
#[derive(Debug, Clone)]
pub struct Declarator {
pub meta: Meta,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
pub unpacked: Vec<Dim>,
/// Comments written on either side of the `=` of an initialiser.
pub eq_comments: Box<BinaryComments>,
/// `=` for variables; net declarations also use this for the initial
/// continuous assignment.
pub init: Option<Expr>,
/// Code extent of the declarator.
pub span: TextRange,
}
#[derive(Debug)]
pub struct FunctionDecl {
/// `Some` when this is a DPI import — `import "DPI-C" function ...;` —
/// which is a prototype with a linkage prefix.
pub dpi: Option<DpiImport>,
/// Class-member qualifiers written *before* the `function` keyword, in
/// source order: `virtual`, `local`, `protected`, `static`, `pure`,
/// `extern`. Empty outside a class body.
pub prefix: Vec<Qualifier>,
/// Comments written between the `function` keyword and whatever follows
/// it (`function /*c*/ void f()`).
pub after_kw: Vec<Comment>,
pub qualifiers: Vec<Qualifier>,
/// True for a body-less prototype — `extern function ...;`,
/// `pure virtual function ...;` or a DPI import — which has no
/// `endfunction`.
pub is_prototype: bool,
/// The `my_class::` written before the name when an `extern` method is
/// *defined* outside its class body. Kept apart from `name` so
/// `src[name_span] == name` still holds for the method's own name.
pub scope: Vec<ScopeSeg>,
pub ret: Option<DataType>,
/// Comments written between the return type (or the keyword run) and the
/// method's name (`function void /*c*/ f()`).
pub before_name: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// False for old-style `function f;` declarations without a port list.
pub has_parens: bool,
/// Comments written between the name and the `(` of the port list.
pub before_args: Vec<Comment>,
pub args: Vec<TfArg>,
/// Comments written inside an argument list with no argument to carry
/// them (`function void f( /*c*/ );`).
pub args_dangling: Vec<Comment>,
/// Comments written between the header's last token and its `;`.
pub before_semi: Vec<Comment>,
pub stmts: Vec<Stmt>,
pub dangling: Vec<Comment>,
/// Comments written in the two gaps of `endfunction : f`.
pub end_label_comments: Box<LabelComments>,
/// Label after `endfunction :`.
pub end_label: Option<String>,
/// Byte range of `end_label`.
pub end_label_span: Option<TextRange>,
/// True when a `;` was written after the footer (`endfunction : f;`) — a
/// null class item (IEEE 1800 A.1.9), reproduced where it was written so
/// the token stream is unchanged.
pub end_semi: bool,
}
#[derive(Debug)]
pub struct TaskDecl {
/// `Some` when this is a DPI import; see [`FunctionDecl::dpi`].
pub dpi: Option<DpiImport>,
/// Class-member qualifiers written *before* the `task` keyword; see
/// [`FunctionDecl::prefix`].
pub prefix: Vec<Qualifier>,
/// Comments written between the `task` keyword and what follows it.
pub after_kw: Vec<Comment>,
pub qualifiers: Vec<Qualifier>,
/// True for a body-less prototype; see [`FunctionDecl::is_prototype`].
pub is_prototype: bool,
/// Out-of-body definition scope; see [`FunctionDecl::scope`].
pub scope: Vec<ScopeSeg>,
/// Comments written between the keyword run and the task's name.
pub before_name: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// False for old-style `task t;` declarations without a port list.
pub has_parens: bool,
/// Comments written between the name and the `(` of the port list.
pub before_args: Vec<Comment>,
pub args: Vec<TfArg>,
/// Comments written inside an empty argument list; see
/// [`FunctionDecl::args_dangling`].
pub args_dangling: Vec<Comment>,
/// Comments written between the header's last token and its `;`.
pub before_semi: Vec<Comment>,
pub stmts: Vec<Stmt>,
pub dangling: Vec<Comment>,
/// Comments written in the two gaps of `endtask : t`.
pub end_label_comments: Box<LabelComments>,
/// Label after `endtask :`.
pub end_label: Option<String>,
/// Byte range of `end_label`.
pub end_label_span: Option<TextRange>,
/// True when a `;` was written after the footer; see
/// [`FunctionDecl::end_semi`].
pub end_semi: bool,
}
/// A `let` declaration: `let max(a, b) = (a > b) ? a : b;` (IEEE 1800 §11.12).
///
/// A `let` port is the same `[type] name [= default]` a task/function port is
/// minus the direction keyword, so the ports reuse [`TfArg`] rather than
/// growing a near-identical node of their own.
#[derive(Debug)]
pub struct LetDecl {
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// False for the port-less spelling `let x = expr;` — an empty `()` was
/// written when this is true and [`LetDecl::ports`] is empty.
pub has_parens: bool,
pub ports: Vec<TfArg>,
pub value: Expr,
}
#[derive(Debug)]
pub struct TfArg {
pub meta: Meta,
pub dir: Option<String>,
/// Comments written between the direction keyword and the type
/// (`input /*c*/ logic`). Empty when no direction was written.
pub after_dir: Vec<Comment>,
pub ty: DataType,
/// Comments written between the type and the argument's name
/// (`bit [3:0] /*c*/ a`).
pub before_name: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
pub unpacked: Vec<Dim>,
/// Comments written on either side of the `=` of a default value.
pub eq_comments: Box<BinaryComments>,
pub default: Option<Expr>,
/// Code extent of the argument declaration.
pub span: TextRange,
}
/// A task/function port list: its arguments, plus the comments written inside
/// a pair of parentheses that hold no argument to carry them (`f( /*c*/ )`).
#[derive(Debug, Default)]
pub struct TfPorts {
pub args: Vec<TfArg>,
pub dangling: Vec<Comment>,
}
+444
View File
@@ -0,0 +1,444 @@
//! Expressions: the [`Expr`] node, every [`ExprKind`], and the boxed
//! comment-slot structs an expression's brackets and operators keep.
use super::*;
/// An expression: its code extent plus what it is.
///
/// The span sits on this wrapper rather than on each [`ExprKind`] variant so
/// that "the span of any expression" is one field access no matter which
/// variant it is — the same shape [`Item`] and [`Stmt`] already have.
#[derive(Debug, Clone)]
pub struct Expr {
pub kind: ExprKind,
/// Code extent of the expression.
pub span: TextRange,
}
#[derive(Debug, Clone)]
pub enum ExprKind {
Ident(String),
Number(String),
Str(String),
/// Explicitly empty (used for `.port()` connections), carrying any
/// comments written between the parens so they stay inside them.
Empty(Vec<Comment>),
Unary {
op: String,
/// Comments written between the operator and its operand
/// (`~ /*c*/ a`), kept so neither drifts across the other. Boxed for
/// the reason [`ArgComments`] gives.
comments: Box<Vec<Comment>>,
expr: Box<Expr>,
},
Binary {
lhs: Box<Expr>,
op: String,
rhs: Box<Expr>,
/// Boxed to keep `Expr` small, as for `TernaryComments`.
comments: Box<BinaryComments>,
},
Ternary {
cond: Box<Expr>,
then: Box<Expr>,
els: Box<Expr>,
/// Boxed to keep `Expr` small: a ternary with comments in it is rare,
/// but every `Expr` would otherwise carry four empty vectors.
comments: Box<TernaryComments>,
},
Call {
callee: Box<Expr>,
args: Vec<ExprItem>,
/// Boxed to keep `Expr` small, as for `TernaryComments`: a call with
/// comments written around its brackets is rare, and there is one
/// `Call` in every other line of real code.
comments: Box<CallComments>,
},
/// A shallow copy, IEEE 1800 §8.12: `new instr_template[name]` (corpus
/// `ibex/vendor/google_riscv-dv/src/isa/riscv_instr.sv:238`). The payload
/// is the source handle — a postfix expression, never a call, because
/// `new(...)` and `new[N]` are the constructor and the dynamic-array
/// resize, which stay an ordinary `Call`/`Index` on the name `new`.
New(Box<Expr>),
Index {
base: Box<Expr>,
index: Box<Expr>,
/// `q /*a*/ [ /*b*/ i /*c*/ ]`.
comments: Box<SegmentComments>,
},
Range {
base: Box<Expr>,
op: String,
msb: Box<Expr>,
lsb: Box<Expr>,
/// Every slot of `q /*a*/ [ /*b*/ m /*c*/ : /*d*/ l /*e*/ ]`.
comments: Box<SegmentComments>,
},
Member {
base: Box<Expr>,
name: String,
/// `a /*a*/ . /*b*/ b`.
comments: Box<SegmentComments>,
},
Scope {
base: Box<Expr>,
name: String,
/// `pkg /*a*/ :: /*b*/ item`.
comments: Box<SegmentComments>,
},
/// A parameterized class reference: the `uvm_config_db#(virtual bus_if)`
/// of `uvm_config_db#(virtual bus_if)::get(...)`. The `#( ... )` is
/// verbatim, for the reason [`DataType::params`] gives.
Parameterized {
base: Box<Expr>,
params: RawText,
},
Concat(Vec<ExprItem>),
Repl {
count: Box<Expr>,
/// Elements carry their comments the way a concatenation's do, so a
/// comment inside a replication stays inside it.
inner: Vec<ExprItem>,
},
/// A streaming concatenation, IEEE 1800 §11.4.14:
/// `{<<8{v}}`, `{>>{a, b}}`, `{<< byte {x}}`. Legal as an lvalue too,
/// which is why it is an ordinary primary expression.
Stream {
/// `<<` or `>>`.
dir: String,
/// The optional slice size: a constant expression or a type.
slice: Option<Box<Expr>>,
/// The stream expressions, carrying their comments the way a
/// concatenation's elements do.
inner: Vec<ExprItem>,
},
Paren {
inner: Box<Expr>,
/// Comments written just inside the `(`.
before: Vec<Comment>,
/// Comments left over just before the `)`.
after: Vec<Comment>,
},
/// `ty'(expr)` cast. The casting type is an expression because it may be
/// a name (`int`, `my_t`), a package-scoped name
/// (`lc_ctrl_pkg::TxWidth'(x)`), a size (`4'(x)`), a parenthesized
/// constant expression (`(DepthW + 3)'(1'b1)`) or a system function call
/// (`$bits(x)'(y)`) — IEEE 1800 §6.24.1.
Cast {
ty: Box<Expr>,
/// Comments written in the cast's own four slots.
comments: Box<CastComments>,
expr: Box<Expr>,
/// True for the `ty'{...}` spelling (IEEE 1800 §10.9.1), where the
/// argument is an assignment pattern. The pattern brings its own
/// `'{` and `}`, so such a cast prints no brackets of its own —
/// which is also why the two spellings must stay distinguishable:
/// `ty'('{a: 1})` is a different token stream from `ty'{a: 1}`.
pattern: bool,
},
/// `'{...}` assignment pattern.
AssignPattern(Vec<PatternItem>),
/// The replication form of an assignment pattern, IEEE 1800 §10.9.1:
/// `'{NumRegs{0}}`. Distinct from [`ExprKind::Repl`], which is the
/// concatenation form `{N{x}}`.
AssignPatternRepl {
count: Box<Expr>,
inner: Vec<ExprItem>,
},
Postfix {
expr: Box<Expr>,
op: String,
/// Comments written between the operand and the operator
/// (`i /*c*/ ++`). Boxed for the reason [`ArgComments`] gives.
comments: Box<Vec<Comment>>,
},
Inside {
lhs: Box<Expr>,
ranges: Vec<ExprItem>,
/// Comments written on either side of the `inside` word, kept per
/// side the way every other binary operator's are.
comments: Box<BinaryComments>,
},
/// `x inside `MACRO` — the set is a macro invocation that expands to a
/// `{...}` set, so it is kept verbatim (corpus
/// `opentitan/hw/ip/uart/dv/env/uart_scoreboard.sv:155`).
InsideMacro {
lhs: Box<Expr>,
/// The macro invocation token, exactly as written.
set: String,
/// Comments written on either side of the `inside` word, as
/// [`ExprKind::Inside`] keeps them.
comments: Box<BinaryComments>,
},
/// `expr with (expr)` — the iterator argument of an array method
/// (IEEE 1800 §7.12): `fld.sum() with (item.bit_width)`. The argument is
/// an ordinary parenthesized expression, so `base` and `arg` are both
/// laid out structurally.
With {
base: Box<Expr>,
arg: Box<Expr>,
/// Boxed to keep `Expr` small, as for `TernaryComments`.
comments: Box<WithComments>,
},
/// `expr with { ... }` — the inline constraint block of a `randomize`
/// call (IEEE 1800 §18.7). The block is a `constraint` body written in an
/// expression, so it is the very same [`ConstraintSet`] a
/// [`ItemKind::Constraint`] carries — or, when the grammar does not
/// recognise it, the byte-for-byte capture every `with` block was before
/// this round.
WithConstraint {
base: Box<Expr>,
block: Box<ConstraintBody>,
/// Boxed to keep `Expr` small, as for `TernaryComments`.
comments: Box<WithComments>,
},
/// `expr dist { 0 := 5, [1:20] :/ 20 }` — a distribution constraint
/// (IEEE 1800 §18.5.4). Only the constraint-item parser ever builds one:
/// `dist` is not a lexer keyword (see `token.rs`), so it is read by text
/// where the grammar leaves no other reading, and nowhere else.
Dist {
expr: Box<Expr>,
/// Comments written on either side of the `dist` word, kept per side
/// the way a binary operator's are.
comments: Box<BinaryComments>,
weights: Vec<DistItem>,
},
/// A named call argument: the `.ptr(ral.ovrd)` of
/// `csr_wr(.ptr(ral.ovrd), .value(x))`. `value` is [`ExprKind::Empty`]
/// for `.name()`, exactly as an empty connection is.
NamedArg {
name: String,
/// Byte range of `name`.
name_span: TextRange,
value: Box<Expr>,
/// The four slots `.name( value )` owns. Boxed to keep `Expr` small:
/// every expression pays for the largest variant, and the tree is
/// walked recursively.
comments: Box<ArgComments>,
},
/// `[a:b]` inside an `inside` range list or value range.
ValueRange {
lo: Box<Expr>,
hi: Box<Expr>,
/// `[ /*a*/ lo /*b*/ : /*c*/ hi /*d*/ ]` — the same four inner slots
/// an [`ExprKind::Range`] has, read by the same shared parse.
comments: Box<SegmentComments>,
},
/// A balanced region of a connection's value that holds a
/// **conditional-compilation directive**, kept byte for byte:
/// `` .dio_pad_io({ IOR9, `ifdef ANALOGSIM '0, `else CC2, `endif POR_N }) ``.
///
/// lucisv never evaluates a `` `ifdef `` condition, so such a region has
/// no single value to model. Capturing just the value keeps everything
/// around it structural — the instantiation's edge, its code lens, its
/// hierarchy site and its other connections' references — where before
/// the whole *item* became [`ItemKind::Verbatim`]. The region itself
/// records nothing and is re-emitted exactly as written.
Verbatim(RawText),
/// A type used in expression position (`parameter type T = logic [7:0]`).
Type(DataType),
/// `(min : typ : max)` delay expression.
MinTypMax {
min: Box<Expr>,
typ: Box<Expr>,
max: Box<Expr>,
},
}
/// Comments written in the fixed slots of a **postfix segment** or a
/// **bracketed range** — the one shape the grammar writes in five places:
///
/// ```text
/// base /*before_open*/ [ /*after_open*/ msb /*before_op*/ : /*after_op*/ lsb /*before_close*/ ]
/// base /*before_open*/ . /*after_open*/ name
/// base /*before_open*/ :: /*after_open*/ name
/// ```
///
/// A member or scope segment uses the first two slots, an index the first
/// two and the last, a range all five. Kept per slot for the reason
/// [`TernaryComments`] gives: printed anywhere else, a comment crosses a
/// token and the safety net refuses the file.
///
/// Boxed by every holder, as [`CallComments`] is: a segment with a comment in
/// it is rare and there is a `.`, a `::` or a `[` in every other line of real
/// code.
#[derive(Debug, Clone, Default)]
pub struct SegmentComments {
/// Between the base and the `.`, `::` or `[` that opens the segment.
pub before_open: Vec<Comment>,
/// Just after that token.
pub after_open: Vec<Comment>,
/// Between the first operand and the `:` / `+:` / `-:` of a range.
pub before_op: Vec<Comment>,
/// Just after that operator.
pub after_op: Vec<Comment>,
/// Just before the closing `]`.
pub before_close: Vec<Comment>,
}
impl SegmentComments {
/// True when nothing was written in any slot — the common case, laid out
/// without any comment handling at all.
pub fn is_empty(&self) -> bool {
self.before_open.is_empty()
&& self.after_open.is_empty()
&& self.before_op.is_empty()
&& self.after_op.is_empty()
&& self.before_close.is_empty()
}
/// True when nothing was written before the opening token. The opener's
/// slot is the one a caller can print for itself, so a printer that has
/// already emitted the base asks this before spacing.
pub fn opens_clean(&self) -> bool {
self.before_open.is_empty()
}
}
/// Comments written in the fixed slots of a `ty'(expr)` cast — the one
/// expression whose punctuation is three tokens with nothing between them to
/// carry a comment.
///
/// The `ty'{...}` spelling writes no `(` `)` of its own, so only the first
/// two slots can be non-empty there.
#[derive(Debug, Clone, Default)]
pub struct CastComments {
/// Between the casting type and the `'`.
pub before_tick: Vec<Comment>,
/// Between the `'` and the `(` (or the `{` of a pattern).
pub after_tick: Vec<Comment>,
/// Just inside the `(`.
pub after_open: Vec<Comment>,
/// Just before the `)`.
pub before_close: Vec<Comment>,
}
impl CastComments {
/// True when nothing was written in any slot — the common case.
pub fn is_empty(&self) -> bool {
self.before_tick.is_empty()
&& self.after_tick.is_empty()
&& self.after_open.is_empty()
&& self.before_close.is_empty()
}
}
/// Comments written in the gaps of a `struct|union [tagged] [packed]
/// [signing] {` header — four keyword positions with nothing between them to
/// carry a comment.
#[derive(Debug, Clone, Default)]
pub struct StructHeaderComments {
/// After `struct` / `union`.
pub after_kw: Vec<Comment>,
/// After `tagged`, if written.
pub after_tagged: Vec<Comment>,
/// After `packed`, if written.
pub after_packed: Vec<Comment>,
/// After the signing word, if written.
pub after_signing: Vec<Comment>,
}
/// Comments written in the fixed slots of a `.name( value )` — a named call
/// argument or a port connection, which are the same four gaps.
#[derive(Debug, Clone, Default)]
pub struct ArgComments {
/// Between the `.` and the name.
pub after_dot: Vec<Comment>,
/// Between the name and the `(`.
pub before_open: Vec<Comment>,
/// Just inside the `(`.
pub after_open: Vec<Comment>,
/// Between the value and the closing `)` (`.src(5'd0 /* x0 */)`),
/// printed back inside the parens.
pub close: Vec<Comment>,
}
/// Comments written next to a binary operator. Kept per side so neither
/// drifts across the operator: `a && // why` and `a // why` + `&& b` are
/// different token streams.
#[derive(Debug, Clone, Default)]
pub struct BinaryComments {
/// Between the left operand and the operator. These force the chain to
/// break, with the operator starting the new line.
pub before: Vec<Comment>,
/// Between the operator and the right operand. These force the chain to
/// break, with the right operand starting the new line.
pub after: Vec<Comment>,
}
/// Comments written inside a `cond ? then : els`, kept per position so the
/// formatter prints each back between the same two tokens it was written
/// between. Anywhere else they would drift across `?` or `:`.
#[derive(Debug, Clone, Default)]
pub struct TernaryComments {
/// Between the condition and `?`.
pub before_question: Vec<Comment>,
/// Between `?` and the then-branch.
pub after_question: Vec<Comment>,
/// Between the then-branch and `:`.
pub before_colon: Vec<Comment>,
/// Between `:` and the else-branch.
pub after_colon: Vec<Comment>,
}
/// Comments written where a call's argument list has no element to carry
/// them: before the `(`, and inside an empty `()`. Both are kept so the
/// formatter can print them back between the same two tokens — dropped or
/// moved, the safety net rejects the output.
#[derive(Debug, Clone, Default)]
pub struct CallComments {
/// Between the callee and the `(` (`x.randomize /*c*/ ()`).
pub before_open: Vec<Comment>,
/// Inside an empty argument list (`x.randomize(/*c*/)`). A list with
/// elements carries its own comments on them, so this is empty there.
pub dangling: Vec<Comment>,
}
impl CallComments {
/// True when nothing was written around the brackets — the common case.
pub fn is_empty(&self) -> bool {
self.before_open.is_empty() && self.dangling.is_empty()
}
}
/// Comments written around the `with` of a postfix `with (expr)` or
/// `with { ... }`, kept per position for the reason [`TernaryComments`] gives.
#[derive(Debug, Clone, Default)]
pub struct WithComments {
/// Between the base expression and `with`.
pub before_kw: Vec<Comment>,
/// Between `with` and the `(` or `{` that follows it.
pub after_kw: Vec<Comment>,
}
impl TernaryComments {
/// True when nothing was written inside the `? :` — the common case, laid
/// out without any comment handling.
pub fn is_empty(&self) -> bool {
self.before_question.is_empty()
&& self.after_question.is_empty()
&& self.before_colon.is_empty()
&& self.after_colon.is_empty()
}
}
#[derive(Debug, Clone)]
pub struct PatternItem {
pub meta: Meta,
/// `key: value` (key may be `default`, a type, or an expression).
pub key: Option<Expr>,
pub value: Expr,
/// Code extent of the pattern element.
pub span: TextRange,
}
/// One element of a bracketed expression list (a concatenation, a call
/// argument list, an `inside` set), with the comments written around it. A
/// comment on an element is what forces its list to break one per line.
#[derive(Debug, Clone)]
pub struct ExprItem {
pub meta: Meta,
pub expr: Expr,
/// Code extent of the element.
pub span: TextRange,
}
+485
View File
@@ -0,0 +1,485 @@
//! AST for the supported Verilog/SystemVerilog subset.
//!
//! Nodes that begin a line carry a [`Meta`] with leading comments, an
//! optional trailing comment, and a blank-line-before flag so the formatter
//! can reproduce vertical structure the way ruff's formatter does.
//!
//! Spans: a node's `span` is its **code extent** — from the first to the last
//! token of the construct itself. Attached comments are *not* part of it and
//! carry their own spans on [`Comment`]; attribute instances `(* ... *)` are
//! real tokens and *are* inside it. See `docs/features/spans/README.md` for
//! which node types carry a span and why the rest do not.
//!
//! Names: a node that declares a name keeps the name as a `String` and the
//! byte range of the identifier that spells it in a sibling field —
//! `name_span` for the declared name, `label_span` / `end_label_span` /
//! `module_span` for the other names a node can carry — so
//! `src[name_span] == name`. Where a node holds a *list* of names the two are
//! bundled into a [`Name`] instead, because parallel `Vec`s cannot be kept in
//! step by construction. See `docs/features/name-spans/README.md`.
//!
//! Layout: this file holds the file and item spine — [`SourceFile`],
//! [`Item`], [`ItemKind`] and the small items' payloads — and the leaf types
//! every node shares ([`Meta`], [`Name`], [`RawText`], [`Qualifier`]). The
//! node types are grouped by grammar domain in sibling files and re-exported
//! here, so every type is `vlog_parser::ast::Name` regardless of which file
//! defines it:
//!
//! | file | holds |
//! |---|---|
//! | `module` | module/interface/program, ports, instantiations, `assign`, gates, `bind`, generate, modports, clocking |
//! | `decl` | data types, dimensions, declarations, `typedef`/`enum`/`struct`, function/task/`let` |
//! | `stmt` | [`Stmt`], [`StmtKind`], timing controls, sensitivity lists |
//! | `expr` | [`Expr`], [`ExprKind`], the expression comment slots |
//! | `class`, `covergroup` | classes and constraints; covergroups |
//! | `sva` | assertions, `property`/`sequence`, the property-expression tree |
use crate::span::TextRange;
use crate::token::Comment;
mod class;
mod covergroup;
mod decl;
mod expr;
mod module;
mod stmt;
mod sva;
pub use class::*;
pub use covergroup::*;
pub use decl::*;
pub use expr::*;
pub use module::*;
pub use stmt::*;
pub use sva::*;
/// A name as written, together with the byte range it occupies:
/// `src[span] == text`.
///
/// Used where a node holds a *list* of names; a node with a single name keeps
/// it as a `String` plus a sibling `name_span`.
#[derive(Debug, Clone)]
pub struct Name {
pub text: String,
pub span: TextRange,
}
/// One `pkg::` / `cls::` segment written in front of an out-of-body
/// definition's name, with the comments written in its two gaps.
///
/// The chain is kept as segments rather than joined into a `String` so that
/// (a) a comment written beside a `::` has a slot, and (b) an escaped
/// segment's terminating space survives — `\my-pkg ::\state-t` is three
/// tokens and `\my-pkg::\state-t` is one (`docs/topo.md` §2.9-21).
#[derive(Debug, Clone)]
pub struct ScopeSeg {
pub name: Name,
/// Comments written between this segment and the `::` after it.
pub before_sep: Vec<Comment>,
/// Comments written between that `::` and whatever follows it.
pub after_sep: Vec<Comment>,
}
/// The `a::b::` prefix a [`ScopeSeg`] chain spells, joined for the consumers
/// that want one string (the binder's out-of-body home, hover text).
///
/// An escaped segment keeps the whitespace that terminates it, for the reason
/// [`ScopeSeg`] gives; nothing else adds any.
pub fn scope_path(segs: &[ScopeSeg]) -> String {
let mut out = String::new();
for seg in segs {
out.push_str(&seg.name.text);
if seg.name.text.rsplit(char::is_whitespace).next().is_some_and(|s| s.contains('\\')) {
out.push(' ');
}
out.push_str("::");
}
out.pop();
out.pop();
out
}
/// Comments written in the two gaps of a `keyword : name` label — the `end`,
/// `endfunction`, `endgroup`, `begin` … footers and headers that carry one.
#[derive(Debug, Clone, Default)]
pub struct LabelComments {
/// Between the keyword and the `:`.
pub before_colon: Vec<Comment>,
/// Between the `:` and the name.
pub after_colon: Vec<Comment>,
}
impl LabelComments {
/// True when nothing was written in either gap — the common case.
pub fn is_empty(&self) -> bool {
self.before_colon.is_empty() && self.after_colon.is_empty()
}
}
/// One keyword of a qualifier run, with the comments written between it and
/// whatever follows it (`local /*c*/ static /*c*/ function`).
///
/// Kept per keyword rather than as one bucket for the run, because two
/// comments in different gaps of the same run are two different token
/// streams and the safety net compares them.
#[derive(Debug, Clone)]
pub struct Qualifier {
pub text: String,
/// Comments written after this keyword and before the next one — or
/// before whatever ends the run.
pub after: Vec<Comment>,
}
impl Qualifier {
/// A qualifier with nothing written after it, for the sites that build a
/// run rather than reading one from source.
pub fn plain(text: impl Into<String>) -> Self {
Qualifier { text: text.into(), after: Vec::new() }
}
}
#[derive(Debug, Clone, Default)]
pub struct Meta {
pub leading: Vec<Comment>,
/// The comment written *after* the node and the separator that closes it
/// (`,` or `;`), on the same line. Several are merged into one, joined by
/// a space; the merged value keeps the first one's position and spans
/// from the first byte of the first to the last byte of the last.
pub trailing: Option<Comment>,
/// Comments written *between* the node and the separator that follows it
/// (`element /* c */,`). They print on the node's side of the separator,
/// which is where the source put them — printing them after it moves a
/// comment across a token and the safety net rejects the output. Empty
/// for a node no separator follows.
pub before_sep: Vec<Comment>,
pub blank_before: bool,
/// Attribute instances `(* ... *)` that preceded the node, verbatim.
pub attrs: Vec<RawText>,
}
/// Source text passed through verbatim: a compiler directive or an attribute
/// instance. `col` is the 1-based column it started in, which is what lets the
/// formatter re-indent continuation lines of a multi-line one without drifting
/// further right on every pass.
#[derive(Debug, Clone)]
pub struct RawText {
pub text: String,
pub col: u32,
/// Byte extent of the passed-through token.
pub span: TextRange,
}
/// A compiler directive written *between* the elements of a port,
/// parameter-port, enum-member, parameter-override or instance-connection
/// list (`` `ifdef``/`` `else``/`` `elsif``/`` `endif``, `` `define``,
/// `` `undef``, `` `include``) — or a standalone macro invocation standing in
/// the same place, which is passed through the same way.
///
/// It is kept in a vector *beside* the elements rather than folded into one
/// enum with them: the element vectors are read by `vlog_semantic` and
/// `vlog_linter`, and a directive is not a port. `before` is what puts the
/// two back into source order. lucisv does not evaluate the condition — both
/// arms' elements are ordinary elements of the one list, exactly as an
/// `` `ifdef`` at item position already works.
#[derive(Debug, Clone)]
pub struct ListDirective {
/// The directive line, verbatim.
pub raw: RawText,
/// Comments written before the directive (`leading`) and the one written
/// after it on the same line (`trailing`).
pub meta: Meta,
/// Index of the element this directive was written before;
/// `elements.len()` when it stands after the last one. Several directives
/// at the same index keep their source order in the vector.
pub before: usize,
/// True when the `,` separating the surrounding elements was written
/// *after* this directive (`` `ifdef X`` ⏎ `, parameter string P = ""`),
/// which is how a conditional list tail stays legal in both arms.
pub comma: bool,
}
/// A macro invocation standing where a module item or a statement belongs
/// (`` `ASSERT_INIT(...) ``, `` `FFARNC(...) ``). Its arguments are token soup
/// handed to a preprocessor we do not run, so the whole invocation is kept as
/// verbatim source text — same treatment as a compiler directive.
#[derive(Debug)]
pub struct MacroCall {
/// The invocation from the backtick through the closing `)`, verbatim.
pub raw: RawText,
/// True if a `;` followed it in the source. Both spellings occur in real
/// RTL, so the formatter reproduces whichever one was written.
pub semi: bool,
}
#[derive(Debug)]
pub struct SourceFile {
pub items: Vec<Item>,
/// Comments at the very end of the file.
pub dangling: Vec<Comment>,
/// The whole source text: `0..len`.
pub span: TextRange,
/// How many `constraint` bodies — declarations and `randomize() with`
/// blocks alike — did not fit the constraint grammar and were captured
/// verbatim instead. Purely diagnostic: it says how much of the real
/// world round 1 of `constraint-bodies` still passes through opaquely,
/// and nothing in the tree depends on it. See
/// `docs/features/constraint-bodies/README.md`.
pub constraint_fallbacks: u32,
/// How many `covergroup` declarations were parsed into a
/// [`ItemKind::Covergroup`], and how many did not fit the covergroup
/// grammar and were captured verbatim instead. The pair is the census
/// `docs/features/covergroup-bodies/README.md` reports: diagnostic only,
/// and nothing in the tree depends on either.
pub covergroups: u32,
pub covergroup_fallbacks: u32,
/// How many `property`/`sequence` declarations and concurrent assertions
/// were parsed into real nodes, and how many did not fit the SVA grammar
/// and were captured verbatim instead. The pair is the census
/// `docs/features/sva-bodies/README.md` reports: diagnostic only, and
/// nothing in the tree depends on any of the four.
pub prop_seq_decls: u32,
pub prop_seq_fallbacks: u32,
pub assertions: u32,
pub assertion_fallbacks: u32,
/// Set when the file is not an item list at all but a **fragment**: the
/// bare middle of some larger construct's body, written to be
/// `` `include``d at exactly that point. `items` is empty whenever this is
/// `Some`, and vice versa. See `docs/features/fragment-mode/README.md`.
pub fragment: Option<Fragment>,
}
/// A whole file that is a piece of a body rather than a list of items.
///
/// Only the three shapes that do not already parse at file scope are here: a
/// class-body fragment and a module-item fragment are ordinary [`Item`] lists
/// and stay in [`SourceFile::items`], because the file-scope item loop is the
/// same loop a class and a module body run.
#[derive(Debug)]
pub enum Fragment {
/// The middle of a procedural block: `if (x) y <= 1;`, `foo();`.
Statements(Vec<Stmt>),
/// The middle of an `enum { ... }` member list: `CUSTOM_1,`.
EnumMembers {
members: Vec<EnumMember>,
/// `` `ifdef``-style directives written between members, exactly as
/// [`EnumType::directives`] records them.
directives: Vec<ListDirective>,
},
/// The middle of a `covergroup ... endgroup` body: `cp_a: coverpoint a;`.
CoverItems(Vec<CoverItem>),
}
#[derive(Debug)]
pub struct Item {
pub meta: Meta,
pub kind: ItemKind,
/// Code extent of the item, its `(* ... *)` attributes included.
pub span: TextRange,
}
#[derive(Debug)]
pub enum ItemKind {
Module(Module),
Package {
kw: String,
/// Comments written between `package` and the name.
before_name: Vec<Comment>,
name: String,
/// Byte range of `name`.
name_span: TextRange,
/// Comments written between the name and the header's `;`.
before_semi: Vec<Comment>,
items: Vec<Item>,
dangling: Vec<Comment>,
/// Comments written in the two gaps of `endpackage : p`.
end_label_comments: Box<LabelComments>,
/// Label after `endpackage :`.
end_label: Option<String>,
/// Byte range of `end_label`.
end_label_span: Option<TextRange>,
},
Directive(RawText),
/// Macro invocation used as a module item.
MacroItem(MacroCall),
/// An elaboration system task standing where a module or generate item
/// belongs: `$error("...");`, `$fatal(1, "...");` (IEEE 1800 §20.11).
/// The payload is the ordinary system-task-call expression — only the
/// position is special.
ElabTask(Expr),
Import(Vec<ImportPath>),
/// `export "DPI-C" function f;` or `export pkg::*;`.
Export(ExportDecl),
Timeunit(String),
Typedef(Typedef),
ParamDecl(ParamDecl),
DataDecl(DataDecl),
/// Non-ANSI port declaration at module scope: `input [7:0] data;`
PortDecl(PortDecl),
ContAssign(ContAssign),
/// The body statement carries any `@(...)`/`#delay` timing control.
Always {
kw: String,
stmt: Stmt,
},
Initial(Stmt),
Final(Stmt),
Instantiation(Instantiation),
GateInstantiation(GateInstantiation),
/// `bind <target> [: <instances>] <instantiation>` (IEEE 1800 §23.11).
Bind(BindDirective),
Genvar(Vec<Name>),
GenerateRegion {
items: Vec<Item>,
dangling: Vec<Comment>,
},
GenIf(GenIf),
/// Boxed: a `for` generate holds a whole `SimpleAssign`, a condition, a
/// step and a block, which together are twice the next-largest item.
GenFor(Box<GenFor>),
GenCase(GenCase),
Function(FunctionDecl),
Task(TaskDecl),
/// `let name(ports) = expr;` (IEEE 1800 §11.12).
Let(LetDecl),
/// A `class` / `virtual class` declaration and its body.
Class(ClassDecl),
/// `modport a (input x, output y), b (...);` (IEEE 1800 §25.5). One
/// declaration may name several modports, so the payload is a list.
Modport(Vec<ModportDecl>),
/// `clocking cb @(posedge clk); ... endclocking` and the `default`
/// spellings of it (IEEE 1800 §14).
Clocking(ClockingDecl),
/// `constraint c { ... }`, its `constraint C::c { ... }` out-of-block
/// form, and the `constraint c;` prototype (IEEE 1800 §18.5).
///
/// A body the constraint grammar does not recognise never reaches this
/// variant: [`Parser::parse_constraint`](crate::parser::Parser) rewinds
/// and produces the [`ItemKind::Verbatim`] leaf constraints have been
/// since the `classes` round, byte for byte. See
/// `docs/features/constraint-bodies/README.md`.
Constraint(ConstraintDecl),
/// `covergroup g ... endgroup` and everything inside it (IEEE 1800 §19.3).
///
/// A body the covergroup grammar does not recognise never reaches this
/// variant: [`Parser::parse_covergroup`](crate::parser::Parser) rewinds
/// and produces the [`ItemKind::Verbatim`] leaf covergroups had before
/// this round, byte for byte. See
/// `docs/features/covergroup-bodies/README.md`.
Covergroup(Box<CovergroupDecl>),
/// `property p; … endproperty` and `sequence s; … endsequence`
/// (IEEE 1800 §16.8, §16.12).
PropSeqDecl(Box<PropSeqDecl>),
/// `[label :] assert|assume|cover|restrict property ( … ) action_block`
/// and `cover sequence ( … ) …` (IEEE 1800 §16.14).
Assertion(Box<AssertionDecl>),
/// `default disable iff ( expression_or_dist ) ;` — the standing
/// `disable iff` clause of every concurrent assertion in the scope
/// (IEEE 1800 §16.15).
DefaultDisable(Box<DisableIff>),
/// A block lucisv deliberately does not model, kept byte-for-byte:
/// a concurrent assertion
/// (`assert property ( ... );`), a `property`/`sequence` declaration —
/// and a `constraint` or a `covergroup` whose body did not fit the
/// grammar. See `docs/features/classes/README.md`,
/// `docs/features/assertions/README.md`,
/// `docs/features/constraint-bodies/README.md`,
/// `docs/features/covergroup-bodies/README.md` and
/// `docs/features/sva-bodies/README.md` for why each one is verbatim.
Verbatim(RawText),
Defparam(Vec<(Expr, Expr)>),
/// `alias a = b = c;` (IEEE 1800 §10.11): one bidirectional connection
/// between two or more net lvalues. The `=`s are separators — no term is
/// the value of any other — so the terms are a flat list.
Alias(Vec<Expr>),
/// A **null item**: a lone `;` standing where an item belongs
/// (IEEE 1800-2017 A.1.4 `package_or_generate_item_declaration ::= … | ;`
/// and `class_item ::= … | ;`). Legal and meaningless in every item
/// scope, and written constantly after `endgenerate`, after a generate
/// block's `end` and after `endmodule`. The span is the `;` itself; the
/// `empty-item` lint is what tells the user about it.
///
/// The `;` after `endfunction`/`endtask` is *not* one of these: it is
/// consumed inside the declaration and recorded as
/// [`FunctionDecl::end_semi`] / [`TaskDecl::end_semi`], which predates
/// this variant.
Empty,
/// Source that could not be parsed as an item, kept verbatim.
///
/// Only error-tolerant parsing
/// (`vlog_parser::parse_source_tolerant`) ever produces this; the
/// strict entry point fails on the first error instead, so the formatter
/// never sees one. See `docs/features/error-recovery/README.md`.
Error(RawText),
}
/// One `pkg::item` (or `pkg::*`) path of an `import`, each half with its own
/// range — a language server resolves the package and the imported name
/// separately.
#[derive(Debug, Clone)]
pub struct ImportPath {
pub pkg: Name,
/// The imported name, or `*` for a wildcard (whose span is the `*`).
pub item: Name,
}
impl ImportPath {
/// The path as it is written: `pkg::item`.
pub fn text(&self) -> String {
format!("{}::{}", self.pkg.text, self.item.text)
}
}
/// The `import "DPI-C" [context|pure] [c_name =]` prefix that makes a function
/// or task prototype a DPI import (IEEE 1800 §35.5). A DPI import *is* a
/// prototype, so it is modelled as [`FunctionDecl`] / [`TaskDecl`] with this
/// hung off it rather than as an item kind of its own.
#[derive(Debug, Clone)]
pub struct DpiImport {
/// The linkage spec string as written, quotes included: `"DPI-C"`.
pub spec: String,
/// The DPI import property, when written: `context` or `pure`.
pub property: Option<String>,
/// The linkage name of the `c_name = function ...` spelling.
pub c_identifier: Option<Name>,
}
/// An `export` item: a DPI export or a package re-export.
#[derive(Debug)]
pub enum ExportDecl {
/// `export "DPI-C" [c_name =] function|task name;` (IEEE 1800 §35.5.4).
Dpi(DpiExport),
/// `export pkg::item, pkg::*;` (IEEE 1800 §26.6). The LRM's `export *::*;`
/// is one path whose package half is `*` as well.
Package(Vec<ImportPath>),
}
/// One `export "DPI-C" ... ;` declaration.
#[derive(Debug)]
pub struct DpiExport {
/// The linkage spec string as written, quotes included: `"DPI-C"`.
pub spec: String,
/// The linkage name of the `c_name = function ...` spelling.
pub c_identifier: Option<Name>,
/// `function` or `task`.
pub kw: String,
/// The exported SystemVerilog task or function name.
pub name: Name,
}
/// The sizes the comment-slots round pinned, so the next slot added inline
/// fails here rather than as a stack overflow in a debug-build test that
/// only runs with the corpus checked out (docs/features/comment-slots).
/// `Expr` is walked recursively; every expression-level comment struct is
/// boxed to keep it at its pre-round size.
#[cfg(all(test, target_pointer_width = "64"))]
mod size_pins {
use super::*;
use std::mem::size_of;
#[test]
fn expr_stmt_and_stmt_kind_stay_within_their_pinned_sizes() {
assert!(size_of::<Expr>() <= 96, "Expr is {} bytes: box the new field", size_of::<Expr>());
assert!(size_of::<StmtKind>() <= 392, "StmtKind is {} bytes", size_of::<StmtKind>());
assert!(size_of::<Stmt>() <= 552, "Stmt is {} bytes", size_of::<Stmt>());
}
}
+550
View File
@@ -0,0 +1,550 @@
//! What a module, interface or program is made of: the header (parameter
//! ports, ports), the items that instantiate or drive (continuous assignments,
//! instantiations, gates, `bind`), generate constructs, modports and clocking
//! blocks.
use super::*;
/// A `module` / `macromodule` / `interface` declaration.
///
/// An interface header is the module header's grammar (IEEE 1800 §25.3) and an
/// interface body is the module body's item list plus `modport` and `clocking`,
/// so the two share one node; `kw` says which was written and
/// [`Module::end_kw`] the closing keyword that goes with it.
#[derive(Debug)]
pub struct Module {
pub kw: String,
/// Comments written between the keyword and the name
/// (`module /*c*/ m`).
pub before_name: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// One entry per `import` statement written in the header. A header may
/// write several (`module m import a::*; import b::t; (...)`), and merging
/// them into one statement would replace a `;` with a `,`.
pub imports: Vec<HeaderImport>,
/// Comments written between the header's name (or its last `import`) and
/// the `#` of the parameter port list. Empty when the header wrote none.
pub param_comments: Vec<Comment>,
/// Comments written between that `#` and its `(`.
pub param_after_hash: Vec<Comment>,
/// `None` when the header wrote no `#( ... )` at all; an empty `Some` is a
/// written-but-empty `#()`, which must be printed back.
pub param_ports: Option<Vec<ParamPort>>,
/// Directives written between the parameter ports, in source order.
pub param_directives: Vec<ListDirective>,
/// Comments written after the last parameter port and before the `)`.
pub param_dangling: Vec<Comment>,
/// Comments written between whatever precedes the port list and its `(`.
/// Empty when the header wrote no parenthesized port list.
pub port_comments: Vec<Comment>,
pub ports: PortList,
/// Directives written between the header's ports, in source order. They
/// live here rather than inside [`PortList`] because a list whose every
/// element sits in an `` `ifdef`` arm is still a [`PortList::Empty`].
pub port_directives: Vec<ListDirective>,
/// Comments written after the last port and before the `)`.
pub port_dangling: Vec<Comment>,
/// Comments written between the header's last token and its `;`.
pub before_semi: Vec<Comment>,
pub items: Vec<Item>,
pub dangling: Vec<Comment>,
/// Comments written in the two gaps of the footer's `: name` label.
pub end_label_comments: Box<LabelComments>,
pub end_label: Option<String>,
/// Byte range of `end_label`.
pub end_label_span: Option<TextRange>,
}
impl Module {
/// The keyword that closes this declaration: `endmodule`, `endinterface`
/// or `endprogram`.
pub fn end_kw(&self) -> &'static str {
match self.kw.as_str() {
"interface" => "endinterface",
"program" => "endprogram",
_ => "endmodule",
}
}
}
/// One `import` statement in a module header, with the comments written
/// around it. A header import is not an [`Item`], so it needs its own place
/// to keep them.
#[derive(Debug)]
pub struct HeaderImport {
pub meta: Meta,
/// The comma-separated paths of this one statement.
pub paths: Vec<ImportPath>,
}
#[derive(Debug)]
pub enum PortList {
/// No port list at all: `module m;`
None,
/// Empty parens: `module m();`
Empty,
/// ANSI-style declarations in the header.
Ansi(Vec<AnsiPort>),
/// Non-ANSI: just names in the header, declared in the body.
NonAnsi(Vec<NonAnsiPort>),
}
/// A name-only port in a non-ANSI header (`module m (a, b);`). It has no
/// `name_span`: the port *is* its name, so `span` already is that range.
#[derive(Debug)]
pub struct NonAnsiPort {
pub meta: Meta,
pub name: String,
/// True when a `,` followed this element in the source. See
/// [`ListDirective::comma`]: a directive between two elements can move
/// the comma to the other side of it, so the formatter reproduces the
/// placement it parsed rather than deriving it from the element's index.
pub comma: bool,
/// Code extent of the port name.
pub span: TextRange,
}
#[derive(Debug)]
pub struct AnsiPort {
pub meta: Meta,
pub dir: Option<String>,
/// Comments written between the direction keyword and the type
/// (`input /*c*/ logic clk`). Empty when no direction was written.
pub after_dir: Vec<Comment>,
pub net: Option<String>,
pub ty: DataType,
/// Comments written between the type and the port's name.
pub before_name: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
pub unpacked: Vec<Dim>,
/// Comments written on either side of the `=` of a default value.
pub eq_comments: Box<BinaryComments>,
pub default: Option<Expr>,
/// True when a `,` followed this element in the source; see
/// [`NonAnsiPort::comma`].
pub comma: bool,
/// Code extent of the port declaration.
pub span: TextRange,
}
#[derive(Debug)]
pub struct ParamPort {
pub meta: Meta,
/// `parameter` or `localparam`; empty if omitted (continuation params).
pub kw: Option<String>,
/// Comments written between that keyword and the type
/// (`parameter /*c*/ int W = 8`).
pub after_kw: Vec<Comment>,
pub ty: DataType,
pub is_type: bool,
/// Comments written between the type and the parameter's name.
pub before_name: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
pub unpacked: Vec<Dim>,
/// Comments written on either side of the `=` of a default value.
pub eq_comments: Box<BinaryComments>,
pub default: Option<Expr>,
/// True when a `,` followed this element in the source; see
/// [`NonAnsiPort::comma`].
pub comma: bool,
/// Code extent of the parameter port.
pub span: TextRange,
}
#[derive(Debug)]
pub struct ContAssign {
/// Drive strength: the `(weak0, pull1)` in
/// `assign (weak0, pull1) x = y;` (IEEE 1800 §10.3.1), in source order.
pub strength: Option<DriveStrength>,
/// Delay expression: the `5` in `assign #5 x = y;`
pub delay: Option<Expr>,
pub assigns: Vec<AssignPair>,
}
/// The `( strength0 , strength1 )` of a continuous assignment or a gate. The
/// two strengths are stored in the order the source wrote them — the language
/// allows either order and lucisv is not a legality checker.
#[derive(Debug)]
pub struct DriveStrength {
pub first: String,
/// `None` for the single-strength spelling `pullup (weak1) p (x);`
/// (IEEE 1800 §28.3's `pullup_strength`), which only a pull gate takes.
pub second: Option<String>,
}
#[derive(Debug)]
pub struct AssignPair {
pub meta: Meta,
pub lhs: Expr,
pub rhs: Expr,
/// Comments written between the left-hand side and the `=`
/// (`assign y /*c*/ = x;`).
pub op_comments: Vec<Comment>,
/// Comments written between the `=` and the right-hand side. Kept here so
/// they print on the `=`'s side of the value instead of drifting into it.
pub rhs_comments: Vec<Comment>,
/// Code extent of `lhs = rhs`.
pub span: TextRange,
}
#[derive(Debug)]
pub struct Instantiation {
pub module: String,
/// Byte range of `module`. A scope-qualified name (`pkg::mod`) is stored
/// with its `::` glued, so there the slice matches `module` only modulo
/// the whitespace the source may have written around the `::`.
pub module_span: TextRange,
/// Comments written between the module name and the `#` of the parameter
/// override list. Empty when the source wrote no `#(...)`.
pub param_comments: Vec<Comment>,
/// Comments written between that `#` and its `(`.
pub after_hash: Vec<Comment>,
/// The parameter override list, `None` when the source wrote no `#(...)`
/// at all. An empty `Some` is a written-but-empty `#()`, which must be
/// printed back: dropping it would lose two tokens.
pub params: Option<Vec<Connection>>,
/// Directives written between the parameter overrides, in source order.
/// They live here rather than inside `params` because a `#( ... )` whose
/// whole body is one `` `include`` has no override to hang them on.
pub param_directives: Vec<ListDirective>,
pub instances: Vec<Instance>,
/// Comments written between the last instance and the `;`.
pub before_semi: Vec<Comment>,
}
#[derive(Debug)]
pub struct Instance {
pub meta: Meta,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
pub dims: Vec<Dim>,
/// Comments written between the instance name (or its dimensions) and the
/// `(` opening its connection list.
pub conn_comments: Vec<Comment>,
pub conns: Connections,
/// Directives written between the connections, in source order. They live
/// here rather than inside [`Connections`] because a list whose every
/// element sits in an `` `ifdef`` arm is still an empty
/// [`Connections::Ordered`].
pub conn_directives: Vec<ListDirective>,
/// Code extent of the instance, its connection list included.
pub span: TextRange,
}
#[derive(Debug)]
pub enum Connections {
Ordered(Vec<OrderedConn>),
Named(Vec<Connection>),
}
#[derive(Debug)]
pub struct OrderedConn {
pub meta: Meta,
pub expr: Option<Expr>,
/// True when a `,` followed this element in the source; see
/// [`NonAnsiPort::comma`].
pub comma: bool,
/// Code extent of the connection; empty for an omitted one.
pub span: TextRange,
}
#[derive(Debug)]
pub struct Connection {
pub meta: Meta,
/// Comments written between the `.` and the port name (`. /*c*/ clk(x)`).
pub after_dot: Vec<Comment>,
/// Port/parameter name; `*` for the SystemVerilog `.*` wildcard.
pub name: String,
/// Byte range of `name`; empty for a positional connection, which has no
/// name to point at.
pub name_span: TextRange,
/// Comments written between the name and the `(` (`.clk /*c*/ (x)`).
pub before_open: Vec<Comment>,
/// Comments written just inside the `(` (`.clk( /*c*/ x)`). An empty
/// connection keeps its own in [`ExprKind::Empty`], as it always has.
pub after_open: Vec<Comment>,
/// `None` for `.name` (implicit) and `.*`; `Some` for `.name(expr)`.
/// An explicitly empty connection `.name()` is `Some(Expr::Empty)`.
pub expr: Option<Expr>,
/// Comments written between the value and the connection's own `)`
/// (`.data_i (x /* verilator lint_off */)`). Printed back inside the
/// parens: after them they would sit in the enclosing list instead.
pub close_comments: Vec<Comment>,
/// True when a `,` followed this element in the source; see
/// [`NonAnsiPort::comma`].
pub comma: bool,
/// Code extent of the connection.
pub span: TextRange,
}
/// One segment of a hierarchical path: the `gen[0]` of `top.gen[0].u_core`.
///
/// Only a `bind` directive's target is written this way today. Every other
/// dotted name in the AST is either an expression
/// ([`ExprKind::Member`]) or a joined string, and neither wanted a third
/// spelling — this one exists because a bind target is a *scope*, not a
/// value, and because its `[…]` is not part of any name.
#[derive(Debug)]
pub struct PathSegment {
/// The segment's identifier, exactly as written.
pub name: String,
/// Byte range of `name`.
pub span: TextRange,
/// The `[…]` selector written after it, if any: `gen[0]`'s `0`.
pub index: Option<Expr>,
}
/// A `bind` directive: everything after the target scope is an ordinary
/// module instantiation, so it is parsed and printed as one.
#[derive(Debug)]
pub struct BindDirective {
/// The bind target: a module or interface name (`prim_secded_22_16_tb`),
/// an instance name (`i_nopass1`) or a hierarchical path
/// (`top.u_dut.u_core`, `top.gen[0].u_core`), one [`PathSegment`] per
/// name. A path is *not* joined into one string: an escaped segment needs
/// the whitespace that terminates it (`docs/topo.md` §2.9-21), and an
/// indexed segment is not a name at all.
pub target: Vec<PathSegment>,
/// Byte range of the whole target path, `.` separators and `[…]`
/// selectors included.
pub target_span: TextRange,
/// Comments written between `bind` and the target name. They have no node
/// of their own to hang on — the target is a bare string — so they are
/// kept here and printed back between the same two tokens.
pub target_comments: Vec<Comment>,
/// The `: u_a, u_b` instance list that narrows a module target to
/// particular instances. Empty when the source wrote no `:`.
pub instances: Vec<Name>,
/// Comments written between the target (or the instance list) and the
/// module name of the instantiation, for the same reason.
pub module_comments: Vec<Comment>,
/// The instantiation being bound, identical in shape to a standalone one.
pub inst: Instantiation,
}
impl BindDirective {
/// The target path as one dotted string, for consumers that want a
/// spelling rather than the segments — the workspace's paths, a
/// diagnostic, a test. An escaped segment keeps the space that terminates
/// it, so the spelling re-lexes as the same names.
pub fn target_path(&self) -> String {
let mut out = String::new();
for seg in &self.target {
if !out.is_empty() {
if out.rsplit(char::is_whitespace).next().is_some_and(|s| s.contains('\\')) {
out.push(' ');
}
out.push('.');
}
out.push_str(&seg.name);
}
out
}
/// The head of the target path — the module, interface or instance name a
/// `bind` starts at. `None` only for a path with no segments, which the
/// parser never builds.
pub fn head(&self) -> Option<&PathSegment> {
self.target.first()
}
}
#[derive(Debug)]
pub struct GateInstantiation {
/// `and`, `or`, `not`, ...
pub gate: String,
/// The `(weak1)` in `pullup (weak1) p (x);` (IEEE 1800 §28.3), or the
/// `(strong0, strong1)` pair every driving gate also accepts.
pub strength: Option<DriveStrength>,
/// The delay written after `#`: empty when there is none, one element for
/// every spelling a net or a continuous assignment also accepts, and two
/// or three for the `(rise, fall[, turn-off])` list that only a gate
/// takes (IEEE 1800 §28.14, `top_earlgrey/ip/ast/rtl/aon_osc.sv:41`).
pub delay: Vec<Expr>,
pub instances: Vec<GateInstance>,
}
#[derive(Debug)]
pub struct GateInstance {
pub meta: Meta,
pub name: Option<String>,
/// Byte range of `name`.
pub name_span: Option<TextRange>,
pub args: Vec<ExprItem>,
/// Code extent of the gate instance.
pub span: TextRange,
}
#[derive(Debug)]
pub struct GenIf {
pub cond: Expr,
pub then: GenBlock,
pub els: Option<Box<GenElse>>,
/// Code extent of the whole `if`, its `else` branch included.
pub span: TextRange,
}
#[derive(Debug)]
pub enum GenElse {
/// `else if`: boxed because a `Meta` plus a whole `GenIf` inline makes
/// this variant several times the size of `Block`.
If(Meta, Box<GenIf>),
Block(GenBlock),
}
#[derive(Debug)]
pub struct GenFor {
pub init: SimpleAssign,
pub init_genvar: bool,
/// Comments written between the `genvar` keyword and the loop variable.
/// Empty when no `genvar` was written.
pub after_genvar: Vec<Comment>,
pub cond: Expr,
pub step: ForStep,
/// The same seven header slots a statement `for` owns.
pub comments: Box<ForComments>,
pub body: GenBlock,
}
#[derive(Debug)]
pub struct GenCase {
pub expr: Expr,
pub items: Vec<GenCaseItem>,
pub dangling: Vec<Comment>,
}
#[derive(Debug)]
pub struct GenCaseItem {
pub meta: Meta,
/// Empty means `default`. Each label carries the comments written around
/// it, so a comment between two labels stays between them.
pub labels: Vec<ExprItem>,
/// Comments written between the last label — or the `default` keyword —
/// and the `:` that ends the label list.
pub before_colon: Vec<Comment>,
pub body: GenBlock,
/// Code extent of the case item, its body included.
pub span: TextRange,
}
/// A single generate block: either a labeled/unlabeled begin..end with items,
/// or a single item.
#[derive(Debug)]
pub struct GenBlock {
/// Comments written between whatever precedes the block and its `begin`
/// (`for (…) /*c*/ begin : g`). Empty for a block-less single item, which
/// keeps them in its own leading comments.
pub before_kw: Vec<Comment>,
/// Comments written between `begin` and the `:` of its label.
pub before_colon: Vec<Comment>,
/// Comments written between that `:` and the label name.
pub after_colon: Vec<Comment>,
pub label: Option<String>,
/// Byte range of `label`.
pub label_span: Option<TextRange>,
pub is_block: bool,
pub items: Vec<Item>,
pub dangling: Vec<Comment>,
/// Comments written in the two gaps of `end : g`.
pub end_label_comments: Box<LabelComments>,
/// Label after `end :`.
pub end_label: Option<String>,
/// Byte range of `end_label`.
pub end_label_span: Option<TextRange>,
/// Code extent of the block or of the single item it holds.
pub span: TextRange,
}
/// One modport of a `modport a (...), b (...);` declaration (IEEE 1800 §25.5).
#[derive(Debug)]
pub struct ModportDecl {
/// Comments written around this modport within the declaration.
pub meta: Meta,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
pub ports: Vec<ModportPort>,
/// Comments written after the last port and before the `)`.
pub dangling: Vec<Comment>,
/// True when a `,` followed this modport in the source.
pub comma: bool,
/// Code extent from the name through the closing `)`.
pub span: TextRange,
}
/// One direction group of a modport's port list: the keyword plus every name
/// it governs. `input a, b, output c` is two groups, which is how the source's
/// grouping survives a reformat.
#[derive(Debug)]
pub struct ModportPort {
pub meta: Meta,
/// `input`, `output`, `inout`, `ref`, `import`, `export` or `clocking`.
pub kw: String,
/// The names this keyword governs. A `clocking` group names exactly one.
pub names: Vec<Name>,
/// True when a `,` followed the last name of this group in the source.
pub comma: bool,
/// Code extent from the keyword through its last name.
pub span: TextRange,
}
/// `clocking cb @(posedge clk); ... endclocking` (IEEE 1800 §14.3), including
/// the `default clocking` spellings and the body-less
/// `default clocking cb;` clocking assignment (§14.12).
#[derive(Debug)]
pub struct ClockingDecl {
/// True when the declaration was written `default clocking ...`.
pub is_default: bool,
/// `None` for the anonymous `default clocking @(posedge clk);` form.
pub name: Option<Name>,
/// The `@( ... )` clocking event. `None` for `default clocking cb;`, which
/// selects an existing clocking block and has no body.
pub event: Option<SensList>,
/// Empty when there is no body (`default clocking cb;`).
pub items: Vec<ClockingItem>,
pub dangling: Vec<Comment>,
/// True when the declaration wrote an `endclocking`.
pub has_end: bool,
/// Comments written in the two gaps of `endclocking : cb`.
pub end_label_comments: Box<LabelComments>,
/// Label after `endclocking :`.
pub end_label: Option<String>,
/// Byte range of `end_label`.
pub end_label_span: Option<TextRange>,
}
/// One item of a clocking block's body.
#[derive(Debug)]
pub struct ClockingItem {
pub meta: Meta,
pub kind: ClockingItemKind,
/// Code extent of the item, its `;` excluded.
pub span: TextRange,
}
#[derive(Debug)]
pub enum ClockingItemKind {
/// `default input #1step output #0;` — at least one half is written.
Default { input: Option<String>, output: Option<String> },
/// `input #2 a, b;`, `output negedge c;`, `inout d;`. `skew` is the delay
/// or edge as written (`#2`, `negedge`), or `None` when omitted.
Signals { dir: String, skew: Option<String>, signals: Vec<ClockingSignal> },
}
/// One `signal [= expression]` of a clocking direction group — IEEE 1800
/// §14.4's `clocking_decl_assign`. The expression binds the clocking signal to
/// something other than the same-named signal in the enclosing scope:
/// `output tms = _tms_internal;`.
#[derive(Debug)]
pub struct ClockingSignal {
pub name: Name,
/// `None` for the plain `input tdo;` spelling.
pub value: Option<Expr>,
}
+407
View File
@@ -0,0 +1,407 @@
//! Statements: the [`Stmt`] node, every [`StmtKind`], timing controls and
//! sensitivity lists, and the pieces of `case`, `for` and `foreach`.
use super::*;
/// One slot of a `foreach`'s loop-variable bracket, with the comments written
/// on either side of it so neither drifts across the `,` that separates two
/// slots.
#[derive(Debug, Clone)]
pub struct ForeachVar {
/// The loop variable. A **skipped** dimension (IEEE 1800 §12.7.3 —
/// `foreach (q[, j])` iterates only the second) is an empty name at the
/// point it was written: it declares nothing and prints as nothing.
pub name: Name,
/// Comments written between the `[` (or the previous `,`) and this slot.
pub before: Vec<Comment>,
/// Comments written between this slot and the `,` or `]` after it.
pub after: Vec<Comment>,
}
#[derive(Debug)]
pub enum SensList {
/// `@*` or `@(*)`, with any comments written next to the `*` so the
/// formatter can print them back in the same place.
Star {
/// Comments between the `@`/`(` and the `*`.
before: Vec<Comment>,
/// Comments between the `*` and the closing `)`.
after: Vec<Comment>,
},
List {
items: Vec<SensItem>,
/// Comments written between the `@` and the `(` (`always @ /*c*/ (`).
after_at: Vec<Comment>,
},
/// `@name` or `@a.b` written without parens; printed back without them —
/// inventing a `( ... )` would be a token-stream change the safety net
/// refuses.
Bare {
expr: Expr,
/// Comments written between the `@` and the name.
after_at: Vec<Comment>,
},
}
#[derive(Debug)]
pub struct SensItem {
/// Comments written around this item: `leading` before it (after the `(`
/// or the separator), `before_sep` between it and the separator that
/// follows — or the closing `)` for the last item.
pub meta: Meta,
/// The separator written before this item; `None` on the first item.
pub sep: Option<SensSep>,
pub edge: Option<String>,
/// Comments written between the edge keyword and the expression
/// (`@(posedge /*c*/ clk)`). Empty when no edge keyword was written.
pub after_edge: Vec<Comment>,
pub expr: Expr,
/// The gating condition of `@(posedge clk iff enable)` — IEEE 1800
/// §9.4.2's optional `iff expression` on one event expression term.
pub iff: Option<Expr>,
}
/// How two event-list items were separated in the source. Both spellings are
/// legal and mean the same thing, but rewriting one as the other changes the
/// token stream, so the formatter reproduces whichever was written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SensSep {
/// `@(posedge clk, negedge rst_n)`
Comma,
/// `@(posedge clk or negedge rst_n)`
Or,
}
#[derive(Debug)]
pub struct Stmt {
pub meta: Meta,
pub kind: StmtKind,
/// Comments written in the gap between the statement's last token and the
/// `;` that ends it (`x = 1 /* inclusive */ ;`).
///
/// The statement is the single owner of that gap — the same rule
/// [`ConstraintItem::before_semi`] states for a constraint item — because
/// the `;` is consumed in a dozen places and read in four of them to
/// decide the statement's shape. Always empty for a kind
/// [`StmtKind::takes_semi`] is false for.
pub before_semi: Vec<Comment>,
/// Code extent of the statement, its `(* ... *)` attributes included.
pub span: TextRange,
}
#[derive(Debug)]
pub enum StmtKind {
Block {
/// Comments written in the two gaps of the `begin : name` label.
label_comments: Box<LabelComments>,
label: Option<String>,
/// Byte range of `label`.
label_span: Option<TextRange>,
stmts: Vec<Stmt>,
dangling: Vec<Comment>,
/// Comments written in the two gaps of `end : name`.
end_label_comments: Box<LabelComments>,
/// Label after `end :`.
end_label: Option<String>,
/// Byte range of `end_label`.
end_label_span: Option<TextRange>,
},
ForkJoin {
/// Comments written in the two gaps of the `fork : name` label.
label_comments: Box<LabelComments>,
label: Option<String>,
/// Byte range of `label`.
label_span: Option<TextRange>,
join_kw: String,
stmts: Vec<Stmt>,
dangling: Vec<Comment>,
/// Comments written in the two gaps of `join : name`.
end_label_comments: Box<LabelComments>,
/// Label after `join :` (any join kind).
end_label: Option<String>,
/// Byte range of `end_label`.
end_label_span: Option<TextRange>,
},
If {
qualifier: Option<String>,
/// Comments written between the `if` keyword and its `(`.
after_kw: Vec<Comment>,
cond: Expr,
then: Box<Stmt>,
/// Comments written between the then-branch and the `else` keyword.
/// They are kept here, not on `els`, because printing them after the
/// keyword moves them across it and the safety net rejects that.
else_comments: Vec<Comment>,
els: Option<Box<Stmt>>,
},
Case {
qualifier: Option<String>,
kw: String,
/// Comments written between the `case` keyword and its `(`.
after_kw: Vec<Comment>,
expr: Expr,
/// True for `case (expr) inside`, whose labels may be `[lo:hi]`
/// value ranges.
inside: bool,
items: Vec<CaseItem>,
dangling: Vec<Comment>,
},
For {
init: Vec<ForInit>,
cond: Option<Expr>,
step: Vec<ForStep>,
/// The seven fixed slots of a `for ( … ; … ; … )` header.
comments: Box<ForComments>,
body: Box<Stmt>,
},
While {
cond: Expr,
body: Box<Stmt>,
},
DoWhile {
body: Box<Stmt>,
cond: Expr,
/// The `while /*a*/ ( /*b*/ cond /*c*/ )` slots. A `do ... while` is
/// the one loop with no body *after* its parentheses, so there is
/// nothing for `Fmt::header_parens` to take a comment back from.
comments: Box<HeaderComments>,
},
Repeat {
count: Expr,
body: Box<Stmt>,
},
Forever {
body: Box<Stmt>,
},
/// `foreach (arr[i, j]) stmt` (IEEE 1800 §12.7.3).
///
/// `target` is the array being iterated, which may be a package-scoped or
/// hierarchical name with index and member selects along the way
/// (`riscv_instr_pkg::supported_isa`, `page_table[i].pte`); `vars` are the
/// names in the *last* bracket group, the only one that declares loop
/// variables.
Foreach {
target: Expr,
vars: Vec<ForeachVar>,
/// Comments written around the loop-variable bracket
/// (`foreach (q /*a*/ [ … ] /*never*/)`) — `before_open`,
/// `after_open` and `before_close` only.
var_comments: Box<SegmentComments>,
/// The `foreach /*a*/ ( /*b*/ … /*c*/ ) /*d*/ body` slots.
comments: Box<HeaderComments>,
body: Box<Stmt>,
},
/// `randcase w1 : stmt; w2 : stmt; endcase` (IEEE 1800 §18.16) — a `case`
/// whose items are weights and which has no selector expression.
RandCase {
items: Vec<CaseItem>,
dangling: Vec<Comment>,
},
/// `wait fork;` — block until every child process finishes
/// (IEEE 1800 §9.6.1). `fork` is a keyword, not an expression, which is
/// why this is not a [`StmtKind::Wait`].
WaitFork,
/// `import pkg::item;` / `import pkg::*;` standing among a block's
/// declarations (IEEE 1800 §13.4.2) — the statement twin of
/// [`ItemKind::Import`].
Import(Vec<ImportPath>),
/// `typedef enum bit {WRITE, READ} rdwr_e;` written inside a
/// function/task body or a `begin` block, scoping the type to that block
/// (IEEE 1800 §6.18) — the statement twin of [`ItemKind::Typedef`], with
/// the same payload and the same layout.
Typedef(Typedef),
/// `name : stmt` — a statement label (IEEE 1800 §9.3.5).
///
/// `begin`/`fork` keep their label inside their own node, because the
/// source writes it *after* the keyword; this is the general prefix form,
/// which any statement may carry.
Labeled {
name: String,
/// Byte range of `name`.
name_span: TextRange,
stmt: Box<Stmt>,
},
/// Blocking/nonblocking/compound assignment.
Assign {
lhs: Expr,
op: String,
/// Comments written between the left-hand side and the operator
/// (`instr[6:0] /* opcode */ = ...;`). Kept here so they print on
/// the operator's left instead of being lost.
op_comments: Vec<Comment>,
/// Comments written between the operator and the right-hand side,
/// kept on the operator's line as a continuous assignment's are.
rhs_comments: Vec<Comment>,
/// Intra-assignment timing control (e.g. `#1`, `@(posedge clk)`).
timing: Option<TimingControl>,
rhs: Expr,
},
/// `force`/`release`/`deassign` statements, raw pieces.
ForceRelease {
kw: String,
lhs: Expr,
rhs: Option<Expr>,
},
/// Procedural timing control: `#10 stmt;`, `@(posedge clk) stmt;`,
/// `#10;`, `@(ev);`
Timing {
control: TimingControl,
stmt: Option<Box<Stmt>>,
},
Wait {
cond: Expr,
stmt: Option<Box<Stmt>>,
},
ExprStmt(Expr),
/// `-> event_name;`
EventTrigger(Expr),
VarDecl(DataDecl),
ParamDecl(ParamDecl),
/// Old-style task/function port declaration: `input [7:0] a;`
PortDecl(PortDecl),
Return {
/// Comments written between `return` and its value.
after_kw: Vec<Comment>,
expr: Option<Expr>,
},
Break,
Continue,
Disable(String),
Directive(RawText),
/// Macro invocation used as a statement.
MacroStmt(MacroCall),
/// A concurrent assertion written in statement position
/// (`assert property ( ... ) else $error("...");` inside an `initial`),
/// kept byte-for-byte. The statement-level twin of the assertion half of
/// [`ItemKind::Verbatim`]; see `docs/features/assertions/README.md`.
Verbatim(RawText),
/// A concurrent assertion — or an `expect` statement — written in
/// statement position, as a real node. The statement-level twin of
/// [`ItemKind::Assertion`]; a spec the SVA grammar does not recognise
/// falls back to [`StmtKind::Verbatim`] above.
Assertion(Box<AssertionDecl>),
/// Immediate assertion: kept simple — `assert (expr) stmt else stmt;`
Assert {
kw: String,
cond: Expr,
then: Option<Box<Stmt>>,
els: Option<Box<Stmt>>,
},
Null,
/// Source that could not be parsed as a statement, kept verbatim.
///
/// The statement-level twin of [`ItemKind::Error`]: produced only by
/// error-tolerant parsing, never seen by the formatter.
Error(RawText),
}
impl StmtKind {
/// True for the kinds whose own last token is followed by a `;` this
/// statement wrote — the kinds [`Stmt::before_semi`] can be non-empty
/// for.
///
/// A `begin`/`fork` block, an `if`, a `case`, a loop and a labelled
/// statement all end in a *body*, whose own last statement owns whatever
/// `;` stands there; [`StmtKind::Null`] **is** its `;`; a directive, a
/// macro call and a verbatim capture carry their own text. The three
/// shape-deciding kinds — a timing control, a `wait` and an immediate
/// assertion — take one only in the branch that wrote no body, which is
/// exactly the branch the parser read the `;` in.
///
/// One answer, read by the parser (which consumes the `;`) and by the
/// formatter (which writes it back), so the two cannot disagree about who
/// owns the gap in front of it.
pub fn takes_semi(&self) -> bool {
match self {
StmtKind::Assign { .. }
| StmtKind::ExprStmt(_)
| StmtKind::EventTrigger(_)
| StmtKind::ForceRelease { .. }
| StmtKind::VarDecl(_)
| StmtKind::ParamDecl(_)
| StmtKind::PortDecl(_)
| StmtKind::Return { .. }
| StmtKind::Break
| StmtKind::Continue
| StmtKind::Disable(_)
| StmtKind::WaitFork
| StmtKind::DoWhile { .. } => true,
StmtKind::Timing { stmt, .. } => stmt.is_none(),
StmtKind::Wait { stmt, .. } => stmt.is_none(),
StmtKind::Assert { then, els, .. } => then.is_none() && els.is_none(),
_ => false,
}
}
}
#[derive(Debug)]
pub enum TimingControl {
/// `#expr`
Delay {
/// Comments written between the `#` and the delay value
/// (`# /*c*/ 10`).
after_hash: Vec<Comment>,
expr: Expr,
},
/// `@(...)`, `@*`
Event(SensList),
}
#[derive(Debug)]
pub struct CaseItem {
pub meta: Meta,
/// Empty means `default`. Each label carries the comments written around
/// it, so a comment between two labels stays between them.
pub labels: Vec<ExprItem>,
/// Comments written between the last label — or the `default` keyword —
/// and the `:` that ends the label list.
pub before_colon: Vec<Comment>,
pub stmt: Stmt,
/// Code extent of the case item, its body included.
pub span: TextRange,
}
#[derive(Debug)]
pub struct ForInit {
/// Declared type for `for (int i = 0; ...)`.
pub ty: Option<DataType>,
/// Comments written between that type and the name (`for (int /*c*/ i`).
pub before_name: Vec<Comment>,
pub assign: SimpleAssign,
}
#[derive(Debug)]
pub struct SimpleAssign {
pub lhs: Expr,
pub op: String,
/// Comments written on either side of the operator.
pub op_comments: Box<BinaryComments>,
pub rhs: Expr,
}
/// Comments written in the fixed slots of a `for ( init ; cond ; step )`
/// header (IEEE 1800 §12.7.1). Seven punctuation positions, none of which has
/// anything beside it to carry a comment.
#[derive(Debug, Default)]
pub struct ForComments {
/// Between `for` and the `(`.
pub after_kw: Vec<Comment>,
/// Just inside the `(`.
pub after_open: Vec<Comment>,
/// Between the initialisers and the first `;`.
pub before_first_semi: Vec<Comment>,
/// Between the first `;` and the condition.
pub after_first_semi: Vec<Comment>,
/// Between the condition and the second `;`.
pub before_second_semi: Vec<Comment>,
/// Between the second `;` and the step list.
pub after_second_semi: Vec<Comment>,
/// Between the step list and the `)`.
pub before_close: Vec<Comment>,
}
#[derive(Debug)]
pub enum ForStep {
Assign(SimpleAssign),
Expr(Expr),
}
+363
View File
@@ -0,0 +1,363 @@
//! Assertions (IEEE 1800-2017 §16): `property`/`sequence` declarations,
//! concurrent assertion items, and the property-expression tree.
use super::*;
/// A `property name (...); ... endproperty [: name]` declaration and its
/// `sequence` / `endsequence` twin (IEEE 1800 §16.8, §16.12).
///
/// A body the SVA grammar does not recognise never reaches this node:
/// [`Parser::parse_prop_seq_decl`](crate::parser::Parser) rewinds and produces
/// the [`ItemKind::Verbatim`] leaf a declaration has been since the
/// `assertions` round, byte for byte. See
/// `docs/features/sva-bodies/README.md`.
#[derive(Debug)]
pub struct PropSeqDecl {
/// `property` or `sequence`, as written.
pub kw: String,
/// Comments written between the keyword and the name.
pub before_name: Vec<Comment>,
pub name: Name,
/// Comments written between the name and the `(` of the formal list.
pub before_args: Vec<Comment>,
/// The formal arguments; `None` when no parentheses were written.
pub args: Option<TfPorts>,
/// Comments written between the header and its `;`.
pub before_semi: Vec<Comment>,
/// `assertion_variable_declaration`s written before the body
/// (IEEE 1800 §16.12): ordinary data declarations.
pub locals: Vec<Item>,
/// The property spec / sequence expression the declaration stands for.
pub spec: PropSpec,
/// Comments written between the spec and its optional `;`.
pub before_spec_semi: Vec<Comment>,
/// True when a `;` was written after the spec. The LRM makes it optional
/// for a `property` and required for a `sequence`; both spellings occur,
/// so whichever was written is what prints.
pub spec_semi: bool,
/// Comments written between the spec and the closing keyword.
pub dangling: Vec<Comment>,
/// Comments written in the two gaps of `endproperty : p`.
pub end_label_comments: Box<LabelComments>,
pub end_label: Option<Name>,
}
/// A concurrent assertion statement: `[label :] assert|assume|cover|restrict
/// property ( spec ) action_block`, `cover sequence ( spec ) …` and the
/// `expect ( spec ) …` statement (IEEE 1800 §16.14, §16.17).
///
/// A spec the SVA grammar does not recognise never reaches this node, for the
/// reason [`PropSeqDecl`] gives.
#[derive(Debug)]
pub struct AssertionDecl {
/// The `lbl :` written in front, and the comments in its two gaps.
pub label: Option<Name>,
pub label_comments: Box<LabelComments>,
/// `assert`, `assume`, `cover`, `restrict` or `expect`, as written.
pub kw: String,
/// Comments written between that keyword and `property`/`sequence`.
pub after_kw: Vec<Comment>,
/// `property` or `sequence`; empty for the `expect` spelling, which
/// writes neither.
pub kw2: String,
/// Comments written between `property`/`sequence` and the `(`.
pub before_open: Vec<Comment>,
/// Comments written just inside the `(`.
pub after_open: Vec<Comment>,
pub spec: PropSpec,
/// Comments written just before the `)`.
pub before_close: Vec<Comment>,
pub action: ActionBlock,
}
/// The `action_block` after a concurrent assertion's spec (IEEE 1800 §16.14):
/// `;`, a pass statement, `else` a fail statement, or both.
#[derive(Debug, Default)]
pub struct ActionBlock {
/// Comments written between the `)` and the `;` of the bare spelling.
pub before: Vec<Comment>,
/// The pass statement. `None` for the bare `;` spelling and for the
/// `else`-only spelling.
pub pass: Option<Box<Stmt>>,
/// Comments written between the pass statement and `else`.
pub before_else: Vec<Comment>,
/// Comments written between `else` and the fail statement.
pub after_else: Vec<Comment>,
pub fail: Option<Box<Stmt>>,
}
/// A `property_spec` (IEEE 1800 §16.12): an optional clocking event, an
/// optional `disable iff ( … )`, and the property expression itself.
#[derive(Debug)]
pub struct PropSpec {
/// Comments written in front of the whole spec — between a property
/// declaration's last local variable and its body, say. Empty wherever
/// an enclosing construct already owns that gap (a concurrent
/// assertion's `after_open` does).
pub leading: Vec<Comment>,
/// A leading `@( … )` clocking event.
pub clocking: Option<SensList>,
pub disable: Option<Box<DisableIff>>,
/// Comments written between the header of the spec — its clocking event,
/// its `disable iff`, or the `(`/`;` before it — and the property
/// expression itself.
pub before_expr: Vec<Comment>,
pub expr: PropExpr,
}
/// `disable iff ( expression_or_dist )` (IEEE 1800 §16.12), and the
/// `default disable iff ( … );` item that states one for a whole scope
/// (§16.15).
#[derive(Debug)]
pub struct DisableIff {
/// True when the source wrote the `( … )` around the expression. The
/// clause inside a property spec always does; the `default` item's
/// `expression_or_dist` usually does not.
pub parens: bool,
/// Comments written in front of `disable`: after the spec's clocking
/// event, or after the `default` keyword of the item spelling.
pub before_kw: Vec<Comment>,
/// Comments written between `disable` and `iff`.
pub after_disable: Vec<Comment>,
/// Comments written between `iff` and the `(`.
pub after_iff: Vec<Comment>,
/// Comments written just inside the `(`.
pub after_open: Vec<Comment>,
pub expr: Expr,
/// Comments written just before the `)`.
pub before_close: Vec<Comment>,
/// Comments written between the `)` and the `;` of the `default`
/// spelling. Always empty for the clause inside a property spec, which
/// writes no `;`.
pub before_semi: Vec<Comment>,
}
/// One node of the `sequence_expr` / `property_expr` grammar.
#[derive(Debug)]
pub struct PropExpr {
pub kind: PropKind,
/// Code extent of the node.
pub span: TextRange,
}
/// The shapes a [`PropExpr`] takes. Every payload is boxed: the tree is
/// walked recursively and the variants differ in size by an order of
/// magnitude.
#[derive(Debug)]
pub enum PropKind {
/// An ordinary boolean expression, a sequence instance with its
/// arguments, or `s.triggered` / `s.matched` — all of which are the
/// expression grammar lucisv already has.
Expr(Box<Expr>),
/// `( prop [, match_items] )`. Written parentheses are kept as nodes and
/// printed back; the formatter invents none of its own.
Paren(Box<ParenProp>),
/// A binary operator: a word (`and`, `throughout`, `until`), a symbol
/// (`|->`, `#=#`) or a cycle delay (`a ##1 b`).
Binary(Box<PropBinary>),
/// A prefix operator word: `not`, `nexttime`, `s_always`,
/// `s_eventually`, …
Unary(Box<PropUnary>),
/// `strong ( seq )`, `weak ( seq )`, `first_match ( seq [, items] )`.
Call(Box<PropCall>),
/// `accept_on ( expr ) prop` and its three siblings.
Abort(Box<PropAbort>),
/// A leading cycle delay: `##1 b`, `##[1:3] b`.
Delay(Box<PropDelay>),
/// A repetition suffix: `b [*3]`, `b [->1:2]`.
Repeat(Box<SvaRepeat>),
/// `if ( expr ) prop [else prop]`.
If(Box<PropIf>),
/// `case ( expr ) … endcase`.
Case(Box<PropCase>),
/// A nested `property_spec`: a clocking event or a `disable iff` written
/// inside parentheses.
Spec(Box<PropSpec>),
}
/// `( prop )`, with the optional `, x = e` sequence match items
/// (IEEE 1800 §16.10).
#[derive(Debug)]
pub struct ParenProp {
/// Comments written just inside the `(`.
pub after_open: Vec<Comment>,
pub expr: PropExpr,
pub items: Vec<MatchItem>,
/// Comments written just before the `)`.
pub before_close: Vec<Comment>,
}
/// One `sequence_match_item`: `x = e`, `x += 1`, `x++` or a subroutine call.
#[derive(Debug)]
pub struct MatchItem {
pub meta: Meta,
/// Comments written between whatever precedes this item and the `,` that
/// introduces it.
pub before_comma: Vec<Comment>,
pub lhs: Expr,
/// The assignment operator, when one was written.
pub op: Option<String>,
/// Comments written on either side of that operator.
pub comments: Box<BinaryComments>,
pub rhs: Option<Expr>,
/// Code extent of the item.
pub span: TextRange,
}
/// A binary operator of the SVA grammar and the comments written beside it.
#[derive(Debug)]
pub struct PropBinary {
pub lhs: PropExpr,
pub op: PropOp,
pub comments: Box<BinaryComments>,
pub rhs: PropExpr,
}
/// Which binary operator a [`PropBinary`] spells.
#[derive(Debug)]
pub enum PropOp {
/// A word or symbol operator printed back exactly as written: `and`,
/// `intersect`, `|->`, `#-#`, …
Word(String),
/// `a ##1 b` — the cycle delay is the operator.
Delay(Box<CycleDelay>),
}
/// A `cycle_delay_range` (IEEE 1800 §16.7): `##3`, `##N`, `##(N+1)`,
/// `##[1:3]`, `##[1:$]`, `##[+]`, `##[*]`.
#[derive(Debug)]
pub struct CycleDelay {
/// Comments written between `##` and what follows it.
pub after_hash: Vec<Comment>,
/// The constant form's expression; `None` for the bracketed forms.
pub expr: Option<Expr>,
/// The bracketed form; `None` for the constant form.
pub range: Option<Box<SvaRange>>,
}
/// A leading cycle delay: `##1 b`.
#[derive(Debug)]
pub struct PropDelay {
pub delay: Box<CycleDelay>,
/// Comments written between the delay and its operand.
pub after_delay: Vec<Comment>,
pub expr: PropExpr,
}
/// The bracketed operand shared by `##[…]`, `[*…]`, `[=…]`, `[->…]` and the
/// optional `[…]` count of `nexttime`/`always`/`eventually`.
#[derive(Debug, Default)]
pub struct SvaRange {
/// Comments written just inside the `[`.
pub after_open: Vec<Comment>,
/// `+` or `*` for the two operand-less shorthands (`[+]`, `[*]`,
/// `##[+]`, `##[*]`); empty otherwise.
pub shorthand: String,
pub lo: Option<Expr>,
/// Comments written between the low bound and the `:`.
pub before_colon: Vec<Comment>,
/// Comments written between the `:` and the high bound.
pub after_colon: Vec<Comment>,
/// The high bound, `$` included; `None` when no `:` was written.
pub hi: Option<Expr>,
/// Comments written just before the `]`.
pub before_close: Vec<Comment>,
}
/// A repetition suffix (IEEE 1800 §16.9.2, §16.9.10): `[*3]`, `[*1:$]`,
/// `[*]`, `[+]`, `[=2]`, `[->1:2]`.
#[derive(Debug)]
pub struct SvaRepeat {
pub expr: PropExpr,
/// Comments written between the operand and the `[`.
pub before_open: Vec<Comment>,
/// `*`, `=` or `->`; empty for the bare `[+]`, whose `+` is the
/// [`SvaRange::shorthand`].
pub op: String,
/// Comments written between that operator and the bound.
pub after_op: Vec<Comment>,
pub range: Box<SvaRange>,
}
/// A prefix operator word: `not`, `nexttime`, `s_nexttime`, `always`,
/// `s_always`, `eventually`, `s_eventually`.
#[derive(Debug)]
pub struct PropUnary {
pub op: String,
/// Comments written between the operator and its operand — or its `[`.
pub comments: Vec<Comment>,
/// The optional bracketed count of `nexttime [2] p`, `always [1:3] p`.
pub count: Option<Box<SvaRange>>,
/// Comments written between that count's `]` and the operand.
pub after_count: Vec<Comment>,
pub expr: PropExpr,
}
/// `strong ( seq )`, `weak ( seq )` or `first_match ( seq [, items] )`.
#[derive(Debug)]
pub struct PropCall {
pub name: String,
/// Comments written between the name and the `(`.
pub before_open: Vec<Comment>,
/// Comments written just inside the `(`.
pub after_open: Vec<Comment>,
pub expr: PropExpr,
/// `first_match`'s optional trailing match items.
pub items: Vec<MatchItem>,
/// Comments written just before the `)`.
pub before_close: Vec<Comment>,
}
/// `accept_on ( expr ) prop`, and `reject_on` / `sync_accept_on` /
/// `sync_reject_on` (IEEE 1800 §16.12.10).
#[derive(Debug)]
pub struct PropAbort {
pub kw: String,
/// Comments written in the three gaps of `accept_on /*a*/ ( /*b*/ e
/// /*c*/ )`.
pub comments: Box<HeaderComments>,
pub cond: Expr,
pub expr: PropExpr,
}
/// `if ( expr ) prop [else prop]` at property position (IEEE 1800 §16.12.5).
#[derive(Debug)]
pub struct PropIf {
/// The `if`'s three header gaps; `before_body` holds `) /*c*/ prop`.
pub comments: Box<HeaderComments>,
pub cond: Expr,
pub then: PropExpr,
/// Comments written between the then-branch and `else`.
pub before_else: Vec<Comment>,
/// Comments written between `else` and the else-branch.
pub after_else: Vec<Comment>,
pub els: Option<PropExpr>,
}
/// `case ( expr ) … endcase` at property position (IEEE 1800 §16.12.5).
#[derive(Debug)]
pub struct PropCase {
pub comments: Box<HeaderComments>,
pub cond: Expr,
pub items: Vec<PropCaseItem>,
/// Comments written between the last item and `endcase`.
pub dangling: Vec<Comment>,
}
/// One arm of a property `case`.
#[derive(Debug)]
pub struct PropCaseItem {
pub meta: Meta,
/// The labels written before the `:`; empty for `default`.
pub labels: Vec<ExprItem>,
pub is_default: bool,
/// Comments written between the labels (or `default`) and the `:`.
pub before_colon: Vec<Comment>,
/// Comments written between the `:` and the expression.
pub after_colon: Vec<Comment>,
pub expr: PropExpr,
/// Comments written between the expression and the arm's `;`.
pub before_semi: Vec<Comment>,
/// Code extent of the arm.
pub span: TextRange,
}
File diff suppressed because it is too large. Load diff
+445
View File
@@ -0,0 +1,445 @@
//! Concurrent assertions and the SVA declarations: `assert`/`assume`/
//! `cover`/`restrict property` items and statements with their action
//! blocks, `property`/`sequence` declarations, `expect`, and
//! `default disable iff`. The property-expression grammar these all
//! contain is [`super::sva`].
use super::*;
/// 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"];
impl<'a> Parser<'a> {
/// 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.
pub(super) 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");
// `cover sequence ( ... )` is the one spelling that names `sequence`
// rather than `property` (IEEE 1800 §16.14); nothing else may.
let second = self.nth(i + 1);
opens && (second.is_kw("property") || (head.is_kw("cover") && second.is_kw("sequence")))
}
/// 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.
pub(super) 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")?;
self.skip_to_semi()?;
Ok(self.verbatim_since(start, col))
}
// ------------------------------------------------------------------
// The SVA declarations
// ------------------------------------------------------------------
/// `property name [( formals )]; [locals] spec [;] endproperty [: name]`
/// and its `sequence` / `endsequence` twin (IEEE 1800 §16.8, §16.12),
/// behind the rewind-to-verbatim fallback this round's README describes.
pub(super) fn parse_prop_seq_decl(&mut self) -> PResult<ItemKind> {
let mark = self.rewind_mark();
match self.parse_prop_seq_decl_inner() {
Ok(decl) => {
self.prop_seq_decls += 1;
Ok(ItemKind::PropSeqDecl(Box::new(decl)))
}
Err(_) => {
self.rewind_to(mark);
self.prop_seq_fallbacks += 1;
self.parse_property_decl().map(ItemKind::Verbatim)
}
}
}
fn parse_prop_seq_decl_inner(&mut self) -> PResult<PropSeqDecl> {
let kw = self.cur().text.clone();
let end_kw = if kw == "sequence" { "endsequence" } else { "endproperty" };
self.bump();
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("(") {
// `property p(sequence a, untyped b);` — the two formal type
// spellings only a property or a sequence has.
self.sva_formals = true;
let out = self.parse_tf_ports();
self.sva_formals = false;
Some(out?)
} else {
None
};
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
let mut locals = Vec::new();
while self.at_assertion_var_decl() {
let start = self.here();
let meta = self.take_meta();
let decl = self.parse_data_decl()?;
locals.push(Item { meta, kind: ItemKind::DataDecl(decl), span: self.span_from(start) });
}
let spec = self.parse_prop_spec()?;
let before_spec_semi = self.gap_before(";");
let spec_semi = self.eat_sym(";");
let dangling = self.take_dangling();
self.expect_kw(end_kw)?;
let (end_label_comments, end_label) = self.parse_label_with()?;
Ok(PropSeqDecl {
kw,
before_name,
name,
before_args,
args,
before_semi,
locals,
spec,
before_spec_semi,
spec_semi,
dangling,
end_label_comments,
end_label,
})
}
/// True when an `assertion_variable_declaration` — an ordinary data
/// declaration (IEEE 1800 §16.12) — stands at the cursor, rather than the
/// property spec that follows the last of them.
fn at_assertion_var_decl(&self) -> bool {
let t = self.cur();
if t.is_kw("var") {
return true;
}
if t.kind == TokenKind::Keyword {
return TYPE_KEYWORDS.contains(&t.text.as_str());
}
t.kind == TokenKind::Ident && self.at_typed_declarator()
}
/// A concurrent assertion at item position, behind the same fallback.
pub(super) fn parse_assertion_item(&mut self) -> PResult<ItemKind> {
let mark = self.rewind_mark();
match self.parse_assertion_decl() {
Ok(decl) => {
self.assertions += 1;
Ok(ItemKind::Assertion(Box::new(decl)))
}
Err(_) => {
self.rewind_to(mark);
self.assertion_fallbacks += 1;
self.parse_concurrent_assertion().map(ItemKind::Verbatim)
}
}
}
/// The same at statement position.
pub(super) fn parse_assertion_stmt(&mut self) -> PResult<StmtKind> {
let mark = self.rewind_mark();
match self.parse_assertion_decl() {
Ok(decl) => {
self.assertions += 1;
Ok(StmtKind::Assertion(Box::new(decl)))
}
Err(_) => {
self.rewind_to(mark);
self.assertion_fallbacks += 1;
self.parse_concurrent_assertion().map(StmtKind::Verbatim)
}
}
}
/// An `expect ( spec ) action_block` statement (IEEE 1800 §16.17), behind
/// the fallback [`Parser::parse_expect_statement`] was.
pub(super) fn parse_expect_stmt(&mut self) -> PResult<StmtKind> {
let mark = self.rewind_mark();
match self.parse_assertion_decl() {
Ok(decl) => {
self.assertions += 1;
Ok(StmtKind::Assertion(Box::new(decl)))
}
Err(_) => {
self.rewind_to(mark);
self.assertion_fallbacks += 1;
self.parse_expect_statement().map(StmtKind::Verbatim)
}
}
}
/// `[label :] assert|assume|cover|restrict property ( spec ) action`,
/// `cover sequence ( spec ) action` and `expect ( spec ) action`.
fn parse_assertion_decl(&mut self) -> PResult<AssertionDecl> {
let mut label = None;
let mut label_comments: Box<LabelComments> = Box::default();
if self.cur().kind == TokenKind::Ident && self.nth(1).is_sym(":") {
label = Some(self.expect_name()?);
label_comments.before_colon = self.gap_before(":");
self.expect_sym(":")?;
label_comments.after_colon = self.take_gap();
}
let kw = self.bump().text;
let mut after_kw = Vec::new();
let mut kw2 = String::new();
if self.cur().is_kw("property") || self.cur().is_kw("sequence") {
after_kw = self.take_gap();
kw2 = self.bump().text;
}
let before_open = self.take_before_open("(");
self.expect_sym("(")?;
let after_open = self.take_gap();
let spec = self.parse_prop_spec()?;
let before_close = self.gap_before(")");
self.expect_sym(")")?;
let action = self.parse_action_block()?;
Ok(AssertionDecl {
label,
label_comments,
kw,
after_kw,
kw2,
before_open,
after_open,
spec,
before_close,
action,
})
}
/// `action_block ::= ; | statement_or_null [ else statement_or_null ] |
/// else statement_or_null` (IEEE 1800 §16.14). Both halves are the
/// ordinary statement the parser already reads.
fn parse_action_block(&mut self) -> PResult<ActionBlock> {
let mut action = ActionBlock::default();
if self.cur().is_sym(";") {
action.before = self.take_gap();
self.bump();
return Ok(action);
}
if !self.cur().is_kw("else") {
action.pass = Some(Box::new(self.parse_stmt()?));
}
if self.cur().is_kw("else") {
action.before_else = self.take_gap();
self.bump();
action.after_else = self.take_gap();
action.fail = Some(Box::new(self.parse_stmt()?));
}
Ok(action)
}
/// `default disable iff ( expression_or_dist ) ;` (IEEE 1800 §16.15),
/// behind the fallback [`Parser::parse_default_disable`] was.
pub(super) fn parse_default_disable_item(&mut self) -> PResult<ItemKind> {
let mark = self.rewind_mark();
match self.parse_default_disable_inner() {
Ok(decl) => Ok(ItemKind::DefaultDisable(Box::new(decl))),
Err(_) => {
self.rewind_to(mark);
self.parse_default_disable().map(ItemKind::Verbatim)
}
}
}
fn parse_default_disable_inner(&mut self) -> PResult<DisableIff> {
self.expect_kw("default")?;
let mut decl = self.parse_disable_iff(false)?;
decl.before_semi = self.gap_before(";");
self.expect_sym(";")?;
Ok(decl)
}
}
+659
View File
@@ -0,0 +1,659 @@
//! Classes and their constraint blocks: the class header and `extends`
//! clause, and the `constraint` sub-grammar (IEEE 1800 §18.5) with its
//! `dist`, `solve … before`, `soft` and `foreach` items. See
//! `docs/features/classes/README.md` and
//! `docs/features/constraint-bodies/README.md`.
use super::stmt::ForeachTarget;
use super::*;
impl<'a> Parser<'a> {
/// `[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`.
pub(super) fn parse_class(&mut self) -> PResult<ClassDecl> {
let mut prefix = self.take_member_prefix();
// `interface class ic; ... endclass` (IEEE 1800 §8.26). The word rides
// in the prefix beside `virtual`, because that is what it is: a
// keyword written in front of `class`, printed back in source order.
// What it changes is the body's *legality* — only pure virtual method
// prototypes, parameters and typedefs may stand in one — and legality
// is a checker's business, not a formatter's.
if self.cur().is_kw("interface") && self.nth(1).is_kw("class") {
let text = self.bump().text;
prefix.push(Qualifier { text, after: self.take_gap() });
}
self.expect_kw("class")?;
let mut before_name = self.take_gap();
let lifetime = if self.cur().is_kw("static") || self.cur().is_kw("automatic") {
let kw = self.bump().text;
before_name.append(&mut self.take_gap());
Some(kw)
} 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;
}
}
}
let before_semi = self.gap_before(";");
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_comments, end_name) = self.parse_label_with()?;
let (end_label, end_label_span) = split_label(end_name);
Ok(ClassDecl {
prefix,
before_name,
lifetime,
name,
name_span,
param_comments,
param_after_hash: params.after_hash,
param_ports: params.ports,
param_directives: params.directives,
param_dangling: params.dangling,
extends,
implements,
before_semi,
items,
dangling,
end_label_comments,
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 after_hash = Vec::new();
let mut param_directives = Vec::new();
if self.cur().is_sym("#") {
self.bump();
after_hash = self.take_gap();
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 {
after_hash,
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.
pub(super) 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,
})
}
/// 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 ForeachTarget { expr: array, vars, comments: var_comments } =
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,
var_comments,
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.
pub(super) 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).
pub(super) 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.
pub(super) 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.
pub(super) 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.
pub(super) 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)))
}
}
+621
View File
@@ -0,0 +1,621 @@
//! Covergroups (IEEE 1800 §19): the header and sampling event, coverpoints
//! and crosses, and the bins sub-grammar — value, transition, `with` and
//! `binsof` selections. See `docs/features/covergroup-bodies/README.md`.
use super::*;
/// 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,
}
}
impl<'a> Parser<'a> {
/// `[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`.
pub(super) 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()?.args) } 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_comments, end_label) = self.parse_label_with()?;
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_comments,
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.
pub(super) 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()?.args;
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 })))
}
}
+364
View File
@@ -0,0 +1,364 @@
//! The token cursor and the comment plumbing.
//!
//! Everything a grammar file does to the token stream goes through here:
//! looking at the current token, consuming it ([`Parser::bump`]), the
//! nesting and chain budgets ([`Parser::enter`] / [`Parser::link`]), the
//! `expect_*` / `eat_*` pair every production is written with, spans, and
//! the `take_*` family that moves a consumed token's comments into the
//! slot the node keeps them in. Nothing here knows any grammar; nothing
//! outside here touches `pos`, `pending_leading` or `pending_trailing`
//! directly.
use super::*;
impl<'a> Parser<'a> {
/// Snapshot the state a speculative parse may move. See [`Rewind`].
pub(super) 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.
pub(super) 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);
}
pub(super) fn cur(&self) -> &Token {
&self.tokens[self.pos]
}
pub(super) fn nth(&self, n: usize) -> &Token {
let i = (self.pos + n).min(self.tokens.len() - 1);
&self.tokens[i]
}
pub(super) fn at_eof(&self) -> bool {
self.cur().kind == TokenKind::Eof
}
pub(super) 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.
pub(super) 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`].
pub(super) 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.
pub(super) 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(())
}
/// Given `self.tokens[i]` == an opening bracket, return the index just
/// past its matching close. Used for disambiguating lookahead only.
pub(super) 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
}
// ------------------------------------------------------------------
// 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.
pub(super) 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`.
pub(super) fn span_from(&self, start: u32) -> TextRange {
TextRange::new(start, self.last_end())
}
/// An expression node spanning from `start` through the last token
/// consumed.
pub(super) fn expr_at(&self, start: u32, kind: ExprKind) -> Expr {
Expr { kind, span: self.span_from(start) }
}
pub(super) 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.
pub(super) 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),
}
}
pub(super) fn expect_sym(&mut self, sym: &str) -> PResult<Token> {
if self.cur().is_sym(sym) {
Ok(self.bump())
} else {
self.error(format!("expected `{sym}`"))
}
}
pub(super) fn expect_kw(&mut self, kw: &str) -> PResult<Token> {
if self.cur().is_kw(kw) {
Ok(self.bump())
} else {
self.error(format!("expected `{kw}`"))
}
}
pub(super) 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.
pub(super) 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")
}
}
pub(super) fn eat_sym(&mut self, sym: &str) -> bool {
if self.cur().is_sym(sym) {
self.bump();
true
} else {
false
}
}
pub(super) 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.
pub(super) 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.
pub(super) 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.
pub(super) 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.
pub(super) 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`].
pub(super) 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.
pub(super) 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
}
pub(super) fn gap_before(&mut self, sym: &str) -> Vec<Comment> {
if self.cur().is_sym(sym) {
self.take_gap()
} else {
Vec::new()
}
}
/// Comments sitting right before a closing keyword (`end`, `endmodule`,
/// ...) — they belong inside the enclosing construct.
pub(super) 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
}
/// 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.
pub(super) 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.
pub(super) 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.
pub(super) fn take_trailing_here(&mut self) -> Vec<Comment> {
match self.tokens[self.pos].trailing.take() {
Some(comment) => vec![comment],
None => Vec::new(),
}
}
/// Consume the current token as verbatim text, keeping the column it
/// started in.
pub(super) fn take_raw_text(&mut self) -> RawText {
let col = self.cur().col;
let span = self.cur().span;
RawText { text: self.bump().text, col, span }
}
}
+470
View File
@@ -0,0 +1,470 @@
//! Data types and the declarations that use them.
//!
//! [`Parser::parse_opt_data_type`] is the one type grammar every position
//! shares (ports, parameters, declarators, casts, function returns); around
//! it stand the declarators, `parameter`/`localparam`, `typedef`, `enum` and
//! `struct`/`union` bodies, and the lookaheads that decide whether a name
//! at the cursor begins a declaration at all.
use super::item::MEMBER_QUALIFIERS;
use super::*;
impl<'a> Parser<'a> {
/// Parse a possibly-implicit data type. Stops before the declarator name.
pub(super) fn parse_opt_data_type(&mut self) -> PResult<DataType> {
let mut ty = DataType::default();
// `property p(sequence a, property b);` — inside a property's or a
// sequence's formal list, and nowhere else, the two keywords name a
// formal's *type* (IEEE 1800 §16.8). `untyped` needs no case: it is
// an ordinary identifier and already reads as a user-defined type.
if self.sva_formals && (self.cur().is_kw("sequence") || self.cur().is_kw("property")) {
ty.name = self.bump().text;
return Ok(ty);
}
// `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();
let segment = self.expect_ident()?;
Self::push_scope_segment(&mut name, &segment);
}
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)
}
pub(super) fn parse_dims(&mut self) -> PResult<Vec<Dim>> {
let mut dims = Vec::new();
while self.cur().is_sym("[") {
let start = self.here();
// A dimension owns the same five slots a postfix `[ ]` segment
// does, and for the same reason: nothing else is written where a
// comment inside the brackets could attach.
let mut comments =
SegmentComments { before_open: self.take_gap(), ..Default::default() };
self.bump();
comments.after_open = self.take_gap();
let kind = if self.cur().is_sym("]") {
// `[]` — a dynamic array.
comments.before_close = std::mem::take(&mut comments.after_open);
self.bump();
dims.push(Dim {
kind: DimKind::Dynamic,
comments: Box::new(comments),
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()?;
comments.before_op = self.gap_before(":");
let b = if self.eat_sym(":") {
comments.after_op = self.take_gap();
Some(self.parse_expr()?)
} else {
None
};
DimKind::Range { a, b }
};
comments.before_close = self.gap_before("]");
self.expect_sym("]")?;
dims.push(Dim { kind, comments: Box::new(comments), span: self.span_from(start) });
}
Ok(dims)
}
pub(super) 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)))
}
/// True when the cursor opens a parameterized type's `#( ... )`.
pub(super) fn at_type_params(&self) -> bool {
self.cur().is_sym("#") && self.nth(1).is_sym("(")
}
/// The `#( ... )` of a parameterized type or class reference, verbatim.
pub(super) 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))
}
/// 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.
pub(super) 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)
}
// ------------------------------------------------------------------
// Declarations
// ------------------------------------------------------------------
pub(super) fn parse_param_decl(&mut self) -> PResult<ParamDecl> {
let kw = self.bump().text;
let after_kw = self.take_gap();
// `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, after_kw, is_type, ty, declarators })
}
/// Parse declarators up to (but not consuming) the terminating `;`.
pub(super) 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 (eq_comments, init) = if type_init {
self.parse_eq_default(|p| p.parse_type_expr())?
} else {
self.parse_eq_default(|p| p.parse_expr())?
};
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, eq_comments, init, span });
if !more {
break;
}
}
Ok(out)
}
pub(super) 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");
let text = self.bump().text;
qualifiers.push(Qualifier { text, after: self.take_gap() });
// `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") {
let text = self.bump().text;
qualifiers.push(Qualifier { text, after: self.take_gap() });
}
} 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.text == "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 })
}
pub(super) 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 })
}
pub(super) fn parse_typedef(&mut self) -> PResult<Typedef> {
self.expect_kw("typedef")?;
let after_kw = self.take_gap();
let kind = 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.
TypedefKind::ForwardClass
} else if self.cur().is_kw("enum") {
TypedefKind::Enum(self.parse_enum_type()?)
} else if self.cur().is_kw("struct") || self.cur().is_kw("union") {
TypedefKind::Struct(self.parse_struct_type()?)
} else {
TypedefKind::Alias(self.parse_opt_data_type()?)
};
let before_name = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked =
if matches!(kind, TypedefKind::ForwardClass) { Vec::new() } else { self.parse_dims()? };
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
Ok(Typedef { after_kw, before_name, name, name_span, unpacked, before_semi, kind })
}
/// `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")?;
let after_kw = self.take_gap();
// 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()?) };
let before_open = self.take_before_open("{");
self.expect_sym("{")?;
let (members, directives) = self.parse_enum_members(false)?;
let dangling = self.take_dangling();
self.expect_sym("}")?;
Ok(EnumType { after_kw, base, before_open, 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`).
pub(super) 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 mut eq_comments = BinaryComments::default();
let value = if self.cur().is_sym("=") {
eq_comments.before = self.take_gap();
self.bump();
eq_comments.after = self.take_gap();
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,
eq_comments: Box::new(eq_comments),
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 mut header_comments =
StructHeaderComments { after_kw: self.take_gap(), ..Default::default() };
// `union tagged [packed] { ... }` (IEEE 1800 §7.3.2): the discriminated
// union. `tagged` is matched by text rather than reserved, for the
// reason [`word_at`] gives, and only the *flag* is modelled — the
// `tagged Valid 5` expression and `case (x) matches` are a pattern
// grammar of their own and are still a clean parse error.
let tagged = word_at(self.cur(), "tagged");
if tagged {
self.bump();
header_comments.after_tagged = self.take_gap();
}
let packed = self.eat_kw("packed");
if packed {
header_comments.after_packed = self.take_gap();
}
let signing = if self.cur().is_kw("signed") || self.cur().is_kw("unsigned") {
let word = self.bump().text;
header_comments.after_signing = self.take_gap();
Some(word)
} 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") {
let text = self.bump().text;
qualifiers.push(Qualifier { text, after: self.take_gap() });
}
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,
header_comments: Box::new(header_comments),
tagged,
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();
let segment = self.expect_ident()?;
Self::push_scope_segment(&mut name, &segment);
}
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)
}
}
+410
View File
@@ -0,0 +1,410 @@
//! Compiler directives and what they do to a token stream that is not a
//! tree: `` `ifdef `` region tracking, the directives a list keeps between
//! its elements, macro calls and macro items, and fragment mode — a file
//! that is the bare middle of some larger construct's body.
//!
//! The conditional-directive *split* recovery, which fires when an
//! `` `ifdef `` region cuts a construct in two, is a recovery and lives in
//! [`super::split`].
use super::*;
/// 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)
}
/// [`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.
pub(super) fn opens_conditional(t: &Token) -> bool {
matches!(directive_word(t), "ifdef" | "ifndef")
}
/// `` `else `` / `` `elsif ``: starts the next arm of the region already open.
pub(super) fn continues_conditional(t: &Token) -> bool {
matches!(directive_word(t), "else" | "elsif")
}
/// `` `endif ``: closes the region already open.
pub(super) fn closes_conditional(t: &Token) -> bool {
directive_word(t) == "endif"
}
/// What [`Parser::take_list_directives`] found between two list elements.
#[derive(Default)]
pub(super) struct Harvested {
/// At least one directive stood here.
pub(super) any: bool,
/// One of them carried the `,` that separates the surrounding elements,
/// so the list continues even though the previous element wrote no comma.
pub(super) carried_comma: bool,
}
/// 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.
pub(super) 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.
pub(super) 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
}
impl<'a> Parser<'a> {
/// The token index of the `close` matching the bracket just consumed —
/// but **only** when a conditional-compilation directive stands somewhere
/// inside it. `None` for every ordinary expression, which is nearly all
/// of them, and for a region that never closes.
///
/// This is what parts `` .dio_pad_io({ IOR9, `ifdef ANALOGSIM '0, `else
/// CC2, `endif POR_N }) `` (opentitan
/// `hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv:604`) from an
/// expression: lucisv never evaluates a `` `ifdef `` condition, so the
/// region has no one value to model. Before this round the whole *item*
/// became opaque bytes through [`Parser::split_conditional_item`], which
/// cost the instantiation its edge, its lens and its port references;
/// now only the one connection's value does.
///
/// Only the given bracket pair is counted, exactly as
/// [`Parser::scan_matching`] counts: a directive's own text is one
/// `TokenKind::Directive` token and can hold no stray bracket, and a
/// string literal is a token too.
pub(super) fn conditional_region_end(&self, close: &str) -> Option<usize> {
let mut depth = 1usize;
let mut conditional = false;
for (i, t) in self.tokens.iter().enumerate().skip(self.pos) {
if t.kind == TokenKind::Eof {
return None;
}
if t.is_sym("(") {
depth += 1;
} else if t.is_sym(close) {
depth -= 1;
if depth == 0 {
return conditional.then_some(i);
}
} else if opens_conditional(t) || continues_conditional(t) || closes_conditional(t) {
conditional = true;
}
}
None
}
/// 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.
pub(super) 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
}
/// 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.
pub(super) 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.
pub(super) 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 `;`.
pub(super) 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 })
}
/// 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,
prop_seq_decls: self.prop_seq_decls,
prop_seq_fallbacks: self.prop_seq_fallbacks,
assertions: self.assertions,
assertion_fallbacks: self.assertion_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)
}
}
+505
View File
@@ -0,0 +1,505 @@
//! The operator grammar: precedence climbing from implication down through
//! ternary, binary, unary and postfix. The leaves — literals, names, casts,
//! concatenations, patterns — are [`super::primary`].
use super::*;
impl<'a> Parser<'a> {
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.
pub(super) 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;
}
// `|->` lexes as `|` + `->` and is the SVA implication operator, never
// a bitwise or: `->` starts no expression, so `a | ->b` cannot be
// written. Said here rather than behind an SVA flag because it is
// true everywhere. Without it every `a |-> b` in the language reaches
// this table, takes the `|`, and fails on the `->`.
if t.is_sym("|") && self.nth(1).is_sym("->") && self.adjacent(2) {
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") {
// The word is an operator like any other, and keeps the
// comments written on either side of it the same way.
let before = self.take_around(mark);
self.bump();
let after = self.take_around(mark);
let comments = Box::new(BinaryComments { before, after });
// `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, comments },
);
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.parse_value_range()?
} 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, comments });
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.
pub(super) 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 comments = self.take_gap();
let expr = self.parse_unary()?;
return Ok(self.expr_at(
start,
ExprKind::Unary { op, comments: Box::new(comments), 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 or consecutive
/// repetition — `[* 3]`, `[-> 2]`, `[= 1]`, `[+]` (IEEE 1800 §19.5.1.2,
/// §16.9.2) — rather than an index or a part select.
///
/// No index expression can start with `*`, `->` or `=`, and none *is* the
/// single token `+`, 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 `*`.
pub(super) fn at_repeat_bracket(&self) -> bool {
if !self.cur().is_sym("[") {
return false;
}
let next = self.nth(1);
if next.kind != TokenKind::Symbol {
return false;
}
matches!(next.text.as_str(), "*" | "->" | "=")
|| (next.text == "+" && self.nth(2).is_sym("]"))
}
/// Postfix segments are parsed by a loop, but each one wraps the
/// expression so far in another AST layer, so they are bounded by
/// [`MAX_CHAIN_LENGTH`]; the links are released when the chain ends.
pub(super) fn parse_postfix(&mut self) -> PResult<Expr> {
let outer_links = self.links;
let out = self.parse_postfix_inner();
self.links = outer_links;
out
}
/// One `.name`, `::name`, `[i]` or `[m:l]` segment wrapping `base`, with
/// the comments written in each of its fixed slots.
///
/// The cursor is on the segment's opening token and `start` is where the
/// whole expression began — each segment wraps what came before it, so
/// every node in the chain starts at the same offset. This is the single
/// owner of the three-branch loop `parse_postfix_inner`,
/// [`Parser::parse_foreach_target_inner`] and
/// [`Parser::parse_bare_event_name`] each used to write out by hand, and
/// each used to lose the same comments in.
pub(super) fn parse_postfix_segment(&mut self, start: u32, base: Expr) -> PResult<Expr> {
let mut comments = SegmentComments { before_open: self.take_gap(), ..Default::default() };
let base = Box::new(base);
if self.cur().is_sym(".") || self.cur().is_sym("::") {
let scoped = self.cur().is_sym("::");
self.bump();
comments.after_open = self.take_gap();
let name = self.expect_ident()?;
let comments = Box::new(comments);
let kind = if scoped {
ExprKind::Scope { base, name, comments }
} else {
ExprKind::Member { base, name, comments }
};
return Ok(self.expr_at(start, kind));
}
self.expect_sym("[")?;
comments.after_open = self.take_gap();
let a = self.parse_expr()?;
let t = self.cur();
if t.is_sym(":") || t.is_sym("+:") || t.is_sym("-:") {
comments.before_op = self.take_gap();
let op = self.bump().text;
comments.after_op = self.take_gap();
let b = self.parse_expr()?;
comments.before_close = self.gap_before("]");
self.expect_sym("]")?;
return Ok(self.expr_at(
start,
ExprKind::Range {
base,
op,
msb: Box::new(a),
lsb: Box::new(b),
comments: Box::new(comments),
},
));
}
comments.before_close = self.gap_before("]");
self.expect_sym("]")?;
Ok(self.expr_at(
start,
ExprKind::Index { base, index: Box::new(a), comments: Box::new(comments) },
))
}
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(".") || t.is_sym("::") || t.is_sym("[") {
expr = self.parse_postfix_segment(start, expr)?;
} 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");
}
let is_pattern = t.is_sym("'{");
let mut comments =
CastComments { before_tick: self.take_gap(), ..Default::default() };
if is_pattern {
let pattern_start = self.here();
let inner = self.parse_assign_pattern(pattern_start)?;
expr = self.expr_at(
start,
ExprKind::Cast {
ty: Box::new(expr),
comments: Box::new(comments),
expr: Box::new(inner),
pattern: true,
},
);
} else {
self.bump(); // '
comments.after_tick = self.take_gap();
self.bump(); // (
comments.after_open = self.take_gap();
let inner = self.parse_expr()?;
comments.before_close = self.gap_before(")");
self.expect_sym(")")?;
expr = self.expr_at(
start,
ExprKind::Cast {
ty: Box::new(expr),
comments: Box::new(comments),
expr: Box::new(inner),
pattern: false,
},
);
}
} else {
// `++` / `--`, the only remaining segment kind.
let comments = self.take_gap();
let op = self.bump().text;
expr = self.expr_at(
start,
ExprKind::Postfix { expr: Box::new(expr), op, comments: Box::new(comments) },
);
}
}
Ok(expr)
}
}
+593
View File
@@ -0,0 +1,593 @@
//! The items that instantiate or drive: continuous assignments, module and
//! gate instantiations with their parameter overrides and connections, and
//! `bind` directives. Drive strengths and delay values live here because
//! these are the only items that write them.
use super::*;
/// 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",
];
/// 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())
}
impl<'a> Parser<'a> {
pub(super) 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 mark = self.pending_trailing.len();
let lhs = self.parse_unary()?;
// Whatever was written on either side of the `=` stays on its own
// side of it, as a procedural assignment's does.
let op_comments = self.take_around(mark);
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, op_comments, 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`].
pub(super) 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, each segment possibly carrying one `[…]` selector), 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 — a `bind [3:0] x;` declaration
/// is a *dimension on the first name*, which is why the scan only steps
/// over a `[…]` that has a `.` or the instantiation after it.
pub(super) 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;
loop {
// `top.gen[0].u_core` (IEEE 1800 §23.11's bind_target_instance):
// binding SVA into a generate array is the shape formal setups
// write. One selector per segment; anything more is not a bind
// this parser reads, and stays the clean error it always was.
if self.tokens.get(p).is_some_and(|t| t.is_sym("[")) {
let after = self.scan_matching(p, "[", "]");
if after == p {
return false;
}
p = after;
}
if 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;
continue;
}
break;
}
self.tokens.get(p).is_some_and(|t| t.is_sym(":") || t.kind == TokenKind::Ident)
}
/// `bind <target> [: <inst>, ...] <module> [#(...)] <name> (...);`
pub(super) 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 = vec![self.parse_path_segment()?];
while self.cur().is_sym(".") {
self.bump();
target.push(self.parse_path_segment()?);
}
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();
let segment = self.expect_ident()?;
Self::push_path_segment(&mut text, &segment);
}
Ok(Name { text, span: self.span_from(start) })
}
/// One segment of a `bind` target path: a name and the one `[…]`
/// selector it may carry.
fn parse_path_segment(&mut self) -> PResult<PathSegment> {
let Name { text: name, span } = self.expect_name()?;
let mut index = None;
if self.eat_sym("[") {
index = Some(self.parse_expr()?);
self.expect_sym("]")?;
}
Ok(PathSegment { name, span, index })
}
pub(super) 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();
let segment = self.expect_ident()?;
Self::push_scope_segment(&mut module, &segment);
}
let module_span = self.span_from(module_start);
let param_comments = self.take_before_open("#");
let mut params = None;
let mut after_hash = Vec::new();
let mut param_directives = Vec::new();
if self.cur().is_sym("#") {
self.bump();
after_hash = self.take_gap();
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;
}
}
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
Ok(Instantiation {
module,
module_span,
param_comments,
after_hash,
params,
param_directives,
instances,
before_semi,
})
}
/// 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.
pub(super) 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.
pub(super) 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 after_dot = self.take_gap();
let star = self.cur().span;
if self.eat_sym("*") {
let span = self.span_from(start);
return Ok(Connection {
meta,
after_dot,
name: "*".to_string(),
name_span: star,
before_open: Vec::new(),
after_open: Vec::new(),
expr: None,
close_comments: Vec::new(),
comma: false,
span,
});
}
let Name { text: name, span: name_span } = self.expect_name()?;
let before_open = self.take_before_open("(");
let mark = self.pending_trailing.len();
let paren_start = self.here();
let mut close_comments = Vec::new();
let mut after_open = 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 {
after_open = self.take_gap();
let value_mark = self.pending_trailing.len();
let e = match self.conditional_region_end(")") {
Some(end_pos) => self.parse_verbatim_expr(end_pos),
None => 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,
after_dot,
name,
name_span,
before_open,
after_open,
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,
after_dot: Vec::new(),
name: String::new(),
name_span: TextRange::empty(span.start),
before_open: Vec::new(),
after_open: Vec::new(),
expr: Some(e),
close_comments: Vec::new(),
comma: false,
span,
})
}
}
/// Consume the tokens up to `end_pos` as one verbatim expression.
///
/// [`Parser::open_conds`] is deliberately left alone: it counts *item*
/// scope only, and a construct that walks its body through
/// [`Parser::bump`] inherits "does not count" by doing nothing — see
/// [`Parser::note_item_conditional`].
fn parse_verbatim_expr(&mut self, end_pos: usize) -> Expr {
let start = self.here();
let col = self.cur().col;
while self.pos < end_pos && !self.at_eof() {
self.bump();
}
let raw = self.verbatim_since(start, col);
self.expr_at(start, ExprKind::Verbatim(raw))
}
pub(super) 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 })
}
}
+726
View File
@@ -0,0 +1,726 @@
//! From the file down to one item.
//!
//! The top-level loop ([`Parser::parse_source_file`]), the item loop every
//! body shares ([`Parser::parse_item`]) and the dispatch from a keyword to
//! the grammar that parses it ([`Parser::parse_keyword_item`]); plus the
//! items that are small enough to live beside the dispatch — packages,
//! imports and exports, DPI, generate regions — and the member-qualifier
//! prefix (`virtual`, `local`, `rand`, …) an item may start with.
use super::directive::{fragment_file, is_prelude};
use super::*;
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 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.
pub(super) const MEMBER_QUALIFIERS: &[&str] = &[
"virtual",
"pure",
"extern",
"local",
"protected",
"rand",
"randc",
"static",
"automatic",
"const",
"var",
];
impl<'a> Parser<'a> {
pub(super) 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,
prop_seq_decls: self.prop_seq_decls,
prop_seq_fallbacks: self.prop_seq_fallbacks,
assertions: self.assertions,
assertion_fallbacks: self.assertion_fallbacks,
fragment: None,
})
}
/// Items nest through generate blocks and package bodies. Gated.
pub(super) 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_assertion_item(),
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"),
}
}
/// The item that a keyword at the cursor begins.
///
/// A dispatch table over the item keywords: one arm per keyword, each
/// arm a call into the grammar file that owns the construct. It stays
/// one function on purpose, for the same reason
/// [`Parser::parse_keyword_stmt`] does.
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): its body is a subset of a class body (pure virtual
// method prototypes, parameters, typedefs) and it closes with
// `endclass`, so it *is* a [`ClassDecl`] — the word `interface`
// rides along in [`ClassDecl::prefix`] beside `virtual`, which is
// where every keyword written in front of `class` already lives.
"interface" if !self.nth(1).is_kw("class") => {
self.parse_module("endinterface").map(ItemKind::Module)
}
"interface" => self.parse_class().map(ItemKind::Class),
// 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_item(),
"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(|g| ItemKind::GenFor(Box::new(g))),
"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_assertion_item()
}
"property" | "sequence" => self.parse_prop_seq_decl(),
// Vendor and formal collateral, each one an opaque leaf. The
// bodies are grammars of their own — a specify path with its
// `=>`/`*>` connections, a UDP truth table, a checker's assertion
// vocabulary, a config's `design`/`instance`/`liblist` clauses —
// that lucisv models none of, and there is no layout convention
// worth inventing for any of them, so the whole block is copied
// out of the source by span the way a `property` declaration is.
// See `docs/features/vendor-formal-grammar/README.md`.
"specify" => self.parse_opaque_block("endspecify").map(ItemKind::Verbatim),
"primitive" => self.parse_opaque_block("endprimitive").map(ItemKind::Verbatim),
"checker" => self.parse_opaque_block("endchecker").map(ItemKind::Verbatim),
"config" => self.parse_opaque_block("endconfig").map(ItemKind::Verbatim),
// A `table ... endtable` only ever stands inside a `primitive`,
// whose scan already swallows it; this arm is what a stray one —
// or a UDP whose `primitive` line is behind an `` `ifdef `` — gets
// instead of an unsupported-construct error.
"table" => self.parse_opaque_block("endtable").map(ItemKind::Verbatim),
"library" => self.parse_opaque_line().map(ItemKind::Verbatim),
"specparam" => self.parse_specparam(),
"alias" => self.parse_alias(),
// 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")
}
/// 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.
pub(super) fn take_member_prefix(&mut self) -> Vec<Qualifier> {
let mut out = Vec::new();
while self.cur().kind == TokenKind::Keyword
&& MEMBER_QUALIFIERS.contains(&self.cur().text.as_str())
{
let text = self.bump().text;
// `local /*c*/ static` — the gap after each keyword is that
// keyword's, so two comments in one run stay in their own gaps.
out.push(Qualifier { text, after: self.take_gap() });
}
out
}
fn parse_package(&mut self) -> PResult<ItemKind> {
let kw = self.bump().text;
let before_name = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
let before_semi = self.gap_before(";");
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_comments, end_name) = self.parse_label_with()?;
let (end_label, end_label_span) = split_label(end_name);
Ok(ItemKind::Package {
kw,
before_name,
name,
name_span,
before_semi,
items,
dangling,
end_label_comments,
end_label,
end_label_span,
})
}
pub(super) 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)
}
// ------------------------------------------------------------------
// 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")?;
let mut comments = ForComments { after_kw: self.take_gap(), ..Default::default() };
self.expect_sym("(")?;
comments.after_open = self.take_gap();
let init_genvar = self.eat_kw("genvar");
let after_genvar = if init_genvar { self.take_gap() } else { Vec::new() };
let lhs = self.parse_unary()?;
let mut op_comments = BinaryComments { before: self.gap_before("="), after: Vec::new() };
self.expect_sym("=")?;
op_comments.after = self.take_gap();
let rhs = self.parse_expr()?;
let init =
SimpleAssign { lhs, op: "=".to_string(), op_comments: Box::new(op_comments), rhs };
comments.before_first_semi = self.gap_before(";");
self.expect_sym(";")?;
comments.after_first_semi = self.take_gap();
let cond = self.parse_expr()?;
comments.before_second_semi = self.gap_before(";");
self.expect_sym(";")?;
comments.after_second_semi = self.take_gap();
let step = self.parse_for_step()?;
comments.before_close = self.gap_before(")");
self.expect_sym(")")?;
let body = self.parse_gen_block()?;
Ok(GenFor {
init,
init_genvar,
after_genvar,
cond,
step,
comments: Box::new(comments),
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 mut before_colon = Vec::new();
let labels = if self.eat_kw("default") {
before_colon = self.gap_before(":");
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, before_colon, 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") {
// The gap between whatever came before and the `begin` belongs to
// the block — nothing else was written where it could attach.
let before_kw = self.take_gap();
self.bump();
let before_colon = self.gap_before(":");
let mut after_colon = Vec::new();
let label_name = if self.eat_sym(":") {
after_colon = self.take_gap();
Some(self.expect_name()?)
} else {
None
};
let (label, label_span) = split_label(label_name);
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_comments, end_name) = self.parse_label_with()?;
let (end_label, end_label_span) = split_label(end_name);
Ok(GenBlock {
before_kw,
before_colon,
after_colon,
label,
label_span,
is_block: true,
items,
dangling,
end_label_comments,
end_label,
end_label_span,
span: self.span_from(start),
})
} else {
let item = self.item_or_recover()?;
let span = item.span;
Ok(GenBlock {
before_kw: Vec::new(),
before_colon: Vec::new(),
after_colon: Vec::new(),
label: None,
label_span: None,
end_label_comments: Box::default(),
is_block: false,
items: vec![item],
dangling: Vec::new(),
end_label: None,
end_label_span: None,
span,
})
}
}
}
@@ -0,0 +1,337 @@
//! The keyword → statement dispatch table.
//!
//! One `match` over every keyword a statement may begin with: each arm is
//! either the whole (short) grammar of that statement or a call into the
//! function in [`super::stmt`] that holds it. It is a table, not a set of
//! productions, which is why it stays one function; and it is half the
//! lines of the statement grammar, which is why it has a file of its own —
//! `stmt.rs` describes the statements, this file describes how a keyword
//! reaches one.
use super::stmt::ForeachTarget;
use super::*;
impl<'a> Parser<'a> {
/// The statement that a keyword at the cursor begins.
///
/// A dispatch table over the statement keywords: one arm per keyword,
/// each arm either the whole (short) grammar or a call to the function
/// that holds it. It stays one function on purpose — split by keyword
/// group it would be the same table read across several places.
pub(super) fn parse_keyword_stmt(&mut self) -> PResult<StmtKind> {
let kw = self.cur().text.clone();
match kw.as_str() {
"begin" => {
self.bump();
let (label_comments, label_name) = self.parse_label_with()?;
let (label, label_span) = split_label(label_name);
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_comments, end_name) = self.parse_label_with()?;
let (end_label, end_label_span) = split_label(end_name);
Ok(StmtKind::Block {
label_comments,
label,
label_span,
stmts,
dangling,
end_label_comments,
end_label,
end_label_span,
})
}
"fork" => {
self.bump();
let (label_comments, label_name) = self.parse_label_with()?;
let (label, label_span) = split_label(label_name);
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_comments, end_name) = self.parse_label_with()?;
let (end_label, end_label_span) = split_label(end_name);
Ok(StmtKind::ForkJoin {
label_comments,
label,
label_span,
join_kw,
stmts,
dangling,
end_label_comments,
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();
let mut comments = ForComments { after_kw: self.take_gap(), ..Default::default() };
self.expect_sym("(")?;
comments.after_open = self.take_gap();
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 before_name = self.take_gap();
let lhs = self.parse_unary()?;
let mut op_comments =
BinaryComments { before: self.gap_before("="), after: Vec::new() };
self.expect_sym("=")?;
op_comments.after = self.take_gap();
let rhs = self.parse_expr()?;
init.push(ForInit {
ty,
before_name,
assign: SimpleAssign {
lhs,
op: "=".to_string(),
op_comments: Box::new(op_comments),
rhs,
},
});
if !self.eat_sym(",") {
break;
}
}
}
comments.before_first_semi = self.gap_before(";");
self.expect_sym(";")?;
comments.after_first_semi = self.take_gap();
let cond = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) };
comments.before_second_semi = self.gap_before(";");
self.expect_sym(";")?;
comments.after_second_semi = self.take_gap();
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()?);
}
}
comments.before_close = self.gap_before(")");
self.expect_sym(")")?;
let body = Box::new(self.parse_stmt()?);
Ok(StmtKind::For { init, cond, step, comments: Box::new(comments), 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")?;
let mut comments =
HeaderComments { after_kw: self.take_before_open("("), ..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(")")?;
self.expect_stmt_semi()?;
Ok(StmtKind::DoWhile { body, cond, comments: Box::new(comments) })
}
"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();
let mut comments =
HeaderComments { after_kw: self.take_gap(), ..Default::default() };
self.expect_sym("(")?;
comments.after_open = self.take_gap();
let ForeachTarget { expr: target, vars, comments: var_comments } =
self.parse_foreach_target()?;
comments.before_close = self.gap_before(")");
self.expect_sym(")")?;
let body = Box::new(self.parse_stmt()?);
Ok(StmtKind::Foreach {
target,
vars,
var_comments,
comments: Box::new(comments),
body,
})
}
"randcase" => {
self.bump();
let (items, dangling) = self.parse_case_body()?;
Ok(StmtKind::RandCase { items, dangling })
}
"return" => {
self.bump();
let after_kw = self.take_gap();
let expr = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) };
self.expect_stmt_semi()?;
Ok(StmtKind::Return { after_kw, expr })
}
"break" => {
self.bump();
self.expect_stmt_semi()?;
Ok(StmtKind::Break)
}
"continue" => {
self.bump();
self.expect_stmt_semi()?;
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_stmt_semi()?;
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_stmt_semi()?;
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_stmt_semi()?;
return Ok(StmtKind::WaitFork);
}
self.expect_sym("(")?;
let cond = self.parse_expr()?;
self.expect_sym(")")?;
let stmt =
if self.eat_stmt_semi() { 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_stmt_semi() {
(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_stmt_semi()?;
Ok(StmtKind::ForceRelease { kw: "force".into(), lhs, rhs: Some(rhs) })
}
"release" | "deassign" => {
let kw = self.bump().text;
let lhs = self.parse_unary()?;
self.expect_stmt_semi()?;
Ok(StmtKind::ForceRelease { kw, lhs, rhs: None })
}
"parameter" | "localparam" => {
let d = self.parse_param_decl()?;
self.expect_stmt_semi()?;
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}`")),
}
}
}
+477
View File
@@ -0,0 +1,477 @@
//! 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`.
//!
//! Layout: this file holds the parser's state and entry points — [`Parser`]
//! and its budgets, `Rewind`, [`parse`] / [`parse_tolerant`] — and the few
//! grammar helpers every file shares (scoped names, labels). The grammar
//! itself is one `impl Parser` block per sibling file, cut by what a reader
//! would look for:
//!
//! | file | holds |
//! |---|---|
//! | `cursor` | the token cursor, spans, `expect`/`eat`, the comment plumbing |
//! | `recover` | tolerant-mode error recovery |
//! | `item` | the file and item loops, the keyword → item dispatch, packages, imports, DPI, generate |
//! | `module` | module/interface/program headers, ports, modports, clocking blocks |
//! | `decl` | data types, declarators, parameters, `typedef`/`enum`/`struct` |
//! | `tf` | `function`, `task` and `let` declarations |
//! | `instance` | continuous assigns, instantiations and connections, gates, `bind` |
//! | `stmt`, `keyword_stmt` | statements; the keyword → statement dispatch table |
//! | `expr`, `primary` | the operator grammar; its leaves and argument lists |
//! | `class`, `covergroup` | classes with their constraints; covergroups |
//! | `assertion`, `sva` | concurrent assertions and SVA declarations; the property grammar |
//! | `directive` | `` `ifdef `` tracking, list directives, macros, fragment mode |
//! | `split` | conditional-directive split recovery |
//! | `verbatim` | vendor/formal blocks kept as bytes, and the capture helpers |
//!
//! Tests live in `tests/`, one file per grammar file they exercise.
use crate::ast::*;
use crate::span::TextRange;
use crate::token::{Comment, Token, TokenKind};
mod assertion;
mod class;
mod covergroup;
mod cursor;
mod decl;
mod directive;
mod expr;
mod instance;
mod item;
mod keyword_stmt;
mod module;
mod primary;
mod recover;
mod split;
mod stmt;
mod sva;
mod tf;
mod verbatim;
pub(crate) use recover::error_file;
#[cfg(test)]
mod tests;
#[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 ASSIGN_OPS: &[&str] =
&["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<<=", ">>>="];
/// 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;
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,
/// `property`/`sequence` declarations and concurrent assertions parsed
/// into real nodes, and the ones that did not fit the SVA grammar and
/// were captured verbatim instead; see [`SourceFile::assertions`].
prop_seq_decls: u32,
prop_seq_fallbacks: u32,
assertions: u32,
assertion_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,
/// While a `property` / `sequence` formal list is being read, `sequence`
/// and `property` are *type* spellings (IEEE 1800 §16.8's
/// `property_formal_type`), not the keywords that open a declaration.
/// Set and cleared around that one list, and never left set on an error
/// path. The sibling of [`Parser::no_with`], for the same reason.
sva_formals: bool,
/// The comments written in the gap before the `;` that ends the statement
/// currently being parsed — `x = 1 /* inclusive */ ;`.
///
/// The `;` is consumed in a dozen places (some of which read it to decide
/// the statement's *shape*), so the gap is handed up here instead of
/// through a dozen return types, and [`Parser::parse_stmt_inner`] moves it
/// onto [`Stmt::before_semi`] — the single owner of that gap, the way
/// `ConstraintItem::before_semi` is of a constraint item's. Cleared before
/// every statement kind is parsed, so nothing can leak from one statement
/// to the next.
semi_comments: Vec<Comment>,
}
/// 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)
}
}
}
/// 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
}
/// 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> {
pub(super) 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,
prop_seq_decls: 0,
prop_seq_fallbacks: 0,
assertions: 0,
assertion_fallbacks: 0,
no_with: false,
sva_formals: false,
semi_comments: 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.
pub(super) fn parse_label(&mut self) -> PResult<Option<Name>> {
Ok(self.parse_label_with()?.1)
}
/// The same, plus the comments written in the label's two gaps
/// (`endgroup /*a*/ : /*b*/ cg`). Every construct that keeps a label
/// keeps these beside it, so neither comment drifts across the `:`.
pub(super) fn parse_label_with(&mut self) -> PResult<(Box<LabelComments>, Option<Name>)> {
let before_colon = self.gap_before(":");
if !self.eat_sym(":") {
return Ok((Box::default(), None));
}
let after_colon = self.take_gap();
let name = self.expect_name()?;
Ok((Box::new(LabelComments { before_colon, after_colon }), Some(name)))
}
/// 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.
pub(super) fn parse_method_name(&mut self) -> PResult<(Vec<ScopeSeg>, Name)> {
let mut name = self.expect_name()?;
let mut scope: Vec<ScopeSeg> = Vec::new();
while self.cur().is_sym("::") {
let before_sep = self.take_gap();
self.bump();
let after_sep = self.take_gap();
let next = self.expect_name()?;
scope.push(ScopeSeg { name, before_sep, after_sep });
name = next;
}
Ok((scope, name))
}
/// [`Parser::push_scope_segment`]'s `.` twin, for the hierarchical paths
/// a `bind`'s `: instance, list` glues into one name. Same rule, same
/// reason: whitespace is an escaped identifier's only terminator, so
/// `\my-inst .u_core` must not come back as `\my-inst.u_core`.
pub(super) fn push_path_segment(joined: &mut String, segment: &str) {
if joined.rsplit(char::is_whitespace).next().is_some_and(|s| s.contains('\\')) {
joined.push(' ');
}
joined.push('.');
joined.push_str(segment);
}
/// Append `::` plus the next segment to a joined scoped name, keeping the
/// whitespace an escaped segment needs to terminate.
///
/// `\my-pkg ::\state-t` is three tokens; joined tightly it reprints as
/// `\my-pkg::\state-t`, which is one — the corruption the safety net had
/// to catch before this round (`docs/topo.md` §2.9-21). Whitespace is an
/// escaped identifier's only terminator, so it is part of the name as
/// written and belongs in the joined text.
pub(super) fn push_scope_segment(joined: &mut String, segment: &str) {
if joined.rsplit(char::is_whitespace).next().is_some_and(|s| s.contains('\\')) {
joined.push(' ');
}
joined.push_str("::");
joined.push_str(segment);
}
/// A `pkg::name` chain, returned as the joined text plus the
/// range covering the whole chain.
pub(super) 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();
let segment = self.expect_ident()?;
Self::push_scope_segment(&mut name, &segment);
}
Ok((name, self.span_from(start)))
}
}
+542
View File
@@ -0,0 +1,542 @@
//! The module, interface and program header, and the body constructs that
//! belong only to them: parameter ports, ports (ANSI and non-ANSI),
//! modports and clocking blocks.
use super::*;
/// The three pieces a `#( parameter ... )` port list yields, so module and
/// class headers can share one parse.
#[derive(Default)]
pub(super) struct ParamPortList {
/// `None` when no `#( ... )` was written at all.
pub(super) ports: Option<Vec<ParamPort>>,
pub(super) directives: Vec<ListDirective>,
pub(super) dangling: Vec<Comment>,
/// Comments written between the `#` and the `(`.
pub(super) after_hash: Vec<Comment>,
}
impl<'a> Parser<'a> {
/// 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.
pub(super) fn parse_module(&mut self, end_kw: &str) -> PResult<Module> {
let kw = self.bump().text;
let before_name = self.take_gap();
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,
after_hash: param_after_hash,
} = self.parse_param_port_list()?;
let port_comments = self.take_before_open("(");
let (ports, port_dangling, port_directives) = self.parse_port_list()?;
let before_semi = self.gap_before(";");
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_comments, end_name) = self.parse_label_with()?;
let (end_label, end_label_span) = split_label(end_name);
Ok(Module {
kw,
before_name,
name,
param_after_hash,
name_span,
imports,
param_comments,
param_ports,
param_directives,
param_dangling,
port_comments,
ports,
port_directives,
port_dangling,
before_semi,
items,
dangling,
end_label_comments,
end_label,
end_label_span,
})
}
/// `modport a (input x, output y), b (...);` (IEEE 1800 §25.5).
pub(super) 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.
pub(super) 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_comments: Box::default(),
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_comments, end_name) = self.parse_label_with()?;
let (end_label, end_label_span) = split_label(end_name);
Ok(ClockingDecl {
is_default,
name,
event,
items,
dangling,
end_label_comments,
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.
pub(super) fn parse_param_port_list(&mut self) -> PResult<ParamPortList> {
let mut out = ParamPortList::default();
if !self.cur().is_sym("#") {
return Ok(out);
}
self.bump();
out.after_hash = self.take_gap();
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)
}
/// An optional `= value`, with the comments written on either side of the
/// `=` (`W /*a*/ = /*b*/ 8`). The value is read by `parse`, since a
/// `type` parameter's default is a type and everything else's is an
/// expression.
pub(super) fn parse_eq_default(
&mut self,
parse: fn(&mut Self) -> PResult<Expr>,
) -> PResult<(Box<BinaryComments>, Option<Expr>)> {
if !self.cur().is_sym("=") {
return Ok((Box::default(), None));
}
let before = self.take_gap();
self.bump();
let after = self.take_gap();
let value = parse(self)?;
Ok((Box::new(BinaryComments { before, after }), Some(value)))
}
fn parse_param_port(&mut self) -> PResult<ParamPort> {
let start = self.here();
let mut meta = self.take_meta();
let mut after_kw = Vec::new();
let kw = if self.cur().is_kw("parameter") || self.cur().is_kw("localparam") {
let word = self.bump().text;
after_kw = self.take_gap();
Some(word)
} else {
None
};
if self.eat_kw("type") {
let before_name = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
let (eq_comments, default) = self.parse_eq_default(|p| p.parse_type_expr())?;
let span = self.span_from(start);
meta.trailing = self.take_trailing();
return Ok(ParamPort {
meta,
kw,
after_kw,
ty: DataType::default(),
is_type: true,
before_name,
name,
name_span,
unpacked: Vec::new(),
eq_comments,
default,
comma: false,
span,
});
}
let ty = self.parse_opt_data_type()?;
let before_name = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?;
let (eq_comments, default) = self.parse_eq_default(|p| p.parse_expr())?;
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(ParamPort {
meta,
kw,
after_kw,
ty,
is_type: false,
before_name,
name,
name_span,
unpacked,
eq_comments,
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 — but only when the header did not write a `;` right
// after the `)`. `module m (input a) /*c*/ ;` writes its comment
// in the *header's* gap, and printing it back inside the parens
// moves it across the `)`.
if !self.cur().is_sym(";") {
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 after_dir = if dir.is_some() { self.take_gap() } else { Vec::new() };
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 before_name = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?;
let (eq_comments, default) = self.parse_eq_default(|p| p.parse_expr())?;
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(AnsiPort {
meta,
dir,
after_dir,
net,
ty,
before_name,
name,
name_span,
unpacked,
eq_comments,
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`.
pub(super) 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.
pub(super) 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() })
}
}
+467
View File
@@ -0,0 +1,467 @@
//! The leaves of an expression — [`Parser::parse_primary`] and the forms
//! it branches to (casts, assignment patterns, streaming concatenations,
//! shallow copies) — and the element and argument lists that primaries,
//! calls and instantiations all take.
use super::*;
impl<'a> Parser<'a> {
pub(super) 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));
let mut comments =
CastComments { before_tick: self.take_gap(), ..Default::default() };
self.bump(); // '
comments.after_tick = self.take_gap();
self.bump(); // (
comments.after_open = self.take_gap();
let inner = self.parse_expr()?;
comments.before_close = self.gap_before(")");
self.expect_sym(")")?;
return Ok(self.expr_at(
start,
ExprKind::Cast {
ty: Box::new(ty),
comments: Box::new(comments),
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"),
}
}
/// 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.
pub(super) 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.
pub(super) 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
}
/// One element of a bracketed expression list, with the comments written
/// before it. The caller harvests the trailing comment after the comma.
pub(super) 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.
pub(super) 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.
pub(super) fn parse_named_arg(&mut self) -> PResult<Expr> {
let start = self.here();
self.bump(); // .
let after_dot = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
let before_open = self.take_before_open("(");
let mark = self.pending_trailing.len();
let paren_start = self.here();
self.expect_sym("(")?;
let mut after_open = Vec::new();
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 {
after_open = self.take_gap();
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),
comments: Box::new(ArgComments {
after_dot,
before_open,
after_open,
close: close_comments,
}),
},
))
}
/// `[lo:hi]` — a value range standing as a list element (a
/// `case ... inside` label, an `inside` set member). The cursor is on
/// the `[`.
///
/// The one place the `[a:b]` grammar is written, after this round: the
/// `inside` set used to inline a hand-copy of it and
/// [`Parser::parse_dims`] a second one, and each copy lost the comments
/// the others lost. See `docs/features/comment-slots/README.md`.
pub(super) fn parse_value_range(&mut self) -> PResult<Expr> {
let start = self.here();
let mut comments = SegmentComments { before_open: self.take_gap(), ..Default::default() };
self.bump(); // [
comments.after_open = self.take_gap();
let lo = self.parse_expr()?;
comments.before_op = self.gap_before(":");
self.expect_sym(":")?;
comments.after_op = self.take_gap();
let hi = self.parse_expr()?;
comments.before_close = self.gap_before("]");
self.expect_sym("]")?;
Ok(self.expr_at(
start,
ExprKind::ValueRange {
lo: Box::new(lo),
hi: Box::new(hi),
comments: Box::new(comments),
},
))
}
/// 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).
pub(super) 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()?);
}
}
/// In parameter connections a value may be a type (`.T(logic [7:0])`).
pub(super) 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()
}
}
+217
View File
@@ -0,0 +1,217 @@
//! Error recovery, reached only in tolerant mode.
//!
//! 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 or 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. See `docs/features/error-recovery/README.md`.
use super::*;
/// 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",
// The vendor/formal closers (`vendor-formal-grammar`, 2026-09-02). Each
// one closes a block the parser keeps as an opaque leaf, so recovery that
// runs past a broken item inside a module must stop before them for the
// same reason it stops before `endgenerate`.
"endspecify",
"endprimitive",
"endtable",
"endchecker",
"endconfig",
];
/// 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"];
/// 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,
prop_seq_decls: 0,
prop_seq_fallbacks: 0,
assertions: 0,
assertion_fallbacks: 0,
fragment: None,
}
}
impl<'a> Parser<'a> {
/// True when the cursor sits on a token recovery must not consume: it
/// closes, or opens, a construct an enclosing loop is responsible for.
pub(super) 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`.
pub(super) 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.
pub(super) 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.
pub(super) 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.
pub(super) 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).
pub(super) 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.
pub(super) 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.
pub(super) 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.
pub(super) 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),
before_semi: Vec::new(),
span,
})
}
other => other,
}
}
}
+471
View File
@@ -0,0 +1,471 @@
//! 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`.
use super::directive::{closes_conditional, continues_conditional, opens_conditional};
use super::*;
/// 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
}
impl<'a> Parser<'a> {
/// 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.
pub(super) 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`]).
pub(super) 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.
pub(super) 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.
pub(super) 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.
pub(super) 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
}
}
}
+494
View File
@@ -0,0 +1,494 @@
//! Statements.
//!
//! [`Parser::parse_stmt`] is the entry; [`Parser::parse_keyword_stmt`] is
//! the dispatch table from a keyword to its grammar, and the rest are the
//! statements with enough shape to deserve their own function: `if`,
//! `case`, `for`/`foreach`, assignments, and the sensitivity lists an
//! `always` or event control takes.
use super::*;
/// The three pieces a `foreach` header's `array[i, j]` yields: what is
/// iterated, the loop variables, and the comments written around their
/// bracket. Both callers — the statement and the constraint item — store all
/// three.
pub(super) struct ForeachTarget {
pub(super) expr: Expr,
pub(super) vars: Vec<ForeachVar>,
pub(super) comments: Box<SegmentComments>,
}
impl<'a> Parser<'a> {
/// Statements nest through blocks and every compound statement. Gated.
pub(super) 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() };
// Nothing may leak from the statement before this one into this
// statement's own `;` slot.
self.semi_comments.clear();
let kind = match self.parse_stmt_kind() {
Ok(kind) => kind,
Err(e) => self.split_conditional_stmt(&mark, e)?,
};
let before_semi = std::mem::take(&mut self.semi_comments);
debug_assert!(
before_semi.is_empty() || kind.takes_semi(),
"only a kind that wrote a `;` may own the gap in front of it"
);
let span = self.span_from(start);
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(Stmt { meta, kind, before_semi, 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 self.parse_assertion_stmt();
}
// `expect (a ##1 b) else $error;` — the one assertion whose keyword is
// not reserved, so what is inside the parentheses is what tells it
// from a task call. See [`Parser::at_expect_statement`].
if self.at_expect_statement() {
return self.parse_expect_stmt();
}
// 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 after_hash = self.take_gap();
let delay = self.parse_delay_value()?;
let stmt = if self.eat_stmt_semi() { None } else { Some(Box::new(self.parse_stmt()?)) };
return Ok(StmtKind::Timing {
control: TimingControl::Delay { after_hash, expr: delay },
stmt,
});
}
if t.is_sym("@") {
self.bump();
let sens = self.parse_sens_list()?;
let stmt = if self.eat_stmt_semi() { 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_stmt_semi()?;
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()
}
pub(super) fn parse_if_stmt(&mut self, qualifier: Option<String>) -> PResult<StmtKind> {
self.expect_kw("if")?;
let after_kw = self.take_before_open("(");
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, after_kw, cond, then, else_comments, els })
}
pub(super) fn parse_case_stmt(&mut self, qualifier: Option<String>) -> PResult<StmtKind> {
let kw = self.bump().text;
let after_kw = self.take_before_open("(");
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, after_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.
pub(super) 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 mut before_colon = Vec::new();
let labels = if self.eat_kw("default") {
// The `:` after `default` is optional (IEEE 1800 §12.5), so
// the gap only belongs to the item when one was written.
before_colon = self.gap_before(":");
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, before_colon, 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.
pub(super) fn parse_foreach_target(&mut self) -> PResult<ForeachTarget> {
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<ForeachTarget> {
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("[") {
// The last bracket group is the loop-variable list, not a
// segment of the target: it is the one whose `]` is followed
// by the header's `)`.
let after = self.scan_matching(self.pos, "[", "]");
if self.tokens.get(after).is_some_and(|t| t.is_sym(")")) {
break;
}
} else if !t.is_sym(".") && !t.is_sym("::") {
break;
}
expr = self.parse_postfix_segment(start, expr)?;
}
let mut comments = SegmentComments { before_open: self.take_gap(), ..Default::default() };
self.expect_sym("[")?;
comments.after_open = self.take_gap();
let mut vars = Vec::new();
if !self.cur().is_sym("]") {
vars.push(self.parse_foreach_var()?);
while self.cur().is_sym(",") {
if let Some(last) = vars.last_mut() {
last.after = self.take_gap();
}
self.bump();
vars.push(self.parse_foreach_var()?);
}
}
if let Some(last) = vars.last_mut() {
last.after = self.gap_before("]");
} else {
comments.before_close = self.gap_before("]");
}
self.expect_sym("]")?;
Ok(ForeachTarget { expr, vars, comments: Box::new(comments) })
}
/// 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<ForeachVar> {
let before = self.take_gap();
if self.cur().is_sym(",") || self.cur().is_sym("]") {
let here = self.here();
let name = Name { text: String::new(), span: self.span_from(here) };
return Ok(ForeachVar { name, before, after: Vec::new() });
}
let name = self.expect_name()?;
Ok(ForeachVar { name, before, after: Vec::new() })
}
pub(super) fn parse_for_step(&mut self) -> PResult<ForStep> {
let mark = self.pending_trailing.len();
let lhs = self.parse_unary()?;
let op = self.cur().text.clone();
if self.cur().kind == TokenKind::Symbol && (ASSIGN_OPS.contains(&op.as_str()) || op == "<=")
{
let before = self.take_around(mark);
self.bump();
let after = self.take_gap();
let rhs = self.parse_expr()?;
Ok(ForStep::Assign(SimpleAssign {
lhs,
op,
op_comments: Box::new(BinaryComments { before, after }),
rhs,
}))
} else {
Ok(ForStep::Expr(lhs))
}
}
pub(super) 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 {
after_hash: self.take_gap(),
expr: 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_stmt_semi()?;
Ok(StmtKind::Assign { lhs, op, op_comments, rhs_comments, timing, rhs })
} else {
self.expect_stmt_semi()?;
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 {
let dotted = self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident;
if !dotted && !self.cur().is_sym("[") {
return Ok(expr);
}
self.link()?;
expr = self.parse_postfix_segment(start, expr)?;
}
}
pub(super) fn parse_sens_list(&mut self) -> PResult<SensList> {
// The `@` is consumed by the caller, so the gap that ends here is the
// one written after it.
let after_at = self.take_gap();
if self.cur().is_sym("*") {
// `@*` without parens — the gap after the `@` is the `*`'s own
// `before` slot, which the formatter prints in the same place.
self.bump();
return Ok(SensList::Star { before: after_at, 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(|expr| SensList::Bare { expr, after_at });
}
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 = after_at;
before.append(&mut 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 mut after_edge = Vec::new();
let edge = {
let t = self.cur();
if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") {
let kw = self.bump().text;
// `@(posedge /*c*/ clk)` — the gap after the keyword is
// the item's, not the next node's.
after_edge = self.take_gap();
Some(kw)
} 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, after_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, after_at })
}
/// [`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.
/// Consume the `;` that ends a statement, recording the comments written
/// in front of it on [`Parser::semi_comments`] for
/// [`Parser::parse_stmt_inner`] to move onto the statement.
pub(super) fn expect_stmt_semi(&mut self) -> PResult<()> {
self.semi_comments = self.gap_before(";");
self.expect_sym(";")?;
Ok(())
}
/// The same for the sites that *read* the `;` to decide the statement's
/// shape (`#10;` versus `#10 x = 1;`). Takes nothing when the cursor is
/// not on a `;`, because [`Parser::gap_before`] does not.
pub(super) fn eat_stmt_semi(&mut self) -> bool {
let gap = self.gap_before(";");
if self.eat_sym(";") {
self.semi_comments = gap;
true
} else {
false
}
}
}
+737
View File
@@ -0,0 +1,737 @@
//! The SVA grammar (IEEE 1800-2017 §16).
//!
//! `sequence_expr` and `property_expr` as one precedence-climbing
//! extension of the expression parser: the leaves are ordinary `Expr`s,
//! and everything above them is the table in
//! `docs/features/sva-bodies/README.md`. Nothing here is reserved — every
//! operator word is matched by text, in SVA position only, through
//! `word_at`.
//!
//! Every entry point is speculative: `parse_assertion_item`,
//! `parse_assertion_stmt` and `parse_prop_seq_decl` take a `Rewind`
//! snapshot and, on any error, restore it and re-run the pre-round
//! verbatim capture character for character. There is no partial node.
use super::*;
/// The four `abort` property operators (IEEE 1800 §16.12.10). They share the
/// **loosest** row of Table 16-3 with the `always` family and with
/// `if`/`case`; see [`PREFIX_WORDS`]. Matched by text in SVA position only,
/// for the reason [`word_at`] gives.
const ABORT_WORDS: &[&str] = &["accept_on", "reject_on", "sync_accept_on", "sync_reject_on"];
/// The prefix property operators on the loosest row of IEEE 1800-2017
/// Table 16-3 — `always`, `s_always`, `eventually`, `s_eventually`, the four
/// [`ABORT_WORDS`], and `if`/`case` — minus `always`, which is already a lexer
/// keyword and is asked for with `is_kw`.
///
/// Being on that row with `if`/`case` is what makes them **position
/// independent**: `p1 and always p2` is legal SVA, so `parse_prop_prefix`
/// takes them wherever a property expression may stand rather than only where
/// something that loose may start. `nexttime` and `s_nexttime` are *not* here
/// — Table 16-3 puts them on `not`'s row ([`NEXTTIME_WORDS`]).
const PREFIX_WORDS: &[&str] = &["s_always", "eventually", "s_eventually"];
/// `nexttime` and `s_nexttime`, which IEEE 1800-2017 Table 16-3 groups with
/// `not` rather than with the `always` family: `nexttime p1 and p2` is
/// `(nexttime p1) and p2`. Unlike `not` they may carry a `[n]` count
/// (§16.12.2).
const NEXTTIME_WORDS: &[&str] = &["nexttime", "s_nexttime"];
impl<'a> Parser<'a> {
/// The precedence of `##`, the highest binary operator of the grammar.
/// See the table in `docs/features/sva-bodies/README.md`.
const DELAY_PREC: u8 = 11;
/// The precedence of `not`, which IEEE 1800-2017 Table 16-3 shares with
/// `nexttime` and `s_nexttime`.
///
/// The loosest row — `always`, `eventually`, the `accept_on` family and
/// `if`/`case` — needs no constant: nothing binds looser, so those are
/// read at any `min_prec` and take their operand at 0.
const NOT_PREC: u8 = 7;
/// True when the `n` tokens starting at the cursor touch, with nothing —
/// not whitespace, not a comment — written between them.
///
/// `|->` lexes as `|` + `->` and `#-#` as `#` + `-` + `#`; the lexer's
/// operator table is deliberately not extended for either. Demanding
/// adjacency is what keeps `a | ~b` and `a #-# b` apart, and is the rule
/// `constraint-bodies` already applies to `:=`.
pub(super) fn adjacent(&self, n: usize) -> bool {
(1..n).all(|i| self.nth(i - 1).span.end == self.nth(i).span.start)
}
/// The SVA binary operator at the cursor: its printed spelling, its
/// precedence, whether it associates right, and how many tokens it
/// spells. `##` is *not* here — it carries an operand, so
/// [`Parser::parse_cycle_delay`] reads it.
fn sva_binary_op(&self) -> Option<(String, u8, bool, usize)> {
let t = self.cur();
let word = |p: u8, right: bool| Some((t.text.clone(), p, right, 1));
match t.kind {
TokenKind::Keyword => match t.text.as_str() {
"and" => word(6, false),
"or" => word(5, false),
"iff" => word(4, true),
_ => None,
},
TokenKind::Ident => match t.text.as_str() {
"intersect" => word(8, false),
"within" => word(9, false),
"throughout" => word(10, true),
"until" | "s_until" | "until_with" | "s_until_with" | "implies" => word(3, true),
_ => None,
},
TokenKind::Symbol => {
if t.is_sym("|") && self.nth(1).is_sym("->") && self.adjacent(2) {
return Some(("|->".to_string(), 2, true, 2));
}
if t.is_sym("|=") && self.nth(1).is_sym(">") && self.adjacent(2) {
return Some(("|=>".to_string(), 2, true, 2));
}
if t.is_sym("#")
&& (self.nth(1).is_sym("-") || self.nth(1).is_sym("="))
&& self.nth(2).is_sym("#")
&& self.adjacent(3)
{
return Some((format!("#{}#", self.nth(1).text), 2, true, 3));
}
None
}
_ => None,
}
}
/// A `property_spec` (IEEE 1800 §16.12): an optional `@( ... )` clocking
/// event, an optional `disable iff ( ... )`, and the property expression.
pub(super) fn parse_prop_spec(&mut self) -> PResult<PropSpec> {
// The gap in front of the whole spec. Empty whenever an enclosing
// construct already claimed it — a concurrent assertion's `(` does.
let leading = self.take_gap();
// `parse_sens_list` reads the list, not the `@`: its caller consumes
// that, exactly as `always @( ... )`'s does.
let clocking = if self.eat_sym("@") { Some(self.parse_sens_list()?) } else { None };
let mut disable = None;
if self.cur().is_kw("disable") && self.nth(1).is_kw("iff") {
disable = Some(Box::new(self.parse_disable_iff(true)?));
}
// The gap between the spec's header and the expression. Nothing else
// owns it: the expression grammar's leaves are ordinary `Expr`s, and
// `parse_expr` takes no meta of its own.
let before_expr = self.take_gap();
let expr = self.parse_prop_expr(0)?;
Ok(PropSpec { leading, clocking, disable, before_expr, expr })
}
/// `disable iff ( expression_or_dist )`. The cursor is on `disable`.
///
/// `parens` says whether the source wrote the parentheses. The clause
/// inside a property spec always does (IEEE 1800 §16.12); the `default`
/// item spells a bare `expression_or_dist` and usually does not
/// (`default disable iff !rst_ni;`), and inventing a pair it did not
/// write would be a token-stream change the safety net refuses.
pub(super) fn parse_disable_iff(&mut self, parens: bool) -> PResult<DisableIff> {
// The gap in front of `disable`. Its single owner: a property spec's
// clocking event may stand before it, and the `default` item's own
// keyword does.
let before_kw = self.take_gap();
self.expect_kw("disable")?;
let after_disable = self.take_gap();
self.expect_kw("iff")?;
// Not `take_before_open("(")`: the `default` spelling writes no
// parentheses, and the gap after `iff` exists either way.
let after_iff = self.take_gap();
let mut after_open = Vec::new();
let mut before_close = Vec::new();
let parens = parens || self.cur().is_sym("(");
if parens {
self.expect_sym("(")?;
after_open = self.take_gap();
}
// What the clause holds is an `expression_or_dist`, so the `dist` set
// a constraint may write is legal here too — OpenTitan
// `hw/ip/tlul/rtl/tlul_assert.sv` does not, but the LRM allows it and
// reading it costs one branch.
let start = self.here();
let mut expr = self.parse_expr()?;
if self.at_dist() {
let before = self.take_gap();
expr = self.parse_dist(start, expr, before)?;
}
if parens {
before_close = self.gap_before(")");
self.expect_sym(")")?;
}
Ok(DisableIff {
parens,
before_kw,
after_disable,
after_iff,
after_open,
expr,
before_close,
before_semi: Vec::new(),
})
}
fn prop_at(&self, start: u32, kind: PropKind) -> PropExpr {
PropExpr { kind, span: self.span_from(start) }
}
/// The precedence-climbing core. `min_prec` is the lowest precedence this
/// call may take; see the table in `docs/features/sva-bodies/README.md`.
fn parse_prop_expr(&mut self, min_prec: u8) -> PResult<PropExpr> {
self.enter()?;
let out = self.parse_prop_expr_inner(min_prec);
self.leave();
out
}
fn parse_prop_expr_inner(&mut self, min_prec: u8) -> PResult<PropExpr> {
let mark = self.pending_trailing.len();
let start = self.here();
let mut lhs = self.parse_prop_prefix(min_prec)?;
loop {
// `a ##1 b` — a cycle delay is a binary operator whose right
// operand follows the delay it carries.
if Self::DELAY_PREC >= min_prec && self.cur().is_sym("##") {
self.link()?;
let before = self.take_around(mark);
let delay = self.parse_cycle_delay()?;
let after = self.take_around(mark);
let rhs = self.parse_prop_expr(Self::DELAY_PREC + 1)?;
lhs = self.prop_at(
start,
PropKind::Binary(Box::new(PropBinary {
lhs,
op: PropOp::Delay(Box::new(delay)),
comments: Box::new(BinaryComments { before, after }),
rhs,
})),
);
continue;
}
let Some((op, prec, right, tokens)) = self.sva_binary_op() else { break };
if prec < min_prec {
break;
}
self.link()?;
let before = self.take_around(mark);
for _ in 0..tokens {
self.bump();
}
let after = self.take_around(mark);
let rhs = self.parse_prop_expr(Self::right_operand_prec(prec, right))?;
lhs = self.prop_at(
start,
PropKind::Binary(Box::new(PropBinary {
lhs,
op: PropOp::Word(op),
comments: Box::new(BinaryComments { before, after }),
rhs,
})),
);
}
Ok(lhs)
}
/// The `min_prec` an operator of precedence `prec` reads its right operand
/// with.
///
/// The **property-level** operators — `|->`, `|=>`, `#-#`, `#=#`, `until`
/// and its `s_`/`_with` spellings, `implies`, `iff` — take a whole
/// `property_expr` on the right, because that is literally what their LRM
/// productions say (`property_expr ::= sequence_expr |=> property_expr`,
/// §16.12.6). Table 11-2's precedence resolves an *ambiguity*; it does not
/// narrow a production. Without this, `a |=> s_eventually b` — OpenTitan
/// `hw/ip/prim/fpv/vip/prim_alert_rxtx_async_assert_fpv.sv:150` and every
/// liveness assertion written like it — is a parse error, because
/// `s_eventually` binds looser than `|=>` and so could not be taken on its
/// right. Every sequence-level operator keeps the ordinary climb.
fn right_operand_prec(prec: u8, right: bool) -> u8 {
match (right, prec <= 4) {
(true, true) => 0,
(true, false) => prec,
(false, _) => prec + 1,
}
}
/// The prefix operators, each gated on `min_prec` so that a call made for
/// a tighter-binding operand does not swallow one that binds looser than
/// it: `not a and b` is `(not a) and b`, never `not (a and b)`.
fn parse_prop_prefix(&mut self, min_prec: u8) -> PResult<PropExpr> {
let start = self.here();
let t = self.cur();
// `if` and `case` are productions of `property_expr` rather than a
// precedence level: both open with a keyword no operand can, so they
// are unambiguous wherever a property expression may stand — the rhs
// of a `|->` included.
if t.is_kw("if") {
return self.parse_prop_if(start);
}
if t.is_kw("case") {
return self.parse_prop_case(start);
}
// The rest of Table 16-3's loosest row is read exactly as `if` and
// `case` are, and for the same reason: sharing that row with them is
// what makes `p1 and always p2` legal, so gating these on `min_prec`
// would refuse a shape the LRM allows. Their operand is a whole
// `property_expr` — nothing binds looser, so each takes everything to
// its right.
if t.kind == TokenKind::Ident && ABORT_WORDS.contains(&t.text.as_str()) {
return self.parse_prop_abort(start);
}
if t.is_kw("always")
|| (t.kind == TokenKind::Ident && PREFIX_WORDS.contains(&t.text.as_str()))
{
return self.parse_prop_unary(start, 0, true);
}
// `not`'s row, which Table 16-3 shares with `nexttime`/`s_nexttime`.
// Gated, because an operator on this row binds *tighter* than `and`:
// `not a and b` is `(not a) and b`, never `not (a and b)`.
if min_prec <= Self::NOT_PREC
&& (t.is_kw("not")
|| (t.kind == TokenKind::Ident && NEXTTIME_WORDS.contains(&t.text.as_str())))
{
let counted = !t.is_kw("not");
return self.parse_prop_unary(start, Self::NOT_PREC, counted);
}
if min_prec <= Self::DELAY_PREC && t.is_sym("##") {
let delay = Box::new(self.parse_cycle_delay()?);
let after_delay = self.take_gap();
let expr = self.parse_prop_expr(Self::DELAY_PREC)?;
return Ok(self.prop_at(
start,
PropKind::Delay(Box::new(PropDelay { delay, after_delay, expr })),
));
}
self.parse_prop_postfix()
}
/// `not p`, and the `nexttime` / `always` / `eventually` family, whose
/// members may carry a `[n]` or `[a:b]` count (IEEE 1800 §16.12.2).
fn parse_prop_unary(&mut self, start: u32, prec: u8, counted: bool) -> PResult<PropExpr> {
let op = self.bump().text;
let comments = self.take_gap();
let mut count = None;
let mut after_count = Vec::new();
if counted && self.cur().is_sym("[") {
self.bump();
let after_open = self.take_gap();
count = Some(Box::new(SvaRange { after_open, ..self.parse_sva_bounds()? }));
after_count = self.take_gap();
}
let expr = self.parse_prop_expr(prec)?;
Ok(self.prop_at(
start,
PropKind::Unary(Box::new(PropUnary { op, comments, count, after_count, expr })),
))
}
/// `accept_on ( expr ) prop`, and its `reject_on` / `sync_accept_on` /
/// `sync_reject_on` siblings (IEEE 1800 §16.12.10).
fn parse_prop_abort(&mut self, start: u32) -> PResult<PropExpr> {
let kw = self.bump().text;
let mut comments =
HeaderComments { after_kw: self.take_before_open("("), ..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.take_gap();
// The operand is a whole `property_expr`, for the reason the
// `always` family's is.
let expr = self.parse_prop_expr(0)?;
Ok(self.prop_at(
start,
PropKind::Abort(Box::new(PropAbort { kw, comments: Box::new(comments), cond, expr })),
))
}
/// `if ( expr ) prop [ else prop ]` at property position
/// (IEEE 1800 §16.12.5).
fn parse_prop_if(&mut self, start: u32) -> PResult<PropExpr> {
self.expect_kw("if")?;
let mut comments =
HeaderComments { after_kw: self.take_before_open("("), ..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.take_gap();
let then = self.parse_prop_expr(0)?;
let mut before_else = Vec::new();
let mut after_else = Vec::new();
let mut els = None;
if self.cur().is_kw("else") {
before_else = self.take_gap();
self.bump();
after_else = self.take_gap();
els = Some(self.parse_prop_expr(0)?);
}
Ok(self.prop_at(
start,
PropKind::If(Box::new(PropIf {
comments: Box::new(comments),
cond,
then,
before_else,
after_else,
els,
})),
))
}
/// `case ( expr ) label : prop ; ... endcase` at property position
/// (IEEE 1800 §16.12.5).
fn parse_prop_case(&mut self, start: u32) -> PResult<PropExpr> {
self.expect_kw("case")?;
let mut comments =
HeaderComments { after_kw: self.take_before_open("("), ..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(")")?;
let mut items = Vec::new();
while !self.cur().is_kw("endcase") {
if self.at_eof() {
return self.error("expected `endcase`");
}
items.push(self.parse_prop_case_item()?);
}
let dangling = self.take_dangling();
self.expect_kw("endcase")?;
Ok(self.prop_at(
start,
PropKind::Case(Box::new(PropCase {
comments: Box::new(comments),
cond,
items,
dangling,
})),
))
}
fn parse_prop_case_item(&mut self) -> PResult<PropCaseItem> {
let start = self.here();
let meta = self.take_meta();
let mut labels = Vec::new();
let is_default = self.cur().is_kw("default");
if is_default {
self.bump();
} else {
loop {
labels.push(self.parse_expr_item()?);
// The gap in front of the separator belongs to the label it
// was written after, which is where the source put it.
let sep = if self.cur().is_sym(",") { "," } else { ":" };
if let Some(last) = labels.last_mut() {
self.take_before_sep(&mut last.meta, sep);
}
if !self.eat_sym(",") {
break;
}
}
}
let before_colon = self.gap_before(":");
// The `:` after `default` is optional, exactly as it is in an
// ordinary `case` statement.
let after_colon = if self.eat_sym(":") { self.take_gap() } else { Vec::new() };
let expr = self.parse_prop_expr(0)?;
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
Ok(PropCaseItem {
meta,
labels,
is_default,
before_colon,
after_colon,
expr,
before_semi,
span: self.span_from(start),
})
}
/// The repetition suffixes, which bind tighter than everything else:
/// `b [*3]`, `b [=1:2]`, `b [->1]` (IEEE 1800 §16.9.2, §16.9.10).
fn parse_prop_postfix(&mut self) -> PResult<PropExpr> {
let start = self.here();
let mut expr = self.parse_prop_primary()?;
while self.at_repeat_bracket() {
self.link()?;
let before_open = self.take_gap();
self.bump(); // [
let after_open = self.take_gap();
// `[+]` writes no operator of its own: its `+` is the bound.
let (op, after_op) = if self.cur().is_sym("+") {
(String::new(), Vec::new())
} else {
let op = self.bump().text;
(op, self.take_gap())
};
let range = Box::new(SvaRange { after_open, ..self.parse_sva_bounds()? });
expr = self.prop_at(
start,
PropKind::Repeat(Box::new(SvaRepeat { expr, before_open, op, after_op, range })),
);
}
Ok(expr)
}
/// The bound of a bracketed SVA operand, from just after its operator
/// through the `]`: `3`, `1:$`, `+`, `*`. The caller owns the gap just
/// inside the `[`, because only the caller knows whether an operator was
/// written between the two.
fn parse_sva_bounds(&mut self) -> PResult<SvaRange> {
let mut range = SvaRange::default();
if (self.cur().is_sym("+") || self.cur().is_sym("*")) && self.nth(1).is_sym("]") {
range.shorthand = self.bump().text;
} else if !self.cur().is_sym("]") {
range.lo = Some(self.parse_expr()?);
if self.cur().is_sym(":") {
range.before_colon = self.take_gap();
self.bump();
range.after_colon = self.take_gap();
range.hi = Some(self.parse_expr()?);
}
}
range.before_close = self.gap_before("]");
self.expect_sym("]")?;
Ok(range)
}
/// `##3`, `##N`, `##(N+1)`, `##[1:3]`, `##[1:$]`, `##[+]`, `##[*]`
/// (IEEE 1800 §16.7). The cursor is on the `##`.
fn parse_cycle_delay(&mut self) -> PResult<CycleDelay> {
self.expect_sym("##")?;
let after_hash = self.take_gap();
if self.cur().is_sym("[") {
self.bump();
let after_open = self.take_gap();
let range = Box::new(SvaRange { after_open, ..self.parse_sva_bounds()? });
return Ok(CycleDelay { after_hash, expr: None, range: Some(range) });
}
// Deliberately not `parse_expr`: `##2 (a || b)` would read the
// parenthesised sequence as a call on the constant `2`, because a `(`
// after an operand is a call everywhere else in the language.
let start = self.here();
let mut expr = self.parse_primary()?;
while self.cur().is_sym("::") {
expr = self.parse_postfix_segment(start, expr)?;
}
Ok(CycleDelay { after_hash, expr: Some(expr), range: None })
}
/// A leaf of the grammar: `strong`/`weak`/`first_match`, a parenthesised
/// sequence or property, or an ordinary expression — a boolean, a
/// sequence instance with its arguments, `s.triggered`, `s.matched`.
fn parse_prop_primary(&mut self) -> PResult<PropExpr> {
let start = self.here();
let t = self.cur();
if t.kind == TokenKind::Ident
&& matches!(t.text.as_str(), "strong" | "weak" | "first_match")
&& self.nth(1).is_sym("(")
{
return self.parse_prop_call(start);
}
if self.at_paren_prop() {
return self.parse_paren_prop(start);
}
let expr = self.parse_expr()?;
Ok(self.prop_at(start, PropKind::Expr(Box::new(expr))))
}
/// `strong ( seq )`, `weak ( seq )`, `first_match ( seq [, items] )`.
fn parse_prop_call(&mut self, start: u32) -> PResult<PropExpr> {
let name = self.bump().text;
let before_open = self.take_before_open("(");
self.expect_sym("(")?;
let after_open = self.take_gap();
let expr = self.parse_prop_spec_expr()?;
let items = self.parse_match_items()?;
let before_close = self.gap_before(")");
self.expect_sym(")")?;
Ok(self.prop_at(
start,
PropKind::Call(Box::new(PropCall {
name,
before_open,
after_open,
expr,
items,
before_close,
})),
))
}
/// True when the `(` at the cursor opens a parenthesised *sequence or
/// property* rather than an ordinary parenthesised expression.
///
/// Decided by a token scan rather than by a speculative parse: a
/// speculative parse that failed would have drained the comment buckets
/// it walked past, and [`Rewind`] cannot put those back. A false positive
/// costs nothing — the parenthesised-property parser reads an ordinary
/// expression through the very same `parse_expr` and prints the same
/// parentheses back — and a false negative is a clean parse error that
/// rewinds the whole construct to its verbatim capture.
fn at_paren_prop(&self) -> bool {
if !self.cur().is_sym("(") {
return false;
}
let mut open = self.pos;
loop {
let end = self.scan_matching(open, "(", ")").saturating_sub(1);
if self.holds_sva_marker(open + 1, end) {
return true;
}
// `(( a, x = 1 ))` — a parenthesised run holding *nothing but*
// one nested group is that group, so the question is asked of it
// instead. Anything else at this level (`(f(a, b) + 1)`) is an
// ordinary expression and the recursion does not fire.
let inner_is_all = self.tokens.get(open + 1).is_some_and(|t| t.is_sym("("))
&& self.scan_matching(open + 1, "(", ")") == end;
if !inner_is_all {
return false;
}
open += 1;
}
}
/// True when the token run `from .. end` holds, at its own bracket depth,
/// something only a sequence or property expression can contain.
fn holds_sva_marker(&self, from: usize, end: usize) -> bool {
let mut depth = 0usize;
for i in from..end {
let t = &self.tokens[i];
let next = self.tokens.get(i + 1);
// A repetition bracket is a marker *and* an opener, so it is
// tested before the depth is moved.
if depth == 0
&& t.is_sym("[")
&& next.is_some_and(|n| n.is_sym("*") || n.is_sym("=") || n.is_sym("->"))
{
return true;
}
// Every bracket pair counts, not only parentheses: the `,` of a
// concatenation or an `inside` set is not a match-item separator.
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") || t.is_sym("'{") {
depth += 1;
continue;
}
if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") {
depth = depth.saturating_sub(1);
continue;
}
if depth > 0 {
continue;
}
let marker = match t.kind {
TokenKind::Symbol => {
t.text == "##"
|| t.text == ","
|| t.text == "@"
|| (t.text == "|" && next.is_some_and(|n| n.is_sym("->")))
|| (t.text == "|=" && next.is_some_and(|n| n.is_sym(">")))
|| (t.text == "#"
&& next.is_some_and(|n| n.is_sym("-") || n.is_sym("="))
&& self.tokens.get(i + 2).is_some_and(|n| n.is_sym("#")))
|| (t.text == "["
&& next
.is_some_and(|n| n.is_sym("*") || n.is_sym("=") || n.is_sym("->")))
}
TokenKind::Keyword => matches!(
t.text.as_str(),
"and" | "or" | "iff" | "not" | "disable" | "if" | "case"
),
TokenKind::Ident => {
ABORT_WORDS.contains(&t.text.as_str())
|| PREFIX_WORDS.contains(&t.text.as_str())
|| matches!(
t.text.as_str(),
"intersect"
| "within"
| "throughout"
| "until"
| "s_until"
| "until_with"
| "s_until_with"
| "implies"
| "strong"
| "weak"
| "first_match"
)
}
_ => false,
};
if marker {
return true;
}
}
false
}
/// `( prop [, x = e ...] )`, the parenthesised sequence or property. A
/// clocking event or a `disable iff` written inside becomes a nested
/// [`PropKind::Spec`].
fn parse_paren_prop(&mut self, start: u32) -> PResult<PropExpr> {
self.expect_sym("(")?;
let after_open = self.take_gap();
let expr = self.parse_prop_spec_expr()?;
let items = self.parse_match_items()?;
let before_close = self.gap_before(")");
self.expect_sym(")")?;
Ok(self.prop_at(
start,
PropKind::Paren(Box::new(ParenProp { after_open, expr, items, before_close })),
))
}
/// A property expression that may open with a clocking event or a
/// `disable iff` of its own — what stands inside a pair of parentheses
/// and inside `strong`/`weak`/`first_match`.
fn parse_prop_spec_expr(&mut self) -> PResult<PropExpr> {
let start = self.here();
if self.cur().is_sym("@") || (self.cur().is_kw("disable") && self.nth(1).is_kw("iff")) {
let spec = self.parse_prop_spec()?;
return Ok(self.prop_at(start, PropKind::Spec(Box::new(spec))));
}
self.parse_prop_expr(0)
}
/// The `, x = e, y++` tail of a sequence match item list
/// (IEEE 1800 §16.10). The cursor is on the `,` that opens it, if any.
fn parse_match_items(&mut self) -> PResult<Vec<MatchItem>> {
let mut items = Vec::new();
while self.cur().is_sym(",") {
let before_comma = self.take_gap();
self.bump();
let start = self.here();
let meta = self.take_meta();
let lhs = self.parse_expr()?;
let mut op = None;
let mut comments = BinaryComments::default();
let mut rhs = None;
if self.cur().kind == TokenKind::Symbol
&& ASSIGN_OPS.contains(&self.cur().text.as_str())
{
comments.before = self.take_gap();
op = Some(self.bump().text);
comments.after = self.take_gap();
rhs = Some(self.parse_expr()?);
}
items.push(MatchItem {
meta,
before_comma,
lhs,
op,
comments: Box::new(comments),
rhs,
span: self.span_from(start),
});
}
Ok(items)
}
}
@@ -0,0 +1,602 @@
//! Classes and constraint bodies, in-class and out-of-block.
use super::*;
#[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!(words(&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!(words(&d.qualifiers), ["local", "rand"]);
let ItemKind::Function(g) = &items[1].kind else { panic!("expected a function") };
assert_eq!(words(&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!(words(&t.prefix), ["extern"]);
assert!(t.is_prototype);
let ItemKind::Task(u) = &items[3].kind else { panic!("expected a task") };
assert_eq!(words(&u.prefix), ["protected", "virtual"]);
assert_eq!(words(&u.qualifiers), ["automatic"]);
assert!(!u.is_prototype);
}
#[test]
fn an_out_of_body_method_keeps_its_class_scope_apart_from_its_name() {
let f = parse_ok("function void my_class::configure(int x);\nendfunction\n");
let ItemKind::Function(g) = &f.items[0].kind else { panic!("expected a function") };
assert_eq!(scope_path(&g.scope), "my_class");
assert_eq!(g.name, "configure");
}
// ------------------------------------------------------------------
// 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_empty());
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!(words(&c.qualifiers), ["extern"]);
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!(words(&constraint_of(&f).qualifiers), ["pure", "static"]);
}
#[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].name.text.is_empty(), "a skipped dimension is an empty name");
assert_eq!(vars[1].name.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!(scope_path(&c.scope), "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!(scope_path(&file_constraint(&f).scope), "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\")");
}
#[test]
fn interface_class_is_not_an_interface() {
// IEEE 1800-2017 §8.26: a different construct — and since
// `vendor-formal-grammar` a supported one. It is a *class*: the word
// rides in the prefix, the closer is `endclass`, and nothing reads it
// as an `interface ... endinterface`.
let f = parse_ok("interface class ic;\n pure virtual function void f();\nendclass\n");
let ItemKind::Class(c) = &f.items[0].kind else { panic!("expected a class") };
assert_eq!(words(&c.prefix), ["interface"]);
assert!(c.is_interface_class());
assert_eq!(c.name, "ic");
assert_eq!(c.items.len(), 1, "the pure virtual prototype is an ordinary class item");
// And an ordinary interface is still an interface.
let f = parse_ok("interface i;\nendinterface\n");
assert!(matches!(&f.items[0].kind, ItemKind::Module(m) if m.kw == "interface"));
}
#[test]
fn an_interface_class_may_extend_another_one() {
// IEEE 1800-2017 §8.26.4: interface classes inherit with `extends`,
// and a plain class promises them with `implements`.
let f = parse_ok("interface class b extends a;\nendclass\n");
let ItemKind::Class(c) = &f.items[0].kind else { panic!("expected a class") };
assert!(c.is_interface_class());
assert_eq!(c.extends.as_ref().map(|e| e.name.as_str()), Some("a"));
}
#[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);
}
@@ -0,0 +1,144 @@
//! Where a comment lands: the slot pins for the comment plumbing in
//! `parser/cursor.rs`.
use super::*;
#[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);
}
@@ -0,0 +1,524 @@
//! Covergroup bodies (`docs/features/covergroup-bodies/README.md`).
use super::*;
#[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");
}
// ------------------------------------------------------------------
// 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);
}
/// 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");
}
+292
View File
@@ -0,0 +1,292 @@
//! Data types, declarators, typedefs, enums, structs, and function/task/let
//! declarations.
use super::*;
#[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 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_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));
}
// ------------------------------------------------------------------
// 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 a_union_may_be_tagged() {
let f = parse_ok("typedef union tagged packed {\n logic [7:0] v;\n} u_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 union") };
assert!(s.tagged);
assert!(s.packed);
// And a plain one is not.
let f = parse_ok("typedef union packed {\n logic [7:0] v;\n} u_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 union") };
assert!(!s.tagged);
}
#[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 an_unterminated_anonymous_enum_is_an_error() {
assert!(
parse_err("module m;\n enum logic [1:0] {A, B state;\nendmodule\n").contains("expected")
);
}
#[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_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_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!(words(&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!(words(&s.members[0].qualifiers), ["rand"]);
assert_eq!(words(&s.members[1].qualifiers), ["randc"]);
assert!(s.members[2].qualifiers.is_empty());
assert_eq!(s.members[0].declarators[0].name, "cpol");
}
@@ -0,0 +1,447 @@
//! Macros, and the directives a list keeps between its elements.
use super::*;
#[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
);
}
#[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 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]);
}
#[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 twice. `directive-in-statements` (2026-08-29) made a
// *conditional* region inside a connection's parens a verbatim
// capture rather than a refusal — of the whole item. TODO §26
// narrowed the capture to the one connection's **value**, so the
// instantiation is a real node again: its module, its instance and
// its other connections are all structural, and only the region
// itself is 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::Instantiation(inst) = &m.items[0].kind else {
panic!("expected an instantiation")
};
assert_eq!(inst.module, "sub");
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
assert_eq!(conns[0].name, "a");
let Some(Expr { kind: ExprKind::Verbatim(raw), .. }) = &conns[0].expr else {
panic!("expected a verbatim value")
};
assert!(raw.text.starts_with("`ifdef X"), "{:?}", raw.text);
assert!(raw.text.ends_with("`endif"), "{:?}", 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));
}
#[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(_)));
}
+370
View File
@@ -0,0 +1,370 @@
//! Expressions: primaries, casts, patterns, calls and their arguments.
use super::*;
#[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",
);
}
/// `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 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 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 a_name_that_contains_a_new_keyword_is_still_a_name() {
// The keyword/identifier boundary: only the whole word is reserved.
let f = parse_ok(
"module checker_x;\n wire config_reg;\n logic library_sel;\n assign config_reg = library_sel;\nendmodule\n",
);
assert_eq!(module_of(&f).name, "checker_x");
}
/// 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 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 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 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_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 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_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(_)));
}
@@ -0,0 +1,219 @@
//! Instantiations, bind directives, gates, drive strengths and delays.
use super::*;
#[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 chk_mod u_chk (.a(x), .b(y));
bind i_inst chk_mod #(.W(8)) u_chk2 (.*);
bind top.u_dut.u_core chk_mod 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 chk_mod 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_path(), "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 an_indexed_bind_target_parses_as_path_segments() {
// `docs/coverage_gaps.md` M6: binding SVA into a generate array is
// the shape formal setups write, and until TODO §26 the path scan
// stopped at the `[` and the file failed with `expected ';'`.
let file = parse_ok("module m;\n bind top.gen[0].u_core chk c (.clk(clk));\nendmodule\n");
let ItemKind::Bind(b) = &module_of(&file).items[0].kind else {
panic!("expected a bind directive")
};
let names: Vec<&str> = b.target.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names, ["top", "gen", "u_core"]);
assert!(b.target[0].index.is_none());
assert!(matches!(
b.target[1].index.as_ref().map(|e| &e.kind),
Some(ExprKind::Number(n)) if n == "0"
));
assert!(b.target[2].index.is_none());
assert_eq!(b.target_path(), "top.gen.u_core");
assert_eq!(b.inst.module, "chk");
// A non-constant selector is an ordinary expression, and a bare
// indexed head needs no path at all.
let file = parse_ok("module m;\n bind arr[N-1] chk c (.*);\nendmodule\n");
let ItemKind::Bind(b) = &module_of(&file).items[0].kind else {
panic!("expected a bind directive")
};
assert_eq!(b.target.len(), 1);
assert!(matches!(b.target[0].index.as_ref().map(|e| &e.kind), Some(ExprKind::Binary { .. })));
}
#[test]
fn an_escaped_bind_path_segment_keeps_its_terminator() {
// §2.9-21's rule for `::` chains, applied to the `.` ones: whitespace
// is an escaped identifier's only terminator, so the segments are
// kept apart rather than glued.
let file = parse_ok("module m;\n bind \\my-inst .u_core chk c (.*);\nendmodule\n");
let ItemKind::Bind(b) = &module_of(&file).items[0].kind else {
panic!("expected a bind directive")
};
assert_eq!(b.target[0].name, "\\my-inst");
assert_eq!(b.target_path(), "\\my-inst .u_core");
// The `: instance, list` glues its paths into one name, so it carries
// the same rule through `push_path_segment`.
let file = parse_ok("module m;\n bind d : \\my-inst .u_core chk c (.*);\nendmodule\n");
let ItemKind::Bind(b) = &module_of(&file).items[0].kind else {
panic!("expected a bind directive")
};
assert_eq!(b.instances[0].text, "\\my-inst .u_core");
}
#[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");
// And the shapes the `[…]` scan could have swallowed: a packed
// dimension on the type, and an unpacked one on the declarator.
parse_ok("module m;\n bind [3:0] x;\n bind y [7:0];\nendmodule\n");
}
#[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_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());
}
#[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_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_path(), "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"]);
}
@@ -0,0 +1,252 @@
//! Items that are neither a module, a class nor a declaration: elaboration
//! tasks, generate regions, packages, imports and exports, DPI, and the
//! vendor/formal collateral kept verbatim.
use super::*;
#[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 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 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}");
}
// ------------------------------------------------------------------
// Vendor and formal collateral — `vendor-formal-grammar`
// ------------------------------------------------------------------
/// The verbatim leaf `src`'s single item must be, with its text.
fn verbatim_item(src: &str) -> String {
let f = parse_ok(src);
let ItemKind::Verbatim(raw) = &f.items[0].kind else {
panic!("expected a verbatim item, got {:?}", f.items[0].kind)
};
raw.text.clone()
}
#[test]
fn a_specify_block_is_one_opaque_item() {
let src = "module m;\n specify\n (a => b) = (1.0, 1.2);\n endspecify\nendmodule\n";
let f = parse_ok(src);
let m = module_of(&f);
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim item") };
assert!(raw.text.starts_with("specify"));
assert!(raw.text.ends_with("endspecify"), "the closer is inside the leaf: {:?}", raw.text);
assert_eq!(raw.col, 3, "the block's own column, for the re-indent contract");
}
#[test]
fn a_primitive_swallows_its_own_table() {
let text = verbatim_item(
"primitive p (q, a);\n output q;\n input a;\n table\n 0 : 1;\n 1 : 0;\n endtable\nendprimitive : p\n",
);
assert!(text.starts_with("primitive p"));
assert!(text.ends_with("endprimitive : p"), "the end label is inside: {text:?}");
assert!(text.contains("endtable"), "the truth table never became an item of its own");
}
#[test]
fn a_semicolon_after_an_opaque_closer_is_a_null_item() {
// None of the five closers takes a `;` in the LRM, so the scan leaves
// it where it is and the `empty-item` lint gets to say so — unlike
// `endgroup`, whose scan eats one.
let f = parse_ok("primitive p (q, a);\n table\n 0 : 1;\n endtable\nendprimitive\n;\n");
assert_eq!(f.items.len(), 2);
assert!(matches!(f.items[1].kind, ItemKind::Empty));
}
#[test]
fn a_checker_nested_in_a_checker_closes_on_the_right_keyword() {
let text = verbatim_item(
"checker outer (logic clk);\n checker inner (logic a);\n endchecker : inner\nendchecker : outer\n",
);
assert!(text.ends_with("endchecker : outer"), "the outer closer, not the inner: {text:?}");
}
#[test]
fn a_config_block_and_a_library_line_are_opaque() {
let text = verbatim_item(
"config cfg;\n design work.top;\n default liblist a b;\n instance top.u1 use work.impl;\nendconfig : cfg\n",
);
assert!(text.ends_with("endconfig : cfg"));
let line = verbatim_item("library rtlLib \"/proj/*.v\" -incdir \"/inc\";\n");
assert_eq!(line, "library rtlLib \"/proj/*.v\" -incdir \"/inc\";");
}
#[test]
fn a_specparam_is_a_declaration() {
let f = parse_ok("module m;\n specparam tS = 0.12, tH = 0.08;\nendmodule\n");
let m = module_of(&f);
let ItemKind::ParamDecl(d) = &m.items[0].kind else { panic!("expected a param decl") };
assert_eq!(d.kw, "specparam");
let names: Vec<&str> = d.declarators.iter().map(|x| x.name.as_str()).collect();
assert_eq!(names, ["tS", "tH"]);
}
#[test]
fn a_specparam_the_grammar_cannot_read_rewinds_to_verbatim() {
// `PATHPULSE$a$b = (reject, error);` — the value is a pair, not an
// expression, so the declaration parse fails and the item is the
// opaque line instead. Nothing is lost and nothing is guessed.
let f = parse_ok("module m;\n specparam PATHPULSE$a$b = (1.0, 1.2);\nendmodule\n");
let m = module_of(&f);
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim item") };
assert_eq!(raw.text, "specparam PATHPULSE$a$b = (1.0, 1.2);");
}
#[test]
fn an_alias_is_a_flat_list_of_nets() {
let f = parse_ok("module m;\n alias a = b[3:0] = {c, d};\nendmodule\n");
let m = module_of(&f);
let ItemKind::Alias(nets) = &m.items[0].kind else { panic!("expected an alias") };
assert_eq!(nets.len(), 3, "three terms, none of them the value of another");
}
#[test]
fn an_unclosed_opaque_block_stops_at_the_next_construct() {
// Tolerant mode only: `SYNC_CLOSERS` gained the five new closers, so a
// broken item inside a module cannot eat the `endspecify` the module's
// own loop is waiting behind.
let src = "module m;\n specify\nendmodule\n";
let (f, diags) = parse_tolerant(tokenize(src).expect("lex error"), src);
assert!(!diags.is_empty(), "the missing `endspecify` is reported");
assert_eq!(f.items.len(), 1, "and the module still closed");
}
@@ -0,0 +1,282 @@
//! The nesting and chain budgets: what parses at the limit and what errors
//! just past it (`docs/features/recursion-limit/README.md`).
use super::*;
/// 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");
}
// ------------------------------------------------------------------
// 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");
}
#[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));
}
#[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);
}
@@ -0,0 +1,72 @@
//! The parser's unit tests, one file per grammar file they exercise
//! (`limits` covers the nesting and chain budgets, `comments` the comment
//! plumbing in `cursor.rs`, `items` the item dispatch and the verbatim
//! vendor/formal blocks). The helpers below are shared by every file.
use super::*;
use crate::lexer::tokenize;
mod class;
mod comments;
mod covergroup;
mod decl;
mod directive;
mod expr;
mod instance;
mod items;
mod limits;
mod module;
mod split;
mod stmt;
mod sva;
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 keywords of a qualifier run, without the comments each one carries.
fn words(run: &[Qualifier]) -> Vec<&str> {
run.iter().map(|q| q.text.as_str()).collect()
}
/// 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,
}
}
fn module_of(file: &SourceFile) -> &Module {
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
m
}
fn class_of(file: &SourceFile) -> &ClassDecl {
let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") };
c
}
// ------------------------------------------------------------------
// 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
}
@@ -0,0 +1,389 @@
//! Module, interface and program headers: parameter ports, ports, modports
//! and clocking blocks.
use super::*;
#[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 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");
}
// ------------------------------------------------------------------
// 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 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 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_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 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::DefaultDisable(_) => "default-disable",
ItemKind::DataDecl(_) => "decl",
ItemKind::Error(_) => "error",
_ => "other",
})
.collect();
assert!(
kinds.contains(&"clocking")
&& kinds.contains(&"default-disable")
&& 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");
}
@@ -0,0 +1,630 @@
//! Split conditional regions (`docs/features/directive-split/README.md`) and
//! the opening split of `directive-in-statements`.
use super::*;
// ------------------------------------------------------------------
// 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_only_that_value() {
// 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. Until TODO §26 the whole instantiation became
// opaque bytes, which cost it its edge, its lens and its port
// references; now the override's value alone is the verbatim leaf.
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::Instantiation(inst) = &m.items[0].kind else {
panic!("expected an instantiation")
};
assert_eq!(inst.module, "padring");
assert_eq!(inst.instances[0].name, "u_padring");
let params = inst.params.as_ref().expect("a parameter override list");
let Some(Expr { kind: ExprKind::Verbatim(raw), .. }) = &params[0].expr else {
panic!("expected a verbatim override value")
};
assert!(raw.text.starts_with("{"), "{:?}", raw.text);
assert!(raw.text.ends_with("}"), "{:?}", raw.text);
// The connection list around it is structural again.
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
assert_eq!(conns[0].name, "clk");
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"
);
}
+308
View File
@@ -0,0 +1,308 @@
//! Statements: event controls, case forms, loops, labels, and the DV
//! statements.
use super::*;
#[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 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 { expr: 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 { expr: 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 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 { expr: 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_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_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 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].name.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].name.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_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_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());
}
// ------------------------------------------------------------------
// 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_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.name.text.as_str()).collect::<Vec<_>>(), ["", "bank"]);
assert!(vars[0].name.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.name.text.as_str()).collect::<Vec<_>>(), ["i", "", "k"]);
}
+555
View File
@@ -0,0 +1,555 @@
//! Concurrent assertions, property/sequence declarations, action blocks and
//! `default disable iff`.
use super::*;
#[test]
fn a_property_declaration_in_a_class_is_a_real_node() {
// Since `sva-bodies` a `property`/`sequence` declaration is a node
// rather than a verbatim leaf, and its span still covers exactly the
// bytes the old capture handed back.
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::PropSeqDecl(d) = &items[0].kind else { panic!("expected a property") };
assert_eq!(d.kw, "property");
assert_eq!(d.name.text, "p");
assert_eq!(d.end_label.as_ref().expect("the end label").text, "p");
assert_eq!(&src[items[0].span.as_range()], "property p;\n a |-> b;\n endproperty : p");
}
#[test]
fn a_comment_after_a_property_declaration_stays_outside_it() {
// The comment is written past the declaration's last token, so it
// must not be swallowed *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;
assert!(matches!(items[0].kind, ItemKind::PropSeqDecl(_)));
assert_eq!(items[0].meta.trailing.as_ref().expect("the comment survived").text, "// why");
}
// ------------------------------------------------------------------
// Concurrent assertions (`docs/features/assertions/README.md`)
// ------------------------------------------------------------------
#[test]
fn a_concurrent_assertion_is_a_real_node() {
let src = "module m;\n assert property (@(posedge clk) a |-> ##[1:3] b);\nendmodule\n";
let f = parse_ok(src);
let items = &module_of(&f).items;
let ItemKind::Assertion(a) = &items[0].kind else { panic!("expected an assertion") };
assert_eq!(a.kw, "assert");
assert_eq!(a.kw2, "property");
assert!(a.spec.clocking.is_some(), "the clocking event is a node");
assert!(a.action.pass.is_none() && a.action.fail.is_none(), "the bare `;` form");
assert_eq!(
&src[items[0].span.as_range()],
"assert property (@(posedge clk) a |-> ##[1:3] b);"
);
}
#[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"));
let ItemKind::Assertion(a) = &module_of(&f).items[0].kind else {
panic!("`{kw} property` did not parse as an assertion")
};
assert_eq!(a.kw, kw);
}
}
/// QA §27, round 1 (HIGH): IEEE 1800-2017 **Table 16-3** puts
/// `nexttime`/`s_nexttime` on `not`'s row, and ties the `always` /
/// `eventually` / `accept_on` family to `if`/`case` on the loosest row.
/// The first draft read the table from Table 11-2 instead: it grouped
/// `nexttime` with `always`, and gated the whole loose row on `min_prec`
/// while leaving only `if`/`case` position-independent. Every shape below
/// is legal SVA and every one of them fell back to the verbatim capture.
#[test]
fn a_loose_prefix_operator_is_read_wherever_a_property_expression_may_stand() {
for body in [
"p1 and nexttime p2",
"p1 and always p2",
"p1 and accept_on(e) p2",
"p1 and s_eventually p2",
"p1 or s_always p2",
"p1 and sync_reject_on(e) p2",
"a |-> nexttime b",
"not nexttime a and b",
"a or always b |-> c",
] {
let src = format!("module m;\n assert property ({body});\nendmodule\n");
let f = parse_ok(&src);
assert!(
matches!(module_of(&f).items[0].kind, ItemKind::Assertion(_)),
"`{body}` must be a node, not the verbatim fallback"
);
assert_eq!(
&src[module_of(&f).items[0].span.as_range()],
format!("assert property ({body});")
);
}
}
/// The other half of the same table row: `nexttime` binds *tighter* than
/// `and`, so it may not swallow one — `not`'s rule, which it now shares.
#[test]
fn nexttime_binds_tighter_than_and_the_way_not_does() {
let f = parse_ok("module m;\n assert property (nexttime a and b);\nendmodule\n");
let ItemKind::Assertion(x) = &module_of(&f).items[0].kind else {
panic!("expected an assertion")
};
// `(nexttime a) and b`: the root is the `and`, not the `nexttime`.
let PropKind::Binary(b) = &x.spec.expr.kind else {
panic!("expected a binary root, got {:?}", x.spec.expr.kind)
};
assert!(matches!(&b.op, PropOp::Word(w) if w == "and"));
assert!(matches!(b.lhs.kind, PropKind::Unary(_)), "{:?}", b.lhs.kind);
// And `always` on the loosest row does the opposite: it takes the
// whole `a and b` to its right.
let f = parse_ok("module m;\n assert property (always a and b);\nendmodule\n");
let ItemKind::Assertion(x) = &module_of(&f).items[0].kind else {
panic!("expected an assertion")
};
let PropKind::Unary(u) = &x.spec.expr.kind else {
panic!("expected a unary root, got {:?}", x.spec.expr.kind)
};
assert_eq!(u.op, "always");
assert!(matches!(u.expr.kind, PropKind::Binary(_)), "{:?}", u.expr.kind);
}
/// `nexttime` keeps its optional `[n]` count on its new row — the one
/// thing it does that `not` does not.
#[test]
fn nexttime_still_carries_its_bracketed_count() {
let f = parse_ok("module m;\n assert property (nexttime [2] a and b);\nendmodule\n");
let ItemKind::Assertion(x) = &module_of(&f).items[0].kind else {
panic!("expected an assertion")
};
let PropKind::Binary(b) = &x.spec.expr.kind else { panic!("expected a binary root") };
let PropKind::Unary(u) = &b.lhs.kind else { panic!("expected a unary lhs") };
assert_eq!(u.op, "nexttime");
assert!(u.count.is_some(), "the `[2]` count survives the regrouping");
}
#[test]
fn cover_sequence_is_the_one_spelling_that_names_a_sequence() {
let f = parse_ok("module m;\n cover sequence (a ##1 b);\nendmodule\n");
let ItemKind::Assertion(a) = &module_of(&f).items[0].kind else {
panic!("expected an assertion")
};
assert_eq!((a.kw.as_str(), a.kw2.as_str()), ("cover", "sequence"));
}
#[test]
fn a_label_before_a_concurrent_assertion_is_part_of_the_item() {
let src = "NoNMI: assume property (~irq_nm_i);\n";
let f = parse_ok(src);
let ItemKind::Assertion(a) = &f.items[0].kind else { panic!("expected an assertion") };
assert_eq!(a.label.as_ref().expect("the label").text, "NoNMI");
assert_eq!(&src[f.items[0].span.as_range()], "NoNMI: assume property (~irq_nm_i);");
}
#[test]
fn an_assertion_action_block_is_part_of_the_item() {
let src = "module m;\n assert property (a) else $error(\"no\");\nendmodule\n";
let f = parse_ok(src);
let items = &module_of(&f).items;
let ItemKind::Assertion(a) = &items[0].kind else { panic!("expected an assertion") };
assert!(a.action.pass.is_none(), "the `else`-only spelling has no pass statement");
assert!(a.action.fail.is_some());
assert_eq!(&src[items[0].span.as_range()], "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::Assertion(a) = &items[0].kind else { panic!("expected an assertion") };
let fail = a.action.fail.as_ref().expect("the fail statement");
assert!(matches!(fail.kind, StmtKind::Block { .. }));
assert_eq!(
&src[items[0].span.as_range()],
"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 of `assertions`: the scan used to stop at the first `;`
// inside the nested block, leaving its `end` (and the `else`) behind.
// The action block is a real statement now, but the extent it covers
// is still exactly what that fix established.
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::Assertion(a) = &items[0].kind else { panic!("expected an assertion") };
assert!(matches!(a.action.pass.as_ref().map(|s| &s.kind), Some(StmtKind::If { .. })));
assert_eq!(
&src[items[0].span.as_range()],
"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 end the action statement early.
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;
assert!(
matches!(items[0].kind, ItemKind::Assertion(_)),
"expected an assertion for {body}"
);
assert_eq!(&src[items[0].span.as_range()], 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 src =
"module m;\n assert property (a) $info(\"y\"); else $error(\"n\");\n wire w;\nendmodule\n";
let f = parse_ok(src);
let items = &module_of(&f).items;
let ItemKind::Assertion(a) = &items[0].kind else { panic!("expected an assertion") };
assert!(a.action.pass.is_some() && a.action.fail.is_some());
assert_eq!(
&src[items[0].span.as_range()],
"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") };
assert!(
matches!(stmts[0].kind, StmtKind::Assertion(_)),
"expected an assertion statement, got {:?}",
stmts[0].kind
);
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_real_nodes() {
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::PropSeqDecl(p) = &items[0].kind else { panic!("expected a property") };
assert_eq!(p.name.text, "p");
assert_eq!(p.args.as_ref().expect("the formal list").args[0].name, "w");
assert_eq!(p.locals.len(), 1, "the `realtime t;` local variable");
assert!(p.spec_semi, "the spec's own `;`");
assert_eq!(
&src[items[0].span.as_range()],
"property p(int w);\n realtime t;\n a |-> b;\n endproperty : p"
);
let ItemKind::PropSeqDecl(s) = &items[1].kind else { panic!("expected a sequence") };
assert_eq!((s.kw.as_str(), s.name.text.as_str()), ("sequence", "s"));
assert_eq!(&src[items[1].span.as_range()], "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 expect_with_a_sequence_operator_is_an_assertion() {
for body in [
"expect (@(posedge clk) a ##1 b) else $error(\"no\");",
"expect (a |-> b);",
"expect (a |=> b);",
"expect (a throughout b);",
"expect (disable iff (rst) a ##1 b);",
] {
let f = parse_ok(&format!("module m;\n initial begin\n {body}\n end\nendmodule\n"));
let m = module_of(&f);
let ItemKind::Initial(stmt) = &m.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::Assertion(_)),
"{body} should be an assertion, got {:?}",
stmts[0].kind
);
}
}
#[test]
fn expect_of_an_argument_list_is_still_a_task_call() {
// The 41-site regression guard: `expect(word1[7:0]);` in picorv32's
// spiflash testbench is a task, and nothing this round did may change
// that. An argument list cannot hold `##`, `|->`, `|=>`, `throughout`,
// `disable iff` or `@(`, which is the whole reason the rule is safe.
for body in ["expect(word1[7:0]);", "expect(x, y);", "expect(a[i] + 1);", "expect();"] {
let f = parse_ok(&format!("module m;\n initial begin\n {body}\n end\nendmodule\n"));
let m = module_of(&f);
let ItemKind::Initial(stmt) = &m.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::Verbatim(_)),
"{body} must stay a call, got {:?}",
stmts[0].kind
);
}
}
#[test]
fn a_default_disable_iff_is_a_real_node() {
// OpenTitan hw/ip/tlul/rtl/tlul_assert.sv:36 — IEEE 1800 §16.15.
// Since `sva-bodies` it is a node with its condition as an ordinary
// expression, so the signals it names are references.
let src = "module m;\n default disable iff disable_sva || !rst_ni;\n wire w;\nendmodule\n";
let f = parse_ok(src);
let items = &module_of(&f).items;
let ItemKind::DefaultDisable(d) = &items[0].kind else {
panic!("expected a default disable, got {:?}", items[0].kind)
};
assert!(!d.parens, "the item spelling writes no parentheses");
assert_eq!(&src[items[0].span.as_range()], "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. The `dist`
// spelling is an `expression_or_dist`, which the expression grammar
// reads since `constraint-bodies`.
let src = "module m;\n default disable iff x dist {1 := 1, 2 := 2};\n wire w;\nendmodule\n";
let f = parse_ok(src);
let items = &module_of(&f).items;
assert!(matches!(items[0].kind, ItemKind::DefaultDisable(_)), "{:?}", items[0].kind);
assert_eq!(&src[items[0].span.as_range()], "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 src = "module m;\n default disable iff x == \"a;b\";\n wire w;\nendmodule\n";
let f = parse_ok(src);
let items = &module_of(&f).items;
assert!(matches!(items[0].kind, ItemKind::DefaultDisable(_)), "{:?}", items[0].kind);
assert_eq!(&src[items[0].span.as_range()], "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 src = "module m;\n default disable iff /* ; */ x;\n wire w;\nendmodule\n";
let f = parse_ok(src);
let items = &module_of(&f).items;
let ItemKind::DefaultDisable(d) = &items[0].kind else { panic!("expected a default disable") };
assert_eq!(d.after_iff.len(), 1, "the comment has a slot of its own");
assert_eq!(&src[items[0].span.as_range()], "default disable iff /* ; */ x;");
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)));
}
#[test]
fn two_default_disable_iffs_in_a_row_are_captured_separately() {
let src =
"module m;\n default disable iff a;\n default disable iff b;\n wire w;\nendmodule\n";
let f = parse_ok(src);
let items = &module_of(&f).items;
assert!(matches!(items[0].kind, ItemKind::DefaultDisable(_)));
assert_eq!(&src[items[0].span.as_range()], "default disable iff a;");
assert!(matches!(items[1].kind, ItemKind::DefaultDisable(_)));
assert_eq!(&src[items[1].span.as_range()], "default disable iff b;");
assert!(matches!(items[2].kind, ItemKind::DataDecl(_)));
}
#[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::Assertion(a) = &items[0].kind else { panic!("expected an assertion") };
let fail = a.action.fail.as_ref().expect("the fail statement");
assert!(matches!(fail.kind, StmtKind::MacroStmt(_)), "{:?}", fail.kind);
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::Assertion(a) = &items[0].kind else { panic!("expected an assertion") };
let fail = a.action.fail.as_ref().expect("the fail statement");
assert!(matches!(fail.kind, StmtKind::Assign { .. }), "{:?}", fail.kind);
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::Assertion(a) = &items[0].kind else { panic!("expected an assertion") };
let fail = a.action.fail.as_ref().expect("the fail statement");
assert!(matches!(fail.kind, StmtKind::Assign { .. }), "{:?}", fail.kind);
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;
// The one shape of the four that the SVA grammar hands back to the
// verbatim fallback: a macro standing first in a statement is a
// `MacroStmt`, so the `+ 1;` after it is a token the action block's
// statement parser cannot place. The fallback's flat scan still
// covers the whole item, which is what this test has always pinned.
let ItemKind::Verbatim(raw) = &items[0].kind else {
panic!("expected the verbatim fallback, got {:?}", items[0].kind)
};
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::Assertion(a) = &items[0].kind else { panic!("expected an assertion") };
let fail = a.action.fail.as_ref().expect("the fail statement");
assert!(matches!(fail.kind, StmtKind::Assign { .. }), "{:?}", fail.kind);
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::Assertion(a) = &items[0].kind else { panic!("expected an assertion") };
assert!(a.action.fail.is_some(), "the `++` is part of the fail statement");
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::Assertion(a) = &items[0].kind else {
panic!("expected an assertion for {next:?}")
};
let fail = a.action.fail.as_ref().expect("the fail statement");
assert!(matches!(fail.kind, StmtKind::MacroStmt(_)), "{next:?}: {:?}", fail.kind);
assert_eq!(items.len(), 2, "{next:?}: {:?}", items.len());
}
}
#[test]
fn a_label_before_a_concurrent_assertion_still_takes_the_assertion_path() {
// The concurrent-assertion check runs first and takes the label with
// it, so the general statement-label path never sees one.
let f = parse_ok(
"module m;\n initial begin\n NoNMI: assert property (@(posedge c) a);\n end\nendmodule\n",
);
let StmtKind::Assertion(a) = &initial_stmts(&f)[0].kind else {
panic!("expected an assertion statement")
};
assert_eq!(a.label.as_ref().expect("the label").text, "NoNMI");
}
+245
View File
@@ -0,0 +1,245 @@
//! Function, task and `let` declarations: qualifiers, the port list, the
//! body and its closing label.
use super::*;
/// A task/function body: its statements, the comments left dangling before
/// the closing keyword, and that keyword's own `: name` label.
type TfBody = (Vec<Stmt>, Vec<Comment>, Box<LabelComments>, Option<Name>);
impl<'a> Parser<'a> {
pub(super) fn parse_function(&mut self) -> PResult<FunctionDecl> {
self.parse_function_decl(None)
}
pub(super) 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.text == "extern" || q.text == "pure");
self.expect_kw("function")?;
let after_kw = self.take_gap();
let mut qualifiers = Vec::new();
while self.cur().is_kw("automatic") || self.cur().is_kw("static") {
let text = self.bump().text;
qualifiers.push(Qualifier { text, after: self.take_gap() });
}
// 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 before_name = self.take_gap();
let (scope, Name { text: name, span: name_span }) = self.parse_method_name()?;
let has_parens = self.cur().is_sym("(");
let before_args = self.take_before_open("(");
let TfPorts { args, dangling: args_dangling } = self.parse_tf_ports()?;
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
let (stmts, dangling, end_label_comments, end) = if is_prototype {
(Vec::new(), Vec::new(), Box::default(), 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,
after_kw,
qualifiers,
is_prototype,
scope,
ret,
before_name,
name,
name_span,
has_parens,
before_args,
args,
args_dangling,
before_semi,
stmts,
dangling,
end_label_comments,
end_label,
end_label_span,
end_semi,
})
}
pub(super) fn parse_task(&mut self) -> PResult<TaskDecl> {
self.parse_task_decl(None)
}
pub(super) 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.text == "extern" || q.text == "pure");
self.expect_kw("task")?;
let after_kw = self.take_gap();
let mut qualifiers = Vec::new();
while self.cur().is_kw("automatic") || self.cur().is_kw("static") {
let text = self.bump().text;
qualifiers.push(Qualifier { text, after: self.take_gap() });
}
let before_name = self.take_gap();
let (scope, Name { text: name, span: name_span }) = self.parse_method_name()?;
let has_parens = self.cur().is_sym("(");
let before_args = self.take_before_open("(");
let TfPorts { args, dangling: args_dangling } = self.parse_tf_ports()?;
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
let (stmts, dangling, end_label_comments, end) = if is_prototype {
(Vec::new(), Vec::new(), Box::default(), 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,
after_kw,
qualifiers,
is_prototype,
scope,
before_name,
name,
name_span,
has_parens,
before_args,
args,
args_dangling,
before_semi,
stmts,
dangling,
end_label_comments,
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.
pub(super) 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()?.args;
self.expect_sym("=")?;
let value = self.parse_expr()?;
self.expect_sym(";")?;
Ok(LetDecl { name, name_span, has_parens, ports, value })
}
pub(super) fn parse_tf_ports(&mut self) -> PResult<TfPorts> {
let mut args = Vec::new();
if !self.cur().is_sym("(") {
return Ok(TfPorts::default());
}
self.bump();
if self.cur().is_sym(")") {
// Only what was written *inside* the empty `()`, as an empty
// argument list of a call keeps.
let dangling = self.take_gap();
self.bump();
return Ok(TfPorts { args, dangling });
}
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 after_dir = if dir.is_some() { self.take_gap() } else { Vec::new() };
let ty = self.parse_opt_data_type()?;
let before_name = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?;
let mut eq_comments = BinaryComments::default();
let default = if self.cur().is_sym("=") {
eq_comments.before = self.take_gap();
self.bump();
eq_comments.after = self.take_gap();
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,
after_dir,
ty,
before_name,
name,
name_span,
unpacked,
eq_comments: Box::new(eq_comments),
default,
span,
});
if !more {
break;
}
}
if let Some(last) = args.last_mut() {
self.take_before_sep(&mut last.meta, ")");
}
self.expect_sym(")")?;
Ok(TfPorts { args, dangling: Vec::new() })
}
fn parse_tf_body(&mut self, end_kw: &str) -> PResult<TfBody> {
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)?;
let (comments, name) = self.parse_label_with()?;
Ok((stmts, dangling, comments, name))
}
}
+227
View File
@@ -0,0 +1,227 @@
//! The constructs lucisv keeps as source bytes rather than as a tree, and
//! the capture helpers every speculative parse falls back to.
//!
//! Vendor and formal collateral — five blocks and two lines that lucisv
//! deliberately does not model. Each one is copied out of the source by
//! span for the reason a `property` declaration is: the body is a second
//! grammar — a specify path's `=>`/`*>` connections, a UDP truth table, a
//! checker's assertion vocabulary, a config's `design`/`instance`/`liblist`
//! clauses — with no layout convention worth inventing. See
//! `docs/features/vendor-formal-grammar/README.md`.
//!
//! [`Parser::skip_balanced`] and [`Parser::verbatim_since`] are the
//! primitives: skip to the matching closer, then cut the bytes since a mark.
use super::*;
impl<'a> Parser<'a> {
/// A block kept byte-for-byte: the keyword at the cursor through the
/// matching `close`, its `: label` included.
///
/// The scan counts its own opener, so a `checker` written inside a
/// `checker` — the only one of the five that may nest (IEEE 1800 §17.1) —
/// closes on the right keyword. A `;` after the closer is left where it
/// is: none of the five takes one, so it is the null item it looks like
/// and the `empty-item` lint gets to say so.
pub(super) fn parse_opaque_block(&mut self, close: &str) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
let open = self.bump().text;
let mut depth = 1usize;
while !self.at_eof() {
let t = self.cur();
if t.is_kw(close) {
depth -= 1;
if depth == 0 {
break;
}
} else if t.is_kw(&open) {
depth += 1;
}
self.bump();
}
self.expect_closer(close)?;
self.parse_label()?;
Ok(self.verbatim_since(start, col))
}
/// An item kept byte-for-byte that ends at its own `;`: the `library
/// lib_name file_path, ...;` line a library map file is made of (IEEE
/// 1800 §33.3), and the `specparam` spelling
/// [`Parser::parse_specparam`] could not read.
pub(super) fn parse_opaque_line(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
self.bump();
self.skip_to_semi()?;
Ok(self.verbatim_since(start, col))
}
/// `specparam [range] name = constant_expression {, ...};` (IEEE 1800
/// §3.12).
///
/// A specify parameter is a declaration with a `localparam`'s shape, so it
/// becomes the same [`ParamDecl`] node — which is what makes the `tRISE`
/// of a vendored cell model hover, resolve and complete. The one spelling
/// that does not fit is the `PATHPULSE$a$b = (reject, error);` form, whose
/// value is a pair rather than an expression; that one rewinds and is kept
/// verbatim, the way a constraint body the grammar does not know is.
pub(super) fn parse_specparam(&mut self) -> PResult<ItemKind> {
let mark = self.rewind_mark();
match self.parse_specparam_decl() {
Ok(decl) => Ok(ItemKind::ParamDecl(decl)),
Err(_) => {
self.rewind_to(mark);
self.parse_opaque_line().map(ItemKind::Verbatim)
}
}
}
fn parse_specparam_decl(&mut self) -> PResult<ParamDecl> {
let kw = self.bump().text;
let after_kw = self.take_gap();
let ty = self.parse_opt_data_type()?;
let declarators = self.parse_declarators()?;
self.expect_sym(";")?;
Ok(ParamDecl { kw, after_kw, is_type: false, ty, declarators })
}
/// `alias a = b = c;` (IEEE 1800 §10.11) — one bidirectional connection
/// between two or more net lvalues.
///
/// The `=` between the terms is a *separator*, not an operator: no term is
/// the value of any other, which is why they are kept as a list rather
/// than as a nested assignment. How many there are, and whether they are
/// legal lvalues, is a checker's business.
pub(super) fn parse_alias(&mut self) -> PResult<ItemKind> {
self.bump(); // alias
let mut nets = vec![self.parse_expr()?];
while self.eat_sym("=") {
nets.push(self.parse_expr()?);
}
self.expect_sym(";")?;
Ok(ItemKind::Alias(nets))
}
/// True when `expect` at the cursor opens a concurrent `expect` statement
/// (IEEE 1800 §16.17) rather than calling a task named `expect`.
///
/// The two spellings are `expect (property_spec) action_block` and
/// `expect(args);`, and only what stands *between* the parentheses tells
/// them apart. The corpus has 41 of the second — `expect(word1[7:0]);` in
/// picorv32's spiflash testbench — and none of the first, so the word is
/// never reserved and the assertion reading is taken only when the
/// parenthesised run holds something no argument list can: a `##` delay, a
/// `|->` or `|=>` implication, `throughout`, `disable iff`, or a clocking
/// event `@(`. Anything else stays the call it has always been.
///
/// The list is deliberately narrow and its misses are safe: an
/// `expect (done) else $error;` written with a purely boolean property is
/// read as a call, which is the parse error it already was.
pub(super) fn at_expect_statement(&self) -> bool {
if !word_at(self.cur(), "expect") || !self.nth(1).is_sym("(") {
return false;
}
// `scan_matching` answers one past the `)`, and the closer itself can
// hold no operator, so the scan stops before it either way.
let end = self.scan_matching(self.pos + 1, "(", ")");
for i in (self.pos + 2)..end {
let Some(t) = self.tokens.get(i) else { return false };
let next = self.tokens.get(i + 1);
let sequence = match t.kind {
// `|->` and `|=>` are two tokens each: the lexer's operator
// table has no entry for either, deliberately, and adding one
// would buy nothing outside a property.
TokenKind::Symbol => {
t.text == "##"
|| (t.text == "|" && next.is_some_and(|n| n.is_sym("->")))
|| (t.text == "|=" && next.is_some_and(|n| n.is_sym(">")))
|| (t.text == "@" && next.is_some_and(|n| n.is_sym("(")))
}
TokenKind::Ident => t.text == "throughout",
TokenKind::Keyword => t.text == "disable" && next.is_some_and(|n| n.is_kw("iff")),
_ => false,
};
if sequence {
return true;
}
}
false
}
/// `expect (property_spec) action_block`, kept as verbatim source for the
/// reason [`Parser::parse_concurrent_assertion`] gives.
pub(super) fn parse_expect_statement(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
self.bump(); // expect
self.expect_sym("(")?;
self.skip_balanced("(", ")")?;
self.skip_action_block()?;
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.
pub(super) 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.
pub(super) 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 }
}
/// Consume everything through the next `;` at bracket depth zero.
///
/// Bracketed runs are skipped whole, so a `;` written inside a
/// `dist { ... }` set — or inside a library map's `-incdir` list — does
/// not end the scan early.
pub(super) fn skip_to_semi(&mut self) -> PResult<()> {
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(";") {
return Ok(());
} else {
self.bump();
}
}
}
}
@@ -0,0 +1,538 @@
# Decomposition — Lane A, `vlog_parser`
## Goal
Apply the file-size rule (CLAUDE.md "File and function size") to the two
files of `vlog_parser` over 1 200 lines: `src/parser.rs` (8 786 production
lines + 5 044 test lines, one 8 100-line `impl Parser` block) and
`src/ast.rs` (3 313 lines). Each becomes a module directory whose files a
reader can describe in one sentence and whose boundaries match the grammar
domains feature lanes are cut by, so that two lanes touching different
domains no longer collide in one file. The split is a **pure move**: no
behaviour change, no renamed public item, every public path preserved by
re-exports, doc comments travelling with their items, the test count
unchanged, and `--stdout` output byte-identical to the v0.33.0 baseline over
the corpus and OpenTitan. TODO.md §28, Lane A.
## Assumptions
- The proof of a pure move is the existing gates — per-binary test counts
equal to the baseline, corpus and OpenTitan byte-identity against
`/tmp/lucisv-0.33.0-baseline`, the `cargo doc` item list unchanged — not
new tests. No test was written; none was dropped.
- Methods that one grammar file calls on another are `pub(super)`: visible
inside the `parser` module tree (siblings and the `tests` subtree), invisible
outside the crate. This adds no public path. The one public method,
`Parser::parse_expr`, stays `pub`.
- The split is by *what a reader looks for*, not by the old section
comments: where a section held a helper every file uses (`gap_before`,
`expect_stmt_semi`, `take_raw_text`, `skip_balanced`), the helper moved to
the file that owns the concept, not the file it happened to sit in.
- `rustfmt` re-indents the moved tests (they came out of a `mod tests { }`
block) and, because they are now four columns narrower, joins a handful
of lines that used to wrap. String literal contents are untouched — the
spans the tests assert are computed from those literals, and all 309 pass.
- The 300–600 target is a target: six production files are over 600 and
one is over 800 (§Work log, "files over the target"), each with the
reason written there.
## Handshakes
Consumed:
- `crate::ast::*`, `crate::span::TextRange`, `crate::token::{Comment, Token,
TokenKind}`, `crate::lexer::tokenize` — unchanged.
- `crate::lib` calls `parser::error_file` (moved to `parser/recover.rs`,
re-exported `pub(crate) use recover::error_file;` from `parser/mod.rs`).
Promised (unchanged, verified by the `cargo doc` item diff and by every
other crate compiling untouched):
- `vlog_parser::parser::{parse, parse_tolerant, ParseError, ParseDiagnostic,
Parser, MAX_NESTING_DEPTH, MAX_CHAIN_LENGTH, PARSE_STACK_SIZE}` and
`Parser::parse_expr` — same names, same signatures, same paths.
- `vlog_parser::ast::*` — every node type is re-exported from `ast/mod.rs`
(`pub use decl::*;` etc.), so `vlog_parser::ast::Expr` is unchanged and
rustdoc inlines the items at the same paths (the submodules are private).
Requests to other lanes: none. Nothing outside `crates/vlog_parser` changed.
## Status / TODO
- [x] `git mv src/parser.rs src/parser/mod.rs`, `git mv src/ast.rs src/ast/mod.rs`
- [x] `parser/` carved into 19 files (18 in the first pass, `keyword_stmt.rs` in the rework), `ast/` into 8, tests into `parser/tests/` (14 files)
- [x] Every original line assigned to exactly one file; concatenation proof
(see Work log) passed for both carves
- [x] Cross-file methods `pub(super)`; cross-file free items imported explicitly
- [x] Module-level doc per new file; module map in `parser/mod.rs` and `ast/mod.rs`
- [x] `cargo fmt -p vlog_parser`, `cargo clippy --all-targets --workspace` (0 warnings)
- [x] `cargo test -p vlog_parser`: 360 / 0 (2 ignored) / 26 / 22 / 18 / 6 / 18 — equal to baseline
- [x] `cargo test --workspace`: every binary's count equal to baseline
- [x] `cargo doc -p vlog_parser` item list diffed: no path changed
- [x] Byte-identity: corpus, 0 differing; OpenTitan `hw/`, 0 differing; exit codes identical
- [x] TODO.md §28 Lane A ticked
- [x] Rework after QA (2026-09-02): `parse_keyword_stmt` moved to `parser/keyword_stmt.rs`; README counts re-measured; all gates re-run on the final tree
## Work log
### 2026-09-02 — the carve
**Method.** The pristine files were `git mv`'d first so history follows
`parser/mod.rs` and `ast/mod.rs`. The carve itself is a manifest of
line-range segments — every line of the original assigned to exactly one
destination — executed by a script that *refuses to write* unless the
segments, concatenated in original order, reproduce the original byte for
byte (`scratchpad/carve_parser.py`, `carve_ast.py`; both passed). This is a
deliberate deviation from "use the Edit tool to remove text": retyping
13 928 lines through Edit cannot be verified, a range manifest can, and the
concatenation check is a stronger guarantee than either. The only text that
is not a verbatim segment: each file's `//!` header and `use` lines, the
`impl<'a> Parser<'a> { … }` wrapper per file, `pub(super)` on the items
another file uses — measured on the final tree with `grep -E '^ pub\(super\) fn '`
and its free-item / struct-field twins: 149 methods, 5 free functions, 13
structs, consts and fields (the first draft of this log said 142 + 11; QA
re-counted, and the rework added the six `stmt.rs` productions the moved
table calls) — four signatures `rustfmt` re-wrapped because `pub(super) `
pushed them past 100 columns (`parse_dist`, `take_list_directives`,
`parse_expr_list`, `split_conditional_item`), and the comment edits listed
under "comment-only changes".
**Pinned test counts** (`cargo test -p vlog_parser`, before = after):
lib unittests 360, `census` 0 (2 ignored), `defines` 26, `error_recovery`
22, `fragments` 18, `null_items` 6, `spans` 18, doctests 0. The 309 `#[test]`
fns of the old `mod tests` are the 309 in `parser/tests/`. Function count:
288 `impl Parser` methods before, 288 after (plus the two `Display::fmt`
impls that the after-census now also sees) — nothing merged, nothing split.
**`parser/` module map** (original `parser.rs` line ranges → file; the
one-sentence description is the file's `//!` doc):
| file | production lines | from `parser.rs` lines |
|---|---:|---|
| `mod.rs` — `Parser`, budgets, `Rewind`, `parse`/`parse_tolerant`, errors, shared name/label helpers | 476 | 1–82, 161–163, 170–237, 274–402, 503–524, 683–703, 705–728, 1534–1553, 1581–1637 |
| `cursor.rs` — token cursor, spans, `expect`/`eat`, comment plumbing | 364 | 729–808, 967–1158, 1236–1245, 1380–1387, 1504–1533, 1638–1659, 2455–2462 |
| `recover.rs` — tolerant-mode error recovery, `error_file` | 217 | 95–131, 477–497, 809–966 |
| `directive.rs` — `` `ifdef `` tracking, list directives, macros, fragment mode | 410 | 264–273, 403–476, 563–572, 660–682, 1159–1235, 1388–1503, 1764–1808, 6726–6764 |
| `split.rs` — conditional-directive split recovery | 471 | 573–659, 4832–5209 |
| `verbatim.rs` — vendor/formal blocks kept as bytes; `skip_balanced`, `verbatim_since`, `skip_to_semi` | 227 | 3719–3745, 4674–4831, 5225–5261 |
| `item.rs` — file and item loops, keyword → item dispatch, member qualifiers, packages, imports, DPI, generate | 726 | 83–94, 132–150, 1554–1580, 1687–1763, 1809–2226, 6834–6991 |
| `module.rs` — module/interface/program header, parameter ports, ports, modports, clocking | 542 | 238–249, 5262–5788 |
| `decl.rs` — data types, dims, type params, declarators, params, typedef/enum/struct | 470 | 1660–1686, 5210–5224, 5789–6204 |
| `tf.rs` — function, task, `let` | 245 | 250–253, 6992–7230 |
| `instance.rs` — `assign`, drive strengths, delays, `bind`, instantiations, connections, gates | 593 | 164–169, 498–502, 6205–6725, 6765–6780, 6793–6833 |
| `stmt.rs` — statements | 494 | 254–263, 2429–2454, 7231–7373, 7690–7998 |
| `keyword_stmt.rs` — the keyword → statement dispatch table | 337 | 7374–7689 |
| `expr.rs` — implication → ternary → binary → unary → postfix | 505 | 7999–8500 |
| `primary.rs` — `parse_primary`, casts, patterns, stream concat, element/argument lists | 467 | 1246–1379, 6781–6792, 8501–8809 |
| `class.rs` — class header, `extends`, constraints, `with` constraints | 659 | 2227–2428, 2463–2908 |
| `covergroup.rs` — covergroups, coverpoints, crosses, bins | 621 | 549–562, 2909–3508 |
| `assertion.rs` — concurrent assertions, action blocks, property/sequence decls, `expect`, `default disable iff` | 445 | 151–160, 3509–3718, 4458–4673 |
| `sva.rs` — the property/sequence expression grammar | 737 | 525–548, 3746–4457 |
Lines 704 (`impl<'a> Parser<'a> {`) and 8810 (`}`) became the per-file
wrappers; 8811–8815 (`#[cfg(test)] mod tests { use … }`) became
`parser/tests/mod.rs`'s head and `#[cfg(test)] mod tests;` in `mod.rs`;
13928 (`}`) was dropped.
**Tests** (`parser/tests/`, 5 086 lines, 309 tests): `mod.rs` (shared
helpers `parse_ok`, `words`, `texts`, `parse_err`, `module_of`, `class_of`,
`initial_stmts`), `limits`, `comments`, `items`, `module`, `instance`,
`decl`, `stmt`, `expr`, `directive`, `split`, `class`, `sva`, `covergroup` —
each named for the grammar file it exercises (`limits` = the budgets in
`mod.rs`/`cursor.rs`, `comments` = the comment plumbing in `cursor.rs`,
`items` = `item.rs` + `verbatim.rs`). Tests were assigned by what they
assert, not by the old section they sat in — e.g. the list-directive tests
that lived under the old "Error recovery" and "ANSI first port" headings
are in `directive.rs`.
**`ast/` module map** (original `ast.rs` line ranges → file):
| file | lines | from `ast.rs` lines |
|---|---:|---|
| `mod.rs` — `Name`, `ScopeSeg`, `LabelComments`, `Qualifier`, `Meta`, `RawText`, `ListDirective`, `MacroCall`, `SourceFile`, `Fragment`, `Item`, `ItemKind`, import/DPI payloads, `size_pins` test | 485 | 1–108, 124–451, 3296–3312 |
| `module.rs` | 550 | 452–603, 874–909, 964–1232, 1313–1399 |
| `decl.rs` | 416 | 604–873, 1400–1540 |
| `stmt.rs` | 407 | 109–123, 910–963, 1541–1874 |
| `expr.rs` | 444 | 1875–2313 |
| `class.rs` | 294 | 1233–1312, 2314–2525 |
| `covergroup.rs` | 407 | 2526–2932 |
| `sva.rs` | 363 | 2933–3295 |
**Cut points that differ from the §28 plan, and why.**
- `cursor.rs` is separate from `mod.rs`. §28 had the cursor and comment
plumbing in `mod.rs`; together with the types, budgets and entry points
that is ~790 lines, the second-largest file of the split. The cursor is
one layer every grammar file drives and no grammar file changes, which is
exactly a one-sentence module; `mod.rs` is now "state, budgets, entry
points and the two helper families every file shares (scoped names,
labels)".
- `split.rs` is separate from `directive.rs` (§28: one `directive`
module). The conditional-directive split recovery is a *recovery* —
it runs only after a parse failure — and at 470 lines it would have
pushed `directive.rs` to ~900. A `directive-split` lane touches
`split.rs` alone; a macro or fragment lane touches `directive.rs` alone.
- `verbatim.rs` (§28: "recovery/opaque capture") holds the vendor/formal
items *and* the capture primitives (`skip_balanced`, `verbatim_since`,
`skip_to_semi`) that every speculative parse falls back to. Recovery
proper stays in `recover.rs`: the two are different things — one is what
lucisv does when the grammar refuses, the other what it does when the
grammar deliberately does not model.
- `tf.rs` is separate from `decl.rs`. Folding function/task/let into
`decl.rs` gives 700 lines and a description with an "and"; a function-port
lane touches `tf.rs` alone.
- `expr.rs` / `primary.rs` (§28: one `expr`). 950 lines in one file; the
operator grammar and the leaves are two things a reader looks for
separately. The element/argument list helpers (`parse_expr_item`,
`parse_expr_list`, `parse_named_arg`, `parse_value_range`) sit with the
leaves because concatenations, calls and patterns are their callers.
- `class.rs` / `covergroup.rs` and `assertion.rs` / `sva.rs` (§28: one
`class`, one `sva`): 1 285 and 1 160 lines respectively as single files.
- Generate constructs went to `item.rs`, not `module.rs`: a generate block
is an item list and its entry is the item dispatch; a generate lane then
touches one file.
- Shared vocabulary stayed where its users are: `TYPE_KEYWORDS`,
`NET_KEYWORDS`, `ASSIGN_OPS`, `ItemMark`, `word_at`, `split_label`,
`take_since` in `mod.rs` (used by three or more files); `MEMBER_QUALIFIERS`
with `member_head`/`take_member_prefix` in `item.rs` (imported by
`decl.rs`); `Harvested` with `take_list_directives` in `directive.rs`;
`ForeachTarget` in `stmt.rs` (imported by `class.rs`); `ParamPortList` in
`module.rs`; `fragment_file`/`is_prelude` in `directive.rs` (imported by
`item.rs`); the three `*_conditional` predicates in `directive.rs`
(imported by `split.rs`).
**Files over the 600 target** (the rule says consider splitting at 800;
nothing is over 1 200):
- `stmt.rs` was 817 in the first pass, 316 of them the `parse_keyword_stmt`
dispatch table. QA recommended and the lead adopted moving the table to
its own file (§rework below): `stmt.rs` is now 494 and
`keyword_stmt.rs` 337.
- `sva.rs` 737: one precedence-climbing grammar, 24 productions; "800 lines
of grammar productions read more easily than 250 lines of state".
- `item.rs` 726: the 167-line `parse_keyword_item` dispatch table plus the
small items that have no home of their own.
- `class.rs` 659, `covergroup.rs` 621, `instance.rs` 593: each one grammar.
**Longest functions, before → after** (≥ 80 lines; none split, none merged):
`parse_keyword_stmt` 316 (dispatch table, stays whole — doc added; its own
file since the rework),
`parse_keyword_item` 167 (dispatch table, stays whole — doc added),
`parse_primary` 149 (a `match` over token kind and symbol; every arm short
enough to read in place, and under the 150 line at which the rules allow a
split — left whole), `parse_postfix_inner` 139, `parse_instantiation` 97,
`parse_port_list` 91, `parse_connection` 91, `skip_action_stmt` 80,
`parse_binary_inner` 80. There is no 316-line `fmt` impl in this crate.
**Comment-only changes** (no code line changed):
- The old `// ---- Section ----` banners that would have stood as the first
thing in a new file were removed where the file's `//!` doc now says the
same (the banner text of "Error recovery", "The SVA grammar",
"Vendor and formal collateral" and "Conditional-directive split recovery"
*became* those files' docs, verbatim). Banners that still separate
sub-sections mid-file (`item.rs` DPI / generate, `cursor.rs` Spans,
`decl.rs` Declarations, `assertion.rs` SVA declarations, `ast/class.rs`
Constraints) stayed.
- `parser/mod.rs`: the doc comment of `push_scope_segment` had been glued
above `push_path_segment` (a trunk doc bug — one `///` block ran into the
next with no blank line). Moved to its own function. This is the one
place a comment did not travel with the item it was attached to, because
it was attached to the wrong one.
- `parse_keyword_stmt` and `parse_keyword_item` gained a one-paragraph doc
saying they are dispatch tables and stay whole.
- Module-level `//!` docs on every new file; a layout table in
`parser/mod.rs` and `ast/mod.rs`; a `//!` on `parser/tests/mod.rs`.
**Gates.** `cargo fmt -p vlog_parser --check` clean; `cargo clippy
--all-targets --workspace` 0 warnings; `cargo test --workspace` per-binary
counts equal to the baseline (48 `test result` lines, diff with the timing
stripped: empty). `cargo doc -p vlog_parser --no-deps` item list (every
`.html` under `target/doc/vlog_parser`) diffed against the baseline build:
0 paths removed, 0 changed; the only additions are the 127 redirect stubs
rustdoc writes at `ast/<submodule>/…` for items re-exported from a private
module, each a `<meta http-equiv="refresh">` to the unchanged
`ast/struct.X.html`. rustdoc's four `private_intra_doc_links` warnings
(`parser` module doc → `Parser::bump`/`enter`/`leave`, and `body` →
`join_continuations`) are trunk's and the worktree shows the same four; the
fifth this lane briefly introduced (`Rewind`) was removed. Byte-identity (`--stdout`, lane release binary vs
`/tmp/lucisv-0.33.0-baseline`, `scratchpad/byte_identity.sh`): corpus 860
files, 0 differing, 0 exit-code mismatches; OpenTitan `hw/` 3 947 files,
0 differing, 0 exit-code mismatches; `git -C opentitan status --porcelain`
before and after: the same three pre-existing modified files
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
`hw/top_earlgrey/ip/ast/rtl/ast.sv`), nothing else.
### 2026-09-02 — final pass
After the last comment-only edits (the dispatch-table docs, the `Rewind`
link, the layout tables) the gates were run once more on the final tree:
fmt check, clippy, a fresh release build, and both byte-identity runs
against that binary — results recorded in the Status list above. The
scratchpad copy of the two pristine files (`parser.orig.rs`, `ast.orig.rs`)
and the carve scripts are not part of the tree; `git show 159f6a0:crates/
vlog_parser/src/parser.rs` is the same text.
### 2026-09-02 — rework after QA (MEDIUM + three LOW)
**`parse_keyword_stmt` → `parser/keyword_stmt.rs`.** The 316-line
keyword → statement dispatch table (original `parser.rs` 7374–7689, with
the doc added in the first pass) moved out of `stmt.rs` into a sibling file
as one `impl Parser` block, by the same range method with the same proof
(kept + removed == the pre-move `stmt.rs`, byte for byte). Nothing else
moved with it: every function the table calls is a statement production
(`parse_if_stmt`, `parse_case_stmt`, `parse_case_body`,
`parse_assign_or_expr_stmt`) or a shared helper (`expect_stmt_semi`,
`eat_stmt_semi`), and those belong to `stmt.rs` — they are the grammar,
the table is how a keyword reaches it. Those six became `pub(super)` and
`parse_keyword_stmt` itself became `pub(super)` (called from
`parse_stmt_kind`); `keyword_stmt.rs` imports `super::stmt::ForeachTarget`
for the `foreach` arm's destructuring. `stmt.rs` 494 lines, one sentence
without an "and"; `keyword_stmt.rs` 337, its `//!` says it is a table and
why it is alone; the layout table in `parser/mod.rs` gained the row.
**`parse_keyword_item` stays in `item.rs`.** The argument does not apply as
cleanly: the item table is 167 lines of a 726-line file (a quarter, not a
half), and it is one of three functions that together make one decision —
`parse_item_kind` → `parse_keyword_item` / `parse_ident_item` — so moving
the middle one out would spread a single decision over two files. The
item dispatch also *is* what `item.rs` is for ("from the file down to one
item"); the statement dispatch was a second thing in a file about
statements.
**Counts re-measured** (QA's independent numbers adopted): four `rustfmt`
re-wrapped signatures, not three; four rustdoc `private_intra_doc_links`
warnings on trunk and in the worktree, not five; `pub(super)` on 149
methods + 5 free functions + 13 structs/consts/fields on the final tree
(the draft's 142 + 11 was the carve script's own count before the fix-ups
and the rework). The tables above are updated to the final tree.
**Rework gates, on the final tree** (after the move and the README edits):
`cargo fmt -p vlog_parser --check` clean; `cargo clippy --all-targets
--workspace` 0 warnings; `cargo test --workspace` 48 `test result` lines,
identical to the baseline with timing stripped (`vlog_parser` lib 360, the
rest unchanged); fresh `cargo build --release -p lucisv`, then
byte-identity (`--stdout`) against `/tmp/lucisv-0.33.0-baseline`: corpus
860 files, 0 differing, 0 exit-code mismatches; OpenTitan `hw/` 3 947
files, 0 differing, 0 exit-code mismatches; `git -C opentitan status
--porcelain` afterwards shows only the three pre-existing modified files.
## QA log
### 2026-09-02 — independent verification
**Method.** Worked only in this worktree; built a throwaway baseline
worktree at `git worktree add <scratch>/baseline-159f6a0 159f6a0` for every
comparison, removed after. Never touched the dev worktree's tracked files
(the one exception below is this QA log entry).
**1. Gates.**
`cargo fmt -p vlog_parser -- --check`: clean, no output.
`cargo clean -p vlog_parser && cargo clippy --all-targets --workspace`
(forced full rebuild, not the cached 0.12s no-op): 0 warnings.
`grep -rn "#\[allow" crates/vlog_parser/src/`: zero hits, in this lane and
in trunk's `parser.rs`/`ast.rs` — no new `#[allow]`, none existed before.
`cargo test --workspace --no-fail-fast`: 48 `test result:` lines, 3215
passed / 0 failed / 40 ignored — diffed byte-for-byte (timing stripped)
against a fresh `cargo test --workspace` on the baseline worktree:
identical, same order. `vlog_parser`'s own counts confirmed line-by-line:
unittests 360, `census` 0 (2 ignored), `defines` 26, `error_recovery` 22,
`fragments` 18, `null_items` 6, `spans` 18 — matches the pinned table
exactly. `parser/tests/*.rs`: 309 `#[test]` fns, matching.
`cargo doc -p vlog_parser --no-deps`: 4 `private_intra_doc_links`
warnings, identical text to a same-flag build on the baseline worktree
(the baseline itself has 4, not 5 — see finding below).
`git status --porcelain`: only `TODO.md`, `crates/vlog_parser/src/**`
and `docs/features/decomposition-parser/**` changed; the `TODO.md` diff
touches only the Lane A line (ticked, one line added citing this README).
`git diff 159f6a0 -- crates/vlog_parser/src/lexer.rs crates/vlog_parser/src/token.rs`:
empty, confirmed untouched.
**2. Pure move, mechanically.** Extracted `git show 159f6a0:.../parser.rs`
lines 1–8810 (the production part, before `#[cfg(test)] mod tests {` at
8811) and `ast.rs` whole, concatenated the 18 new `parser/*.rs` and 8 new
`ast/*.rs` files in the README's stated order, normalized leading/trailing
whitespace, and took a line multiset diff (Python `Counter`). `parser`:
209 distinct lines only-in-orig / 342 only-in-new (551 total instances).
Every one of the 209 orig-only lines is explained: 155 gain a
`pub(super)`/`pub` prefix in the new file (matched by string concatenation),
50 are section-banner comments that became a file's `//!` doc verbatim,
and 4 are signatures rustfmt rewrapped onto multiple lines (below). Every
one of the 342 new-only lines is: 161 visibility-prefixed
duplicates of the above, 145 `//!` module docs, 34 `impl<'a> Parser<'a> {`
wrapper braces, 21 `use`, 19 `mod`/`pub use`, 12 `///` doc comments, and 16
continuation lines of the 4 rewrapped signatures. Nothing left over.
`ast`: 3 orig-only lines (all banner comments) and 46 new-only (32 `//!`
docs, 14 `mod`/`pub use`, 7 `use`) — cleanly explained, and ast needs no
`pub(super)` (its items were already `pub`, confirmed: `grep -rn
"pub(super)" crates/vlog_parser/src/ast/*.rs` is empty).
**The one doc re-attachment**: verified directly — trunk's `parser.rs`
1596–1609 glues the `push_scope_segment` doc (describing the `::` joiner)
above `push_path_segment`, leaving `push_scope_segment` (1618) undocumented;
the worktree's `parser/mod.rs` has the doc correctly above each of its own
function.
**Signature census** (regex + paren-depth scan, from scratch, independent
of the dev's method): 306 `fn` signatures in `parser.rs`'s production part,
306 in the concatenation, and the *only* 4 mismatches are the same 4
rewrapped signatures (`take_list_directives`, `parse_expr_list`,
`parse_dist`, `split_conditional_item` — all three original one-line
signatures pushed past 100 columns once `pub(super) ` (11 chars) is
prepended, e.g. 98→109). `ast.rs`: 23 signatures before and after, 0
mismatches. No signature added, removed, or split, in either file.
**Finding (LOW)**: the work log says "three signatures `rustfmt`
re-wrapped"; it is four (listed above) — an off-by-one in the narrative,
not in the carve itself.
**`pub(super)` count (against the dev's 142 methods + 11 free items)**:
counted 147 `pub(super) fn` (not 142) and, outside `fn`, 3 `pub(super)
struct` (`Harvested`, `ParamPortList`, `ForeachTarget`), 1 `pub(super)
const` (`MEMBER_QUALIFIERS`) and 9 `pub(super)` struct fields — 13 non-fn
items by the broadest reading (or 4 if "free items" means only top-level
struct/const, excluding fields), none of which is 11 under any reading I
tried. Total `pub(super)` markers: 160. **Finding (LOW)**: the pinned
142+11 undercounts the actual 147+13(or 4); every one of the visibility
additions found is accounted for as a plain visibility-keyword change
(the allowed category), so this does not affect the pure-move verdict,
but the README's counts should be corrected.
**3. Public API.** `cargo public-api` is not installed; used `cargo doc`
page-list diff instead (find every `.html` under `target/doc/vlog_parser`,
diff against a same-flag baseline build): 0 removed, 0 changed, 127 added
— all 127 confirmed to be `<meta http-equiv="refresh">` redirect stubs
(spot-checked `ast/class/struct.ClassDecl.html`) pointing at the unchanged
`ast/struct.X.html`. Spot-checked 10 promised paths (`ast::Expr`,
`ast::ItemKind`, `parser::Parser`, `parser::parse`, `parser::parse_tolerant`,
`parser::ParseError`, `parser::ParseDiagnostic`, the three `MAX_*`/`*_SIZE`
constants) byte-identical to baseline after stripping `href="..."`
attributes (only the `Source` line-number links differ, as expected for
code that moved files). `parser`/`ast` submodules are `mod` (private), not
`pub mod`, confirmed by reading `mod.rs` — no new public path. The full
workspace build (§1) is the proof every other crate compiles unchanged;
all of `vlog_semantic`, `vlog_formatter`, `vlog_linter`, `vlog_refactor`,
`lucisv`, `lucisv_server`'s tests passed against this tree with 0 changes
needed in those crates.
**4. Byte-identity, independently.** Built `cargo build --release -p
lucisv` in both this worktree and a fresh baseline worktree at `159f6a0`
(not the pre-supplied `/tmp/lucisv-0.33.0-baseline`, to keep the baseline
independent of anything the dev might have produced; both report `lucisv
0.33.0`). Corpus: `find corpus -name "*.sv" -o -name "*.v" -o -name
"*.svh"` → 860 files (matches). Ran `--stdout` through both binaries per
file: 0 differing, 0 exit-code mismatches. OpenTitan `hw/`: `find -type f`
(no `-L`) → 3947 files, matching the pinned count exactly (a naive
recursive walk that follows symlinks finds 3979 — the 32-file gap is
`top_englishbreakfast`'s symlinked duplicates of earlgrey/darjeeling files;
re-ran against the symlink-following 3979-file set too, still 0 diffs, so
this doesn't change the verdict, just a note on how to reproduce the exact
3947). 0 differing, 0 exit-code mismatches either way.
`git -C /Users/guoliangchen/repo/opentitan status --porcelain` checked
before and after both runs: unchanged, exactly `hw/ip/aes/dv/tb/tb.sv`,
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`,
nothing else — no write, read-only confirmed.
**5. Size rule.** `wc -l` on every new file matches the README's tables
exactly, both `parser/*.rs` (18 files) and `ast/*.rs` (8 files) — no
discrepancy. Longest-function spot check: `parse_keyword_stmt` 316,
`parse_keyword_item` 167 confirmed by direct inspection; `parse_primary`
149 confirmed by locating its enclosing lines (9–157) — a first attempt
with an automated brace-matcher misreported 142 because of a brace inside
a token the script didn't recognize as a string/char boundary; manual
line-counting confirms the README's 149, one line under the 150 threshold
the write-up leans on. **`stmt.rs` split recommendation (MEDIUM, per the
brief's request to judge this)**: yes — `stmt.rs` at 817 is over 800
mainly because of `parse_keyword_stmt` (316 lines, ~39% of the file);
moving it to a sibling (e.g. `parser/stmt/keyword.rs`) leaves the
statement-grammar file at ~500 lines (squarely in the 300–600 target,
consistent with how `item.rs` kept its own smaller 167-line table inline)
and a `keyword.rs` a reader names as "the keyword → statement dispatch
table" — both easier to name in one sentence than the current combined
file. Not done, per instructions; recorded as a recommendation for the
lead. No file is over 800 without the file already carrying a written
reason in the Work log (`stmt.rs`, `sva.rs`, `item.rs`, `class.rs`,
`covergroup.rs`, `instance.rs`), and none is within reach of 1200. Every
new file's `//!` doc was read: none needs an "and" to describe two
unrelated responsibilities — the lists inside several docs (`item.rs`,
`instance.rs`, `assertion.rs`) name sub-parts of one grammar domain, not
two different domains stitched together, so no MEDIUM beyond the
`stmt.rs` one above.
**6. Tests regrouping.** Name-level diff: extracted all 309 `#[test]` fns
from trunk's `mod tests { ... }` block and all 309 from `parser/tests/*.rs`
by a custom Rust-string/char/comment-aware scanner (a first attempt using
naive brace-counting broke on Verilog snippets in the test bodies
containing `{`/`}`); 0 missing, 0 added — same 309 names, no renames.
Body diff after stripping all whitespace outside string/char literals and
removing comments (token-level, not just whitespace-collapse): 11 of the
309 differ, and every one is `rustfmt` re-flowing a call it now fits on
one line where it used to wrap (dropping/adding a trailing comma after a
single argument, or adding/removing braces around a one-line match-arm
body) — spot-checked all 11 by hand, e.g. `exports_split_into_dpi_and_
package_re_exports`: the `format!(...)` call's arguments are character-for
-character identical, only whether it's `{ format!(...) }` or bare
`format!(...)` as the match arm changed, because the file is now 4 columns
shallower per the documented Assumption. No test's assertions, inputs, or
expected values changed. Spot-checked 5 random test → file placements:
`a_bind_instance_may_be_a_hierarchical_path`→`instance.rs`,
`the_option_assignment_slots_keep_their_comments`→`covergroup.rs`,
`a_written_empty_parameter_list_is_distinguishable_from_none`→`module.rs`,
`the_header_keeps_the_comments_written_around_its_name`→`class.rs`,
`a_randomize_with_block_is_parsed_and_the_call_is_not`→`class.rs` — every
one lands in the file matching its subject.
**7. Docs.** All required README sections present and non-empty
(Goal/Assumptions/Handshakes/Status-TODO/Work log/QA log/Review reserved).
Spot-checked 5 line ranges against `git show 159f6a0`: `recover.rs`
95–131 (`SYNC_CLOSERS`/`SYNC_OPENERS`), `tf.rs` 250–253 + 6992/7230
(`TfBody`, the functions-and-tasks banner, closing label parse), and both
`covergroup.rs` 549–562/2909–3508 boundaries plus `ast/covergroup.rs`
2526–2932 and `ast/sva.rs` 2933–3295 — all five match the stated original
line content exactly. The "range manifest with a concatenation proof"
method is described well enough that I reproduced an equivalent check
independently (Python `Counter` multiset diff, §2 above) without needing
the dev's own scripts, and got the same result.
**Findings summary.**
- LOW: work log says "three signatures" rustfmt re-wrapped; actually four
(`take_list_directives`, `parse_expr_list`, `parse_dist`,
`split_conditional_item`).
- LOW: work log says rustdoc's trunk baseline has "five"
`private_intra_doc_links` warnings; a from-scratch build of 159f6a0 with
the same flags shows four, matching the worktree's four exactly (same
text) — the delta-of-one-removed ("Rewind") claim doesn't reconcile
against what trunk actually emits, but the outcome (4 == 4, identical
text) is correct and byte-checked.
- LOW: `pub(super)` count is 147 methods + 13 non-fn items (3 structs, 1
const, 9 fields) by the broadest reading — not the pinned 142 + 11.
Every addition found is a plain visibility-keyword change (the allowed
category); this doesn't change the pure-move verdict.
- MEDIUM (recommendation, not a defect): split `parse_keyword_stmt` out of
`stmt.rs` into its own file; see §5.
- No HIGH or CRITICAL findings: 0 changed code lines beyond the allowed
categories, 0 public paths removed/renamed, 0 test count drop, 0 test
body changed beyond `rustfmt` reflow, 0 corpus/OpenTitan output diffs, 0
exit-code mismatches, OpenTitan tree unmodified beyond its 3 pre-existing
files.
**Verdict: PASS.** The three LOW findings are narrative/count corrections
the dev should make in the Work log; the one MEDIUM is a recommendation
for a future pass, explicitly not to be acted on now. Nothing here forces
rework.
## Review
**2026-09-02 — lead.** Accepted; merged onto master beside lane B. The
range-manifest method — refuse to write unless the segments concatenate
back to the original byte for byte — is the right way to carve fourteen
thousand lines, and it is why QA's from-scratch multiset and signature
census found only visibility keywords, `use` lines and rustfmt rewraps.
Nineteen parser files and eight AST files a reader can name in one
sentence; the cut points that differ from the plan (`cursor` out of
`mod`, `split` beside `directive`, `expr`/`primary`, `class`/
`covergroup`, `assertion`/`sva`) each carry their reason. QA's one
MEDIUM taken at review: `parse_keyword_stmt` now stands alone in
`keyword_stmt.rs`, so `stmt.rs` is "statements" with no "and";
`parse_keyword_item` stays in `item.rs` for the reason the dev gives.
The three count nits fixed. Every public path unchanged, per-binary test
counts identical, 4 807 files byte-identical — the lead re-ran the
multiset check on the final tree. Files over 600 (`sva`, `item`, `class`,
`covergroup`) keep their written reasons and are the next lane's problem
if they grow.