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:
1 parent
159f6a0bd8
commit
9b93f33ae3
45 files changed
+17999
-17241
No files matched your search
@@ -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,
|
||||
}
|
||||
@@ -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>>,
|
||||
}
|
||||
@@ -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>,
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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>());
|
||||
}
|
||||
}
|
||||
@@ -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>,
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
Reference in new issue
Block a user