Coverage gaps L3, L6, L10: six language shapes, randsequence as real nodes, an opt-in uvm_field_* indent

TODO §54 (docs/features/coverage-gaps-l); closes docs/coverage_gaps.md
L3, L6 and L10. The first dev stalled under machine load; a second
finished from the tree.

54.1 `->>` with optional delay or event control (`StmtKind::EventTrigger`),
stream `with [range]` (`ExprKind::StreamWith`), the LRM's other
`casting_type`s, drive strength on a net declaration (`DataDecl::strength`,
whose comment slots also fix a pre-existing refusal on an `assign` with
a comment before its strength), `let` at statement position
(`StmtKind::Let`), and `#(min:typ:max)` clocking skews — `ClockingSkew`
as the LRM's two alternatives, `edge [delay]` | `delay` (review rework of
QA's HIGH). Comment slots added to `let`, stream concatenations and the
clocking grammar; the RTL gap fuzzer at 505 gaps, zero failing.
54.2 `randsequence` (it was a parse error; the keyword is new):
`RandSequence` → `Production` → `Alternative` → `ProdItem` (ref, block,
if, repeat, case, rand join), code blocks by the statement grammar; one
production per line, alternatives aligned; the LRM's examples as cases.
54.3 `[format] uvm-utils-indent` / `lucisv.format.uvmUtilsIndent`, default
off, tracking nested `_begin`/`_end` pairs; 21 corpus files change with
it on, all idempotent. A short comment-free enum body already one-lines,
so no key was built — the behaviour is pinned. `[format]` table tests
added (review rework). `->>`'s event control is bound through the shared
`bind_timing` (review rework of QA's second HIGH).

0 of 820 corpus files differ from 0.48.x with the key off; the opentitan
sweep is identical; no corpus or opentitan file writes any of the new
shapes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5.1 committed 2026-09-07 01:12:49 -05:00
1 parent e1679bebc5
commit a69a1cb528
69 files changed
+3660 -127

No files matched your search

+13
View File
@@ -340,6 +340,12 @@ pub struct NetDelay {
pub struct DataDecl {
/// Net type (`wire`, `tri`, ...) if any.
pub net: Option<String>,
/// Drive strength: the `(strong0, weak1)` of
/// `wire (strong0, weak1) w = a;` (IEEE 1800 §6.6), read only after a net
/// keyword — the one position the grammar allows it. Carried the way
/// [`ContAssign::strength`] is, and printed between the net keyword and
/// the delay, where the source wrote it.
pub strength: Option<DriveStrength>,
/// Net delay, if any: the `5` in `wire #5 w;` or the `0.1` in
/// `wire [31:0] #0.1 x = y;`.
pub delay: Option<NetDelay>,
@@ -477,6 +483,8 @@ pub struct TaskDecl {
/// growing a near-identical node of their own.
#[derive(Debug)]
pub struct LetDecl {
/// Comments written between the `let` keyword and the name.
pub after_kw: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
@@ -484,7 +492,12 @@ pub struct LetDecl {
/// written when this is true and [`LetDecl::ports`] is empty.
pub has_parens: bool,
pub ports: Vec<ListElem<TfArg>>,
/// Comments written on either side of the `=`, each kept on its own side
/// of it the way a declarator's `eq_comments` are.
pub eq_comments: Box<BinaryComments>,
pub value: Expr,
/// Comments written between the value and the `;`.
pub before_semi: Vec<Comment>,
}
#[derive(Debug)]
+51
View File
@@ -119,6 +119,18 @@ pub enum ExprKind {
/// The stream expressions, carrying their comments the way a
/// concatenation's elements do.
inner: Vec<ExprItem>,
/// The three gaps the two nested brace pairs open. Boxed to keep
/// `Expr` small, as for `TernaryComments`.
comments: Box<StreamComments>,
},
/// `expr with [ range ]` — a stream expression's array range
/// (IEEE 1800 §11.4.14): `{<< {a with [0:3]}}`, `{>> {a with [i+:4]}}`,
/// `{<< {a with [i]}}`. The only `with` whose argument is a bracket
/// rather than a `(` or a `{`, which is what tells it from an array
/// method's iterator argument and from a `randomize` constraint block.
StreamWith {
base: Box<Expr>,
range: Box<StreamRange>,
},
Paren {
inner: Box<Expr>,
@@ -451,6 +463,45 @@ pub struct WithComments {
pub after_kw: Vec<Comment>,
}
/// The gaps of a streaming concatenation's own brackets:
/// `{ /*a*/ << byte /*b*/ { x } /*c*/ }`. The elements inside carry their own
/// comments the way a concatenation's do; these three are what the nesting of
/// the two brace pairs leaves over.
#[derive(Debug, Clone, Default)]
pub struct StreamComments {
/// Between the outer `{` and the `<<` or `>>`.
pub after_open: Vec<Comment>,
/// Between the direction (or the slice size) and the inner `{`.
pub before_inner: Vec<Comment>,
/// Between the inner `}` and the outer `}`.
pub before_close: Vec<Comment>,
}
/// The `with [ … ]` bracket of a stream expression: one index (`[i]`) or a
/// range in any of the three spellings a part select takes (`[m:l]`,
/// `[i+:n]`, `[i-:n]`).
///
/// It is not an [`ExprKind::Range`] because that node wraps a *base* — here
/// the base stands on the `with`'s left, outside the bracket — but it keeps
/// exactly the same comment slots, so the printer lays both out through one
/// function.
#[derive(Debug, Clone)]
pub struct StreamRange {
/// Comments written on either side of the `with` keyword.
pub with_comments: WithComments,
/// The single index, or the range's first operand.
pub msb: Expr,
/// `:`, `+:` or `-:`; `None` for the single-index spelling.
pub op: Option<String>,
/// The range's second operand; `None` for the single-index spelling.
pub lsb: Option<Expr>,
/// `[ /*a*/ m /*b*/ : /*c*/ l /*d*/ ]` — the slots
/// [`SegmentComments`] names. `before_open` is always empty here: what
/// was written between the `with` and the `[` belongs to the keyword, so
/// it goes in `with_comments.after_kw`.
pub comments: SegmentComments,
}
impl TernaryComments {
/// True when nothing was written inside the `? :` — the common case, laid
/// out without any comment handling.
+3
View File
@@ -33,6 +33,7 @@
//! | `expr` | [`Expr`], [`ExprKind`], the expression comment slots |
//! | `class`, `covergroup` | classes and constraints; covergroups |
//! | `sva` | assertions, `property`/`sequence`, the property-expression tree |
//! | `randsequence` | the `randsequence` production grammar (IEEE 1800 §18.17) |
use crate::span::TextRange;
use crate::token::Comment;
@@ -42,6 +43,7 @@ mod covergroup;
mod decl;
mod expr;
mod module;
mod randsequence;
mod stmt;
mod sva;
@@ -50,6 +52,7 @@ pub use covergroup::*;
pub use decl::*;
pub use expr::*;
pub use module::*;
pub use randsequence::*;
pub use stmt::*;
pub use sva::*;
+93 -2
View File
@@ -183,6 +183,24 @@ pub struct DriveStrength {
/// `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>,
/// Boxed: five comment vectors dwarf the two strength words, and a
/// [`DataDecl`] carrying one of these is what `ast::size_pins` measures.
pub comments: Box<DriveStrengthComments>,
}
/// The five gaps of `/*a*/ ( /*b*/ strong0 /*c*/ , /*d*/ weak1 /*e*/ )`.
///
/// `before_open` is the gap in front of the `(` — the strength owns it because
/// the three constructs that write one (`assign`, a gate, a net declaration)
/// all have something of their own directly in front of it.
#[derive(Debug, Default)]
pub struct DriveStrengthComments {
pub before_open: Vec<Comment>,
pub after_open: Vec<Comment>,
/// Empty for the single-strength spelling, which has no `,`.
pub before_comma: Vec<Comment>,
pub after_comma: Vec<Comment>,
pub before_close: Vec<Comment>,
}
#[derive(Debug)]
@@ -549,8 +567,16 @@ pub struct ModportPort {
pub struct ClockingDecl {
/// True when the declaration was written `default clocking ...`.
pub is_default: bool,
/// Comments written between the `clocking` keyword and whatever follows
/// it — the name, or the `@` of an anonymous block.
pub after_kw: Vec<Comment>,
/// `None` for the anonymous `default clocking @(posedge clk);` form.
pub name: Option<Name>,
/// Comments written between the name and the `@` of the clocking event.
/// Empty when no name or no event was written.
pub before_event: Vec<Comment>,
/// Comments written between the header's last token and its `;`.
pub before_semi: Vec<Comment>,
/// The `@( ... )` clocking event. `None` for `default clocking cb;`, which
/// selects an existing clocking block and has no body.
pub event: Option<SensList>,
@@ -572,6 +598,8 @@ pub struct ClockingDecl {
pub struct ClockingItem {
pub meta: Meta,
pub kind: ClockingItemKind,
/// Comments written between the item's last token and its `;`.
pub before_semi: Vec<Comment>,
/// Code extent of the item, its `;` excluded.
pub span: TextRange,
}
@@ -579,10 +607,73 @@ pub struct ClockingItem {
#[derive(Debug)]
pub enum ClockingItemKind {
/// `default input #1step output #0;` — at least one half is written.
Default { input: Option<String>, output: Option<String> },
Default { input: Option<ClockingDefault>, output: Option<ClockingDefault> },
/// `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> },
Signals {
dir: String,
/// Comments written between the direction keyword and the skew — or,
/// when no skew was written, between it and the first signal name.
after_dir: Vec<Comment>,
skew: Option<ClockingSkew>,
/// Comments written between that skew and the first signal name.
/// Empty when no skew was written.
after_skew: Vec<Comment>,
signals: Vec<ClockingSignal>,
},
}
/// One half of a `default input #1step output #0;` item: a direction keyword
/// and the skew that follows it.
#[derive(Debug)]
pub struct ClockingDefault {
/// Comments written between whatever precedes the direction keyword — the
/// `default`, or the other half's skew — and the keyword itself.
pub before_dir: Vec<Comment>,
/// Comments written between the direction keyword and the skew.
pub after_dir: Vec<Comment>,
pub skew: ClockingSkew,
}
/// The skew of a clocking item — IEEE 1800 §14.3's
/// `clocking_skew ::= edge_identifier [ delay_control ] | delay_control`.
#[derive(Debug)]
pub enum ClockingSkew {
/// `posedge`, `negedge`, `edge`, each of which may carry a delay of its
/// own (`input negedge #(1:2:3) sig;`).
Edge {
/// The edge keyword as written.
word: String,
/// Comments written between that keyword and the `#` behind it. Empty
/// when no delay was written — the gap is then the caller's own slot
/// before the signal name or the other `default` half.
after_edge: Vec<Comment>,
delay: Option<ClockingDelay>,
},
/// A skew that is a `delay_control` alone: `#2`, `#(1:2:3)`.
Delay(ClockingDelay),
}
/// The `# …` half of a clocking skew — IEEE 1800 §14.3's `delay_control`,
/// written alone or behind an edge identifier.
#[derive(Debug)]
pub enum ClockingDelay {
/// `#2`, `#1step` — the one token written after the `#`, kept exactly as
/// written: it is a delay, never something lucisv re-lays out.
Word {
/// Comments written between the `#` and that token.
after_hash: Vec<Comment>,
word: String,
},
/// The parenthesized spelling `#(1:2:3)`, `#(5)` — the same delay
/// expression a net declaration writes, so it arrives with the comment
/// slots [`ExprKind::MinTypMax`] and [`ExprKind::Paren`] already have.
Paren {
/// Comments written between the `#` and the `(`.
after_hash: Vec<Comment>,
/// The parenthesized delay, `(` and `)` included.
expr: Expr,
},
}
/// One `signal [= expression]` of a clocking direction group — IEEE 1800
+173
View File
@@ -0,0 +1,173 @@
//! `randsequence` — the production grammar of IEEE 1800 §18.17.
//!
//! A `randsequence` statement is a little grammar of its own written inside a
//! procedural block: a list of *productions*, each a name with optional
//! arguments and return type, each defining one or more weighted
//! *alternatives*, each alternative a run of *items* — a reference to another
//! production, a code block of ordinary statements, or one of the three
//! control shapes (`if`/`else`, `repeat`, `case`).
//!
//! Every node here carries the comment slots its own tokens open, for the
//! reason the rest of the AST does: a comment written between two tokens must
//! print back between those same two tokens or `verify.rs` refuses the file.
use super::*;
/// `randsequence (main) … endsequence` (IEEE 1800 §18.17).
#[derive(Debug)]
pub struct RandSequence {
/// Comments written between the keyword and its `(`.
pub after_kw: Vec<Comment>,
/// Comments written just inside the `(`.
pub after_open: Vec<Comment>,
/// The starting production, `None` for the empty `randsequence ()`.
pub start: Option<Name>,
/// Comments written between that name and the `)`.
pub before_close: Vec<Comment>,
pub productions: Vec<Production>,
/// Comments written after the last production and before `endsequence`.
pub dangling: Vec<Comment>,
}
/// One production: `[type] name [(ports)] : alternative { | alternative } ;`.
#[derive(Debug)]
pub struct Production {
pub meta: Meta,
/// The production's return type, `None` when it declares none (or wrote
/// `void`, which is kept here as an ordinary type name).
pub ret_type: Option<DataType>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// True when the production wrote a `( … )` port list, even an empty one.
pub has_parens: bool,
/// The formal arguments, read as a subroutine's are (§18.17.5).
pub args: Vec<ListElem<TfArg>>,
/// Comments written between the head and the `:`.
pub before_colon: Vec<Comment>,
/// At least one; the `|`-separated right-hand sides.
pub alternatives: Vec<Alternative>,
/// Comments written between the last alternative and the `;`.
pub before_semi: Vec<Comment>,
/// Code extent of the production, its `;` excluded.
pub span: TextRange,
}
/// One `|`-separated right-hand side of a production, with the optional
/// `:= weight` that biases it.
#[derive(Debug)]
pub struct Alternative {
/// Comments written between the previous alternative and the `|` that
/// starts this one. Always empty on the first alternative, whose left
/// neighbour is the production's `:`.
pub before_bar: Vec<Comment>,
/// Comments written between the `:` (or the `|`) and the first item.
pub after_bar: Vec<Comment>,
pub items: Vec<ProdItem>,
/// Comments written between the last item and the `:=`.
pub before_weight: Vec<Comment>,
/// The `:= expr` weight (§18.17.2), `None` when unweighted.
pub weight: Option<Weight>,
}
/// The `:= weight [code block]` of a weighted alternative.
#[derive(Debug)]
pub struct Weight {
/// Comments written between the `:=` and the weight expression.
pub after_op: Vec<Comment>,
pub expr: Expr,
/// The optional code block run when the alternative is chosen.
pub block: Option<Box<CodeBlock>>,
}
/// One item of an alternative's right-hand side — §18.17's `rs_prod`.
#[derive(Debug)]
pub enum ProdItem {
/// `name`, or `name(args)` — a reference to another production.
Ref(ProdRef),
/// `{ … }` — ordinary statements, laid out as a `begin`/`end` body is.
Block(Box<CodeBlock>),
/// `if (expr) item [else item]`.
If {
/// Comments written between the `if` and its `(`.
after_kw: Vec<Comment>,
cond: Expr,
then: Box<ProdItem>,
/// Comments written between the `then` item and the `else`.
before_else: Vec<Comment>,
/// Comments written between the `else` and its item.
after_else: Vec<Comment>,
els: Option<Box<ProdItem>>,
},
/// `repeat (expr) item`.
Repeat {
/// Comments written between the `repeat` and its `(`.
after_kw: Vec<Comment>,
count: Expr,
body: Box<ProdItem>,
},
/// `case (expr) … endcase`, whose arms take production items rather than
/// statements.
Case {
/// Comments written between the `case` and its `(`.
after_kw: Vec<Comment>,
expr: Expr,
items: Vec<ProdCaseItem>,
/// Comments written after the last arm and before `endcase`.
dangling: Vec<Comment>,
},
/// `rand join [(expr)] item item { item }` (§18.17.6).
RandJoin {
/// Comments written between the `rand` and the `join`.
after_rand: Vec<Comment>,
/// The `( expr )` bias, `None` when omitted.
weight: Option<Expr>,
items: Vec<ProdItem>,
},
}
/// A reference to another production: `name` or `name(a, b)`.
#[derive(Debug)]
pub struct ProdRef {
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// True when a `( … )` argument list was written, even an empty one.
pub has_parens: bool,
/// Comments written between the name and that `(`.
pub before_args: Vec<Comment>,
pub args: Vec<ExprItem>,
}
/// One arm of an `rs_case`: `expr, expr : item;` or `default [:] item;`.
#[derive(Debug)]
pub struct ProdCaseItem {
pub meta: Meta,
/// Empty for the `default` arm.
pub labels: Vec<ExprItem>,
/// True when the arm was written `default`.
pub is_default: bool,
/// Comments written between the labels (or the `default`) and the `:`.
pub before_colon: Vec<Comment>,
/// Comments written between the `:` and the item. A `default` arm may
/// write no `:` at all, and then this is the gap after the keyword.
pub after_colon: Vec<Comment>,
pub item: ProdItem,
/// Comments written between the item and the arm's `;`.
pub before_semi: Vec<Comment>,
/// Code extent of the arm, its `;` excluded.
pub span: TextRange,
}
/// An `rs_code_block`: `{ declarations statements }`. The braces are the
/// block's own, and what stands between them is the statement grammar.
///
/// There is no slot for the gap just inside the `{`: it belongs to the first
/// statement's leading comments, exactly as a `begin`/`end` block's does, and
/// to `dangling` when the block holds no statement at all.
#[derive(Debug)]
pub struct CodeBlock {
pub stmts: Vec<Stmt>,
/// Comments written after the last statement and before the `}`.
pub dangling: Vec<Comment>,
}
+39 -2
View File
@@ -253,9 +253,25 @@ pub enum StmtKind {
stmt: Option<Box<Stmt>>,
},
ExprStmt(Expr),
/// `-> event_name;`
EventTrigger(Expr),
/// `-> ev;` and the non-blocking `->> ev;` (IEEE 1800 §15.5.2), which may
/// carry a delay or event control of its own: `->> #5 ev;`,
/// `->> @(posedge clk) ev;`.
///
/// Boxed because the timing control is the size of a whole sensitivity
/// list and this is one of the smallest statements there is; see
/// `ast::size_pins`.
EventTrigger(Box<EventTrigger>),
VarDecl(DataDecl),
/// A block-scoped `let` (IEEE 1800 §11.13): `let sum = a + b;` written
/// among a `begin`/`end`'s declarations. Same grammar and same layout as
/// the item-level one, so it carries the item's node; boxed because a
/// `let` is rare and its node is wider than the statement kinds that are
/// not (see `ast::size_pins`).
Let(Box<LetDecl>),
/// `randsequence (main) … endsequence` (IEEE 1800 §18.17) — a production
/// grammar of its own, modelled in `ast::randsequence`. Boxed: a
/// production list is wide and a `randsequence` is rare.
RandSequence(Box<RandSequence>),
ParamDecl(ParamDecl),
/// Old-style task/function port declaration: `input [7:0] a;`
PortDecl(PortDecl),
@@ -341,6 +357,27 @@ impl StmtKind {
}
}
/// An event trigger: `-> ev;` or the non-blocking `->> ev;`.
///
/// Only the non-blocking spelling may write a delay or an event control
/// between the arrow and the event (IEEE 1800 §15.5.2), but the node carries
/// one either way — lucisv reproduces what was written and is not a legality
/// checker.
#[derive(Debug)]
pub struct EventTrigger {
/// `->` or `->>`, as written.
pub arrow: String,
/// Comments written between the arrow and whatever follows it
/// (`->> /*c*/ #5 ev;`).
pub after_arrow: Vec<Comment>,
/// The `#5` or `@(posedge clk)` of `->> #5 ev;`.
pub timing: Option<TimingControl>,
/// Comments written between that timing control and the event name.
/// Empty when no timing control was written.
pub before_event: Vec<Comment>,
pub expr: Expr,
}
#[derive(Debug)]
pub enum TimingControl {
/// `#expr`
+3 -3
View File
@@ -52,9 +52,9 @@ struct RawLexer<'a> {
/// Multi-character operators, longest first so greedy matching works.
const OPERATORS: &[&str] = &[
"<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "<->", "**", "==",
"!=", "<=", ">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=", "/=",
"%=", "&=", "|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{",
"<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "<->", "->>", "**",
"==", "!=", "<=", ">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=",
"/=", "%=", "&=", "|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{",
];
const SINGLE_OPS: &[u8] = b"+-*/%&|^~!<>=?:;,.#@()[]{}'$";
+5 -1
View File
@@ -260,6 +260,10 @@ impl<'a> Parser<'a> {
break;
}
}
// `wire (strong0, weak1) w = a;` — IEEE 1800 §6.6 writes the strength
// directly after the net keyword and nowhere else, so a `(` here is
// only read as one when a net keyword was actually written.
let strength = if net.is_some() { self.parse_opt_drive_strength()? } else { None };
let before = self.parse_net_delay(net.is_some(), false)?;
// A declaration reaches here with its `virtual` already in
// `qualifiers`, so `parse_opt_data_type`'s own modport branch cannot
@@ -285,7 +289,7 @@ impl<'a> Parser<'a> {
};
let declarators = self.parse_declarators()?;
self.expect_sym(";")?;
Ok(DataDecl { net, delay, qualifiers, ty, declarators })
Ok(DataDecl { net, strength, delay, qualifiers, ty, declarators })
}
/// The net delay at the cursor, if one is written there: `#5`, `#0.1`,
+44 -6
View File
@@ -265,14 +265,16 @@ impl<'a> Parser<'a> {
|| (t.is_sym("'{") && self.is_cast_base(base))
|| t.is_sym("++")
|| t.is_sym("--")
// `with ( ... )` (an array method's iterator argument) and
// `with { ... }` (a `randomize` constraint block) are the two
// postfix spellings of `with`; the delimiter tells them apart and
// demanding one keeps the `with [range]` of a stream expression,
// which lucisv does not model, out of this path.
// `with ( ... )` (an array method's iterator argument),
// `with { ... }` (a `randomize` constraint block) and
// `with [ ... ]` (a stream expression's array range,
// IEEE 1800 §11.4.14) are the three postfix spellings of `with`;
// the delimiter after the keyword is what tells them apart.
|| (t.is_kw("with")
&& !self.no_with
&& (self.nth(1).is_sym("(") || self.nth(1).is_sym("{")))
&& (self.nth(1).is_sym("(")
|| self.nth(1).is_sym("{")
|| self.nth(1).is_sym("[")))
}
/// True when the `[` at the cursor opens a transition or consecutive
@@ -363,6 +365,35 @@ impl<'a> Parser<'a> {
))
}
/// The `[ … ]` of a stream expression's `with` (IEEE 1800 §11.4.14), the
/// `with` already consumed: one index or a range in any of the three
/// spellings a part select takes.
///
/// `with_comments` arrives holding what was written in front of the
/// keyword; the gap after it is that same node's `after_kw`, so the two
/// halves of `a /*x*/ with /*y*/ [i]` keep their own sides of the word and
/// the printer lays the head out through the one function all three
/// postfix `with` forms share.
fn parse_stream_range(&mut self, mut with_comments: WithComments) -> PResult<StreamRange> {
with_comments.after_kw = self.take_before_open("[");
let mut comments = SegmentComments::default();
self.expect_sym("[")?;
comments.after_open = self.take_gap();
let msb = self.parse_expr()?;
let t = self.cur();
let (op, lsb) = if t.is_sym(":") || t.is_sym("+:") || t.is_sym("-:") {
comments.before_op = self.take_gap();
let op = self.bump().text;
comments.after_op = self.take_gap();
(Some(op), Some(self.parse_expr()?))
} else {
(None, None)
};
comments.before_close = self.gap_before("]");
self.expect_sym("]")?;
Ok(StreamRange { with_comments, msb, op, lsb, comments })
}
fn parse_postfix_inner(&mut self) -> PResult<Expr> {
let mut expr = self.parse_primary()?;
while self.at_postfix_segment(&expr) {
@@ -430,6 +461,13 @@ impl<'a> Parser<'a> {
comments: Box::new(comments),
},
);
} else if self.nth(1).is_sym("[") {
self.bump(); // with
let range = self.parse_stream_range(comments)?;
expr = self.expr_at(
start,
ExprKind::StreamWith { base: Box::new(expr), range: Box::new(range) },
);
} else {
self.bump(); // with
comments.after_kw = self.take_before_open("(");
+13 -3
View File
@@ -76,22 +76,32 @@ impl<'a> Parser<'a> {
/// strength when a strength keyword follows it, so a parenthesized
/// left-hand side — and a gate whose first argument is an expression — is
/// untouched.
fn parse_opt_drive_strength(&mut self) -> PResult<Option<DriveStrength>> {
pub(super) fn parse_opt_drive_strength(&mut self) -> PResult<Option<DriveStrength>> {
if !self.cur().is_sym("(") || !is_drive_strength(self.nth(1)) {
return Ok(None);
}
let mut comments =
Box::new(DriveStrengthComments { before_open: self.take_gap(), ..Default::default() });
self.bump(); // (
comments.after_open = self.take_gap();
let first = self.bump().text;
// The gap after the first strength ends either at the `,` or at the
// `)`, and it is that token which says which slot it belongs in.
let gap = self.take_gap();
if self.eat_sym(")") {
return Ok(Some(DriveStrength { first, second: None }));
comments.before_close = gap;
return Ok(Some(DriveStrength { first, second: None, comments }));
}
comments.before_comma = gap;
self.expect_sym(",")?;
comments.after_comma = self.take_gap();
if !is_drive_strength(self.cur()) {
return self.error("expected a drive strength");
}
let second = Some(self.bump().text);
comments.before_close = self.gap_before(")");
self.expect_sym(")")?;
Ok(Some(DriveStrength { first, second }))
Ok(Some(DriveStrength { first, second, comments }))
}
/// The value after a `#`: a bare primary, or a parenthesized delay —
@@ -238,6 +238,13 @@ impl<'a> Parser<'a> {
// A package import standing among a block's declarations
// (IEEE 1800 §13.4.2): the same statement the item level takes.
"import" => Ok(StmtKind::Import(self.parse_import_list()?)),
// A block-scoped `let` (IEEE 1800 §11.13). `parse_let` reads the
// `;` itself, which is why `takes_semi()` says this kind takes
// none — exactly as the item-level spelling works.
"let" => Ok(StmtKind::Let(Box::new(self.parse_let()?))),
// `randsequence` reads its own `endsequence`, so like a block it
// takes no `;` of its own (`takes_semi()` says so).
"randsequence" => Ok(StmtKind::RandSequence(Box::new(self.parse_randsequence()?))),
// A block-scoped type (IEEE 1800 §6.18), e.g.
// `spi_host/dv/env/seq_lib/spi_host_base_vseq.sv:577`. Same
// grammar and same layout as the item-level `typedef`.
+2
View File
@@ -37,6 +37,7 @@
//! | `expr`, `primary` | the operator grammar; its leaves and argument lists |
//! | `class`, `covergroup` | classes with their constraints; covergroups |
//! | `assertion`, `sva` | concurrent assertions and SVA declarations; the property grammar |
//! | `randsequence` | the `randsequence` production grammar (IEEE 1800 §18.17) |
//! | `directive` | `` `ifdef `` tracking, list directives, macros, fragment mode |
//! | `split` | conditional-directive split recovery |
//! | `verbatim` | vendor/formal blocks kept as bytes, and the capture helpers |
@@ -59,6 +60,7 @@ mod item;
mod keyword_stmt;
mod module;
mod primary;
mod randsequence;
mod recover;
mod recover_list;
mod split;
+72 -19
View File
@@ -217,15 +217,21 @@ impl<'a> Parser<'a> {
/// `default` keyword, when written, has already been consumed.
pub(super) fn parse_clocking(&mut self, is_default: bool) -> PResult<ClockingDecl> {
self.expect_kw("clocking")?;
let after_kw = self.take_gap();
let name =
if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None };
let before_event = if self.cur().is_sym("@") { self.take_gap() } else { Vec::new() };
// `default clocking cb;` selects an existing block and has no body.
let event = if self.eat_sym("@") { Some(self.parse_sens_list()?) } else { None };
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
if event.is_none() {
return Ok(ClockingDecl {
is_default,
after_kw,
name,
before_event,
before_semi,
event,
items: Vec::new(),
dangling: Vec::new(),
@@ -245,7 +251,10 @@ impl<'a> Parser<'a> {
let (end_label, end_label_span) = split_label(end_name);
Ok(ClockingDecl {
is_default,
after_kw,
name,
before_event,
before_semi,
event,
items,
dangling,
@@ -262,9 +271,8 @@ impl<'a> Parser<'a> {
let start = self.here();
let mut meta = self.take_meta();
let kind = if self.eat_kw("default") {
let input = if self.eat_kw("input") { Some(self.parse_clocking_skew()?) } else { None };
let output =
if self.eat_kw("output") { Some(self.parse_clocking_skew()?) } else { None };
let input = self.parse_clocking_default("input")?;
let output = self.parse_clocking_default("output")?;
if input.is_none() && output.is_none() {
return self.error("expected `input` or `output` after `default`");
}
@@ -275,20 +283,28 @@ impl<'a> Parser<'a> {
return self.error("expected a clocking item");
}
let dir = self.bump().text;
let skew =
if self.at_clocking_skew() { Some(self.parse_clocking_skew()?) } else { None };
let after_dir = self.take_gap();
let mut after_skew = Vec::new();
let skew = if self.at_clocking_skew() {
let skew = self.parse_clocking_skew()?;
after_skew = self.take_gap();
Some(skew)
} else {
None
};
let mut signals = vec![self.parse_clocking_signal()?];
while self.eat_sym(",") {
signals.push(self.parse_clocking_signal()?);
}
ClockingItemKind::Signals { dir, skew, signals }
ClockingItemKind::Signals { dir, after_dir, skew, after_skew, signals }
};
let span = self.span_from(start);
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(ClockingItem { meta, kind, span })
Ok(ClockingItem { meta, kind, before_semi, span })
}
/// One `signal [= expression]` of a clocking direction group — IEEE 1800
@@ -301,6 +317,21 @@ impl<'a> Parser<'a> {
Ok(ClockingSignal { name, value })
}
/// One half of a `default input #1step output #0;` item: the direction
/// keyword `dir` and its skew, or `None` when this half was not written.
///
/// The gap in front of the keyword is the half's own, so the two halves
/// keep their own sides of the word that separates them.
fn parse_clocking_default(&mut self, dir: &str) -> PResult<Option<ClockingDefault>> {
if !self.cur().is_kw(dir) {
return Ok(None);
}
let before_dir = self.take_gap();
self.bump();
let after_dir = self.take_gap();
Ok(Some(ClockingDefault { before_dir, after_dir, skew: self.parse_clocking_skew()? }))
}
/// True when the cursor is on a clocking skew rather than on the first
/// signal name: `#2`, `#1step`, `posedge`, `negedge`, `edge`.
fn at_clocking_skew(&self) -> bool {
@@ -308,25 +339,47 @@ impl<'a> Parser<'a> {
t.is_sym("#") || t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge")
}
/// A clocking skew, as written: `#2`, `#1step`, `negedge`. Kept as text —
/// it is a delay or an edge, never something lucisv re-lays out — so the
/// printer writes back exactly what the source said. The `#(min:typ:max)`
/// spelling is not supported; see the feature README's Assumptions.
fn parse_clocking_skew(&mut self) -> PResult<String> {
if self.eat_sym("#") {
let t = self.cur();
if !matches!(t.kind, TokenKind::Number | TokenKind::Ident) {
return self.error("expected a clocking skew delay");
}
return Ok(format!("#{}", self.bump().text));
/// A clocking skew, as written: `#2`, `#1step`, the parenthesized
/// `#(1:2:3)`, an edge identifier, or — IEEE 1800 §14.3's first
/// alternative — an edge identifier with a delay behind it
/// (`negedge #(1:2:3)`).
fn parse_clocking_skew(&mut self) -> PResult<ClockingSkew> {
if self.cur().is_sym("#") {
return Ok(ClockingSkew::Delay(self.parse_clocking_delay()?));
}
let t = self.cur();
if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") {
return Ok(self.bump().text);
let word = self.bump().text;
// Only a gap that really is in front of a `#` is the edge's own;
// otherwise it belongs to the caller's slot before the name.
let after_edge = self.gap_before("#");
let delay =
if self.cur().is_sym("#") { Some(self.parse_clocking_delay()?) } else { None };
return Ok(ClockingSkew::Edge { word, after_edge, delay });
}
self.error("expected a clocking skew")
}
/// The `# …` half of a clocking skew.
///
/// The one-token spellings are kept as text — a delay is never something
/// lucisv re-lays out — so the printer writes back exactly what the source
/// said. The parenthesized one goes through the delay-value grammar every
/// other `#( … )` uses, which is what gives its `:` and its parens their
/// comment slots.
fn parse_clocking_delay(&mut self) -> PResult<ClockingDelay> {
self.expect_sym("#")?;
let after_hash = self.take_gap();
if self.cur().is_sym("(") {
return Ok(ClockingDelay::Paren { after_hash, expr: self.parse_delay_value()? });
}
let t = self.cur();
if !matches!(t.kind, TokenKind::Number | TokenKind::Ident) {
return self.error("expected a clocking skew delay");
}
Ok(ClockingDelay::Word { after_hash, word: self.bump().text })
}
/// A `#( parameter ... )` port list, shared by module and class headers.
/// `ports` is `None` when no `#(` was written at the cursor at all.
pub(super) fn parse_param_port_list(&mut self) -> PResult<ParamPortList> {
+16 -3
View File
@@ -146,20 +146,25 @@ impl<'a> Parser<'a> {
/// its `<<` or `>>`: IEEE 1800 §11.4.14
/// `{ (<<|>>) [slice_size] { stream_expression {, stream_expression} } }`.
///
/// The `with [range]` form of a stream expression is not supported; a
/// file using it keeps its old "expected expression" error.
/// A stream expression's `with [range]` is read by `parse_postfix_inner`,
/// as the postfix segment it is; the elements here are ordinary
/// expressions either way.
fn parse_stream_concat(&mut self, start: u32) -> PResult<Expr> {
let mut comments =
Box::new(StreamComments { after_open: self.take_gap(), ..Default::default() });
let dir = self.bump().text;
// The slice size is optional and is a constant expression or a type
// (`{<< byte {x}}`); a `{` here means it was omitted.
let slice =
if self.cur().is_sym("{") { None } else { Some(Box::new(self.parse_expr_or_type()?)) };
comments.before_inner = self.take_before_open("{");
self.expect_sym("{")?;
let first = self.parse_expr_item()?;
let inner = self.parse_expr_list(first, "}")?;
self.expect_sym("}")?;
comments.before_close = self.gap_before("}");
self.expect_sym("}")?;
Ok(self.expr_at(start, ExprKind::Stream { dir, slice, inner }))
Ok(self.expr_at(start, ExprKind::Stream { dir, slice, inner, comments }))
}
/// True when `e` may stand left of a cast's `'` — the `constant_primary`
@@ -180,6 +185,14 @@ impl<'a> Parser<'a> {
| ExprKind::Scope { .. }
| ExprKind::Member { .. }
| ExprKind::Paren { .. } => true,
// A data type with dimensions on it — `logic [3:0]'(x)`,
// `bit signed [7:0]'(y)`. A bare `int'(x)` never reaches here
// (`parse_primary` takes the keyword-and-tick shape itself); this
// is the spelling whose `[3:0]` sent it down `parse_type_expr`
// instead. IEEE 1800 §6.24.1's `casting_type` names only
// `simple_type`, but every tool in use accepts the packed
// dimensions and lucisv is not a legality checker.
ExprKind::Type(_) => true,
ExprKind::Call { callee, .. } => {
matches!(&callee.kind, ExprKind::Ident(n) if n.starts_with('$'))
}
@@ -0,0 +1,316 @@
//! `randsequence` — the production grammar of IEEE 1800 §18.17.
//!
//! One file for one sub-grammar, the way the SVA and covergroup grammars each
//! have their own: a `randsequence` body is a production list, not a
//! statement list, and nothing outside it reads these productions.
//!
//! The nesting between an alternative's items and the control shapes that
//! wrap them is real recursion, so `parse_prod_item` brackets itself with
//! [`Parser::enter`] / [`Parser::leave`] the way every other recursive
//! production does.
use super::*;
impl<'a> Parser<'a> {
/// `randsequence ( [name] ) production { production } endsequence`
/// (IEEE 1800 §18.17), the cursor on the keyword.
pub(super) fn parse_randsequence(&mut self) -> PResult<RandSequence> {
self.expect_kw("randsequence")?;
let after_kw = self.take_before_open("(");
self.expect_sym("(")?;
let after_open = self.take_gap();
let start =
if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None };
let before_close = self.gap_before(")");
self.expect_sym(")")?;
let mut productions = Vec::new();
while !self.at_body_end("endsequence") {
productions.push(self.parse_production()?);
}
let dangling = self.take_dangling();
self.expect_closer("endsequence")?;
Ok(RandSequence { after_kw, after_open, start, before_close, productions, dangling })
}
/// One production: `[data_type] name [( ports )] : alternatives ;`.
///
/// The optional return type is told from the name by what follows the
/// identifier: a production's name is the last identifier before the `(`,
/// the `:` or another identifier, so a second identifier means the first
/// one was the type.
fn parse_production(&mut self) -> PResult<Production> {
let start = self.here();
let mut meta = self.take_meta();
let ret_type = self.parse_opt_production_type()?;
let Name { text: name, span: name_span } = self.expect_name()?;
let has_parens = self.cur().is_sym("(");
let args = self.parse_tf_ports(false)?.args;
let before_colon = self.gap_before(":");
self.expect_sym(":")?;
let mut alternatives = vec![self.parse_alternative(Vec::new())?];
while self.cur().is_sym("|") {
// The gap in front of the `|` belongs to the alternative it opens,
// so it prints on the bar's own side of the previous one.
let before_bar = self.take_gap();
self.bump();
alternatives.push(self.parse_alternative(before_bar)?);
}
let span = self.span_from(start);
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(Production {
meta,
ret_type,
name,
name_span,
has_parens,
args,
before_colon,
alternatives,
before_semi,
span,
})
}
/// The production's return type, when it wrote one. `void` is a keyword
/// rather than an identifier, so it is read here too and kept as the type
/// name it is written as.
fn parse_opt_production_type(&mut self) -> PResult<Option<DataType>> {
let t = self.cur();
let typed = if t.is_kw("void") {
true
} else if t.kind == TokenKind::Keyword {
// `int name : …`, `bit [3:0] name : …` — a type keyword can only
// be the type, never the production's own name.
TYPE_KEYWORDS.contains(&t.text.as_str())
} else {
// Two identifiers in a row: the first is a user-defined type.
t.kind == TokenKind::Ident && self.nth(1).kind == TokenKind::Ident
};
if !typed {
return Ok(None);
}
Ok(Some(self.parse_opt_data_type()?))
}
/// One `|`-separated right-hand side, with its optional `:= weight`.
fn parse_alternative(&mut self, before_bar: Vec<Comment>) -> PResult<Alternative> {
let after_bar = self.take_gap();
let mut items = vec![self.parse_prod_item()?];
while self.at_prod_item() {
items.push(self.parse_prod_item()?);
}
let mut before_weight = Vec::new();
let mut weight = None;
if self.at_weight_op() {
before_weight = self.take_gap();
self.bump(); // :
self.bump(); // =
weight = Some(self.parse_weight()?);
}
Ok(Alternative { before_bar, after_bar, items, before_weight, weight })
}
/// True when the cursor is on the `:=` of a weight. The lexer has no `:=`
/// token — it is a `:` and an `=` written adjacently, the same two tokens
/// a `dist` weight is read from — so adjacency is checked by span and
/// `a : = 5` written with a space is not one.
fn at_weight_op(&self) -> bool {
self.cur().is_sym(":")
&& self.nth(1).is_sym("=")
&& self.nth(1).span.start == self.cur().span.end
}
/// The `:= expr [ { code } ]` of a weighted alternative (§18.17.2).
///
/// §18.17.2's `weight_specification` is a number, a scoped name or a
/// *parenthesized* expression — never a bare operator expression — and
/// that is what keeps `a := 3 | b := 2` readable: an unparenthesized `|`
/// separates the alternatives, it does not or two weights together. So
/// the weight is read as a postfix expression and stops there.
fn parse_weight(&mut self) -> PResult<Weight> {
let after_op = self.take_gap();
let expr = self.parse_postfix()?;
let block =
if self.cur().is_sym("{") { Some(Box::new(self.parse_rs_code_block()?)) } else { None };
Ok(Weight { after_op, expr, block })
}
/// True when the cursor opens another item of the alternative rather than
/// ending it. An alternative ends at `|`, `:=`, `;`, or the `}` / `endcase`
/// of whatever encloses it.
fn at_prod_item(&self) -> bool {
let t = self.cur();
t.kind == TokenKind::Ident
|| t.is_sym("{")
|| t.is_kw("if")
|| t.is_kw("repeat")
|| t.is_kw("case")
|| t.is_kw("rand")
}
/// One `rs_prod`: a production reference, a code block, or one of the four
/// control shapes.
fn parse_prod_item(&mut self) -> PResult<ProdItem> {
self.enter()?;
let item = self.parse_prod_item_inner();
self.leave();
item
}
fn parse_prod_item_inner(&mut self) -> PResult<ProdItem> {
let t = self.cur();
if t.is_sym("{") {
return Ok(ProdItem::Block(Box::new(self.parse_rs_code_block()?)));
}
if t.is_kw("if") {
return self.parse_rs_if();
}
if t.is_kw("repeat") {
self.bump();
let after_kw = self.take_before_open("(");
self.expect_sym("(")?;
let count = self.parse_expr()?;
self.expect_sym(")")?;
let body = Box::new(self.parse_prod_item()?);
return Ok(ProdItem::Repeat { after_kw, count, body });
}
if t.is_kw("case") {
return self.parse_rs_case();
}
if t.is_kw("rand") {
return self.parse_rand_join();
}
Ok(ProdItem::Ref(self.parse_prod_ref()?))
}
/// `if ( expr ) item [ else item ]` — the arms are production items, not
/// statements, so this is not `parse_if_stmt`.
fn parse_rs_if(&mut self) -> PResult<ProdItem> {
self.expect_kw("if")?;
let after_kw = self.take_before_open("(");
self.expect_sym("(")?;
let cond = self.parse_expr()?;
self.expect_sym(")")?;
let then = Box::new(self.parse_prod_item()?);
// Whatever was written in the gap before `else` stays on the
// keyword's left, as an `if` statement's does.
let mut before_else = Vec::new();
if self.cur().is_kw("else") {
before_else = self.take_dangling();
}
let (after_else, els) = if self.eat_kw("else") {
(self.take_gap(), Some(Box::new(self.parse_prod_item()?)))
} else {
(Vec::new(), None)
};
Ok(ProdItem::If { after_kw, cond, then, before_else, after_else, els })
}
/// `case ( expr ) arm { arm } endcase`, whose arms take production items.
fn parse_rs_case(&mut self) -> PResult<ProdItem> {
self.expect_kw("case")?;
let after_kw = self.take_before_open("(");
self.expect_sym("(")?;
let expr = self.parse_expr()?;
self.expect_sym(")")?;
let mut items = Vec::new();
while !self.at_body_end("endcase") {
items.push(self.parse_rs_case_item()?);
}
let dangling = self.take_dangling();
self.expect_closer("endcase")?;
Ok(ProdItem::Case { after_kw, expr, items, dangling })
}
/// One arm: `expr {, expr} : item ;` or `default [:] item ;`.
fn parse_rs_case_item(&mut self) -> PResult<ProdCaseItem> {
let start = self.here();
let mut meta = self.take_meta();
let mut labels = Vec::new();
let is_default = self.eat_kw("default");
if !is_default {
let first = self.parse_expr_item()?;
labels = self.parse_expr_list(first, ":")?;
}
let before_colon = self.gap_before(":");
// A `default` arm may write no `:` at all (§18.17.4).
let has_colon = self.cur().is_sym(":");
if has_colon {
self.bump();
} else if !is_default {
return self.error("expected `:` in a randsequence case arm");
}
let after_colon = self.take_gap();
let item = self.parse_prod_item()?;
let span = self.span_from(start);
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(ProdCaseItem {
meta,
labels,
is_default,
before_colon,
after_colon,
item,
before_semi,
span,
})
}
/// `rand join [ ( expr ) ] item item { item }` (§18.17.6): the items are
/// interleaved rather than run in order, and there are at least two.
fn parse_rand_join(&mut self) -> PResult<ProdItem> {
self.expect_kw("rand")?;
let after_rand = self.take_gap();
self.expect_kw("join")?;
let weight = if self.cur().is_sym("(") {
self.bump();
let e = self.parse_expr()?;
self.expect_sym(")")?;
Some(e)
} else {
None
};
let mut items = vec![self.parse_prod_item()?];
while self.at_prod_item() {
items.push(self.parse_prod_item()?);
}
Ok(ProdItem::RandJoin { after_rand, weight, items })
}
/// A production reference: `name` or `name(a, b)`.
fn parse_prod_ref(&mut self) -> PResult<ProdRef> {
let Name { text: name, span: name_span } = self.expect_name()?;
let before_args = self.take_before_open("(");
let has_parens = self.cur().is_sym("(");
let mut args = Vec::new();
if has_parens {
self.bump();
if !self.cur().is_sym(")") {
let first = self.parse_expr_item()?;
args = self.parse_expr_list(first, ")")?;
}
self.expect_sym(")")?;
}
Ok(ProdRef { name, name_span, has_parens, before_args, args })
}
/// An `rs_code_block`: `{ … }` around ordinary statements.
fn parse_rs_code_block(&mut self) -> PResult<CodeBlock> {
self.expect_sym("{")?;
let mut stmts = Vec::new();
while !self.cur().is_sym("}") && !self.at_eof() {
stmts.push(self.stmt_or_recover()?);
}
let dangling = self.take_dangling();
self.expect_sym("}")?;
Ok(CodeBlock { stmts, dangling })
}
}
+38 -5
View File
@@ -144,11 +144,8 @@ impl<'a> Parser<'a> {
let stmt = if self.eat_stmt_semi() { None } else { Some(Box::new(self.parse_stmt()?)) };
return Ok(StmtKind::Timing { control: TimingControl::Event(sens), stmt });
}
if t.is_sym("->") {
self.bump();
let e = self.parse_unary()?;
self.expect_stmt_semi()?;
return Ok(StmtKind::EventTrigger(e));
if t.is_sym("->") || t.is_sym("->>") {
return self.parse_event_trigger();
}
if t.kind == TokenKind::Keyword {
return self.parse_keyword_stmt();
@@ -157,6 +154,42 @@ impl<'a> Parser<'a> {
self.parse_assign_or_expr_stmt()
}
/// `-> ev;` and `->> [delay_or_event_control] ev;` (IEEE 1800 §15.5.2).
///
/// The arrow is kept as written: `->` and `->>` are different statements
/// (blocking and non-blocking), so rewriting one as the other would
/// change the design. Only `->>` may carry the timing control, but it is
/// read for both spellings — the parser reproduces what stands there and
/// leaves legality to the tools that check it.
fn parse_event_trigger(&mut self) -> PResult<StmtKind> {
let arrow = self.bump().text;
let after_arrow = self.take_gap();
let timing = self.parse_opt_timing_control()?;
let before_event = if timing.is_some() { self.take_gap() } else { Vec::new() };
let expr = self.parse_unary()?;
self.expect_stmt_semi()?;
Ok(StmtKind::EventTrigger(Box::new(EventTrigger {
arrow,
after_arrow,
timing,
before_event,
expr,
})))
}
/// The `#delay` or `@(event)` written at the cursor, if one is.
fn parse_opt_timing_control(&mut self) -> PResult<Option<TimingControl>> {
if self.eat_sym("#") {
let after_hash = self.take_gap();
let expr = self.parse_delay_value()?;
return Ok(Some(TimingControl::Delay { after_hash, expr }));
}
if self.eat_sym("@") {
return Ok(Some(TimingControl::Event(self.parse_sens_list()?)));
}
Ok(None)
}
pub(super) fn parse_if_stmt(&mut self, qualifier: Option<String>) -> PResult<StmtKind> {
self.expect_kw("if")?;
let after_kw = self.take_before_open("(");
+28 -6
View File
@@ -226,13 +226,17 @@ fn only_a_brace_after_the_first_element_makes_an_assignment_pattern_a_replicatio
fn a_streaming_concatenation_keeps_its_direction_and_optional_slice_size() {
// corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_sha2_pkg.sv:123.
with_assign_rhs("module m;\n assign y = {<<8{v}};\nendmodule\n", |e| {
let ExprKind::Stream { dir, slice, inner } = &e.kind else { panic!("expected a stream") };
let ExprKind::Stream { dir, slice, inner, .. } = &e.kind else {
panic!("expected a stream")
};
assert_eq!(dir, "<<");
assert!(matches!(slice.as_deref().map(|s| &s.kind), Some(ExprKind::Number(_))));
assert_eq!(inner.len(), 1);
});
with_assign_rhs("module m;\n assign y = {>>{a, b}};\nendmodule\n", |e| {
let ExprKind::Stream { dir, slice, inner } = &e.kind else { panic!("expected a stream") };
let ExprKind::Stream { dir, slice, inner, .. } = &e.kind else {
panic!("expected a stream")
};
assert_eq!(dir, ">>");
assert!(slice.is_none(), "no slice size was written");
assert_eq!(inner.len(), 2);
@@ -287,10 +291,28 @@ fn an_argument_carries_its_own_comments_and_the_call_carries_none() {
}
#[test]
fn a_with_that_opens_neither_a_paren_nor_a_brace_is_not_a_postfix_segment() {
// The stream expression's `with [range]` is still unsupported, and
// still fails where it always did rather than being mis-read.
assert!(parse_err("module m;\n initial x = {<<{a with [0:1]}};\nendmodule\n").contains("with"));
fn a_with_that_opens_a_bracket_is_a_stream_range() {
// The third postfix spelling of `with` (TODO §54.1): `[` after the
// keyword is a stream expression's array range, not an array method's
// iterator argument and not a `randomize` constraint block.
let f = parse_ok("module m;\n initial x = {<<{a with [0:1]}};\nendmodule\n");
let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else {
panic!("expected an initial block")
};
let StmtKind::Assign { rhs, .. } = &stmt.kind else { panic!("expected an assignment") };
let ExprKind::Stream { inner, .. } = &rhs.kind else { panic!("expected a stream") };
let ExprKind::StreamWith { range, .. } = &inner[0].expr.kind else {
panic!("expected a stream range, got {:?}", inner[0].expr.kind)
};
assert_eq!(range.op.as_deref(), Some(":"));
assert!(range.lsb.is_some());
}
#[test]
fn a_with_that_opens_none_of_the_three_delimiters_is_not_a_postfix_segment() {
// A bare `with name` is no postfix segment at all, and still fails where
// it always did rather than being mis-read.
assert!(parse_err("module m;\n initial x = a with b;\nendmodule\n").contains("with"));
}
#[test]
+78 -3
View File
@@ -338,18 +338,93 @@ fn a_clocking_block_parses_its_items() {
assert_eq!(c.items.len(), 3);
assert!(matches!(
&c.items[0].kind,
ClockingItemKind::Default { input: Some(i), output: Some(o) } if i == "#2" && o == "#4"
ClockingItemKind::Default {
input: Some(ClockingDefault {
skew: ClockingSkew::Delay(ClockingDelay::Word { word: i, .. }), ..
}),
output: Some(ClockingDefault {
skew: ClockingSkew::Delay(ClockingDelay::Word { word: o, .. }), ..
}),
} if i == "2" && o == "4"
));
assert!(matches!(
&c.items[1].kind,
ClockingItemKind::Signals { dir, skew: None, signals } if dir == "input" && signals.len() == 2
ClockingItemKind::Signals { dir, skew: None, signals, .. }
if dir == "input" && signals.len() == 2
));
assert!(matches!(
&c.items[2].kind,
ClockingItemKind::Signals { dir, skew: Some(s), .. } if dir == "output" && s == "negedge"
ClockingItemKind::Signals {
dir,
skew: Some(ClockingSkew::Edge { word: s, delay: None, .. }),
..
} if dir == "output" && s == "negedge"
));
}
#[test]
fn a_clocking_skew_reads_a_delay_behind_its_edge() {
// IEEE 1800-2017 14.3: `clocking_skew ::= edge_identifier [ delay_control ]
// | delay_control`. The edge and the delay are one skew, not two.
let f = parse_ok(
"module m;\n clocking cb @(posedge clk);\n default input negedge #(1:2:3) output posedge #5;\n input posedge #1step a;\n input edge b;\n endclocking\nendmodule\n",
);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Clocking(c) = &m.items[0].kind else { panic!("expected a clocking block") };
assert!(matches!(
&c.items[0].kind,
ClockingItemKind::Default {
input: Some(ClockingDefault {
skew: ClockingSkew::Edge {
word: i,
delay: Some(ClockingDelay::Paren { .. }),
..
},
..
}),
output: Some(ClockingDefault {
skew: ClockingSkew::Edge {
word: o,
delay: Some(ClockingDelay::Word { word: d, .. }),
..
},
..
}),
} if i == "negedge" && o == "posedge" && d == "5"
));
assert!(matches!(
&c.items[1].kind,
ClockingItemKind::Signals {
skew: Some(ClockingSkew::Edge { delay: Some(ClockingDelay::Word { word, .. }), .. }),
..
} if word == "1step"
));
assert!(matches!(
&c.items[2].kind,
ClockingItemKind::Signals { skew: Some(ClockingSkew::Edge { word, delay: None, .. }), .. }
if word == "edge"
));
}
#[test]
fn an_edge_skews_delay_is_read_the_same_way_in_tolerant_mode() {
// Strict/tolerant parity: the shape is grammar, not recovery, so the
// tolerant parser reads it with no diagnostic of its own.
let src = "module m;\n clocking cb @(posedge clk);\n default input negedge #(1:2:3) output posedge #5;\n input edge /*c*/ #2 a;\n endclocking\nendmodule\n";
let (f, diags) = parse_tolerant(tokenize(src).expect("lex error"), src);
assert!(diags.is_empty(), "tolerant mode recovered from a legal skew: {diags:?}");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Clocking(c) = &m.items[0].kind else { panic!("expected a clocking block") };
let ClockingItemKind::Signals {
skew: Some(ClockingSkew::Edge { after_edge, delay, .. }), ..
} = &c.items[1].kind
else {
panic!("expected an edge skew with a delay")
};
assert_eq!(texts(after_edge), ["/*c*/"], "the gap in front of the `#` is the edge's own");
assert!(matches!(delay, Some(ClockingDelay::Word { word, .. }) if word == "2"));
}
#[test]
fn a_default_clocking_may_be_anonymous_or_body_less() {
// corpus/ibex/dv/formal/check/top.sv:143, and IEEE 1800-2017 14.12.
+15 -1
View File
@@ -134,13 +134,27 @@ impl<'a> Parser<'a> {
/// writes no parens at all, which is what `has_parens` records.
pub(super) fn parse_let(&mut self) -> PResult<LetDecl> {
self.expect_kw("let")?;
let after_kw = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
let has_parens = self.cur().is_sym("(");
let ports = self.parse_tf_ports(false)?.args;
let mut eq_comments = Box::new(BinaryComments::default());
eq_comments.before = self.gap_before("=");
self.expect_sym("=")?;
eq_comments.after = self.take_gap();
let value = self.parse_expr()?;
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
Ok(LetDecl { name, name_span, has_parens, ports, value })
Ok(LetDecl {
after_kw,
name,
name_span,
has_parens,
ports,
eq_comments,
value,
before_semi,
})
}
/// The header a subroutine declaration and a `modport` method prototype
+1
View File
@@ -257,6 +257,7 @@ keywords![
"pure",
"extern",
"rand",
"randsequence",
"randc",
"local",
"protected",
+77 -1
View File
@@ -980,9 +980,36 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) {
check_stmt(src, s, here);
}
}
StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => check_expr(src, e, here),
StmtKind::ExprStmt(e) => check_expr(src, e, here),
StmtKind::EventTrigger(t) => check_expr(src, &t.expr, here),
StmtKind::VarDecl(d) => check_declarators(src, &d.declarators, here),
StmtKind::Typedef(t) => check_typedef(src, t, here),
StmtKind::RandSequence(r) => {
for p in &r.productions {
assert_inside(src, "production", p.span, here);
check_name(src, "production name", &p.name, p.name_span, p.span);
check_list(src, "production port", &p.args, p.span, |a| {
assert_inside(src, "production port", a.span, p.span);
check_name(src, "production port name", &a.name, a.name_span, a.span);
});
for alt in &p.alternatives {
for item in &alt.items {
check_prod_item(src, item, p.span);
}
if let Some(w) = &alt.weight {
check_expr(src, &w.expr, p.span);
}
}
}
}
StmtKind::Let(l) => {
check_name(src, "let name", &l.name, l.name_span, here);
check_list(src, "let port", &l.ports, here, |a| {
assert_inside(src, "let port", a.span, here);
check_name(src, "let port name", &a.name, a.name_span, a.span);
});
check_expr(src, &l.value, here);
}
StmtKind::ParamDecl(p) => check_declarators(src, &p.declarators, here),
StmtKind::PortDecl(p) => check_declarators(src, &p.declarators, here),
StmtKind::Return { expr, .. } => check_opt_expr(src, expr.as_ref(), here),
@@ -1126,6 +1153,50 @@ fn check_match_items(src: &str, items: &[MatchItem], parent: TextRange) {
}
}
/// Every span a `randsequence` item and the items nested in it carry.
fn check_prod_item(src: &str, item: &ProdItem, parent: TextRange) {
match item {
ProdItem::Ref(r) => {
check_name(src, "production reference", &r.name, r.name_span, parent);
for a in &r.args {
check_expr(src, &a.expr, parent);
}
}
ProdItem::Block(b) => {
for s in &b.stmts {
check_stmt(src, s, parent);
}
}
ProdItem::If { cond, then, els, .. } => {
check_expr(src, cond, parent);
check_prod_item(src, then, parent);
if let Some(e) = els {
check_prod_item(src, e, parent);
}
}
ProdItem::Repeat { count, body, .. } => {
check_expr(src, count, parent);
check_prod_item(src, body, parent);
}
ProdItem::Case { expr, items, .. } => {
check_expr(src, expr, parent);
for arm in items {
assert_inside(src, "randsequence case arm", arm.span, parent);
for l in &arm.labels {
check_expr(src, &l.expr, arm.span);
}
check_prod_item(src, &arm.item, arm.span);
}
}
ProdItem::RandJoin { weight, items, .. } => {
check_opt_expr(src, weight.as_ref(), parent);
for i in items {
check_prod_item(src, i, parent);
}
}
}
}
fn check_opt_expr(src: &str, e: Option<&Expr>, parent: TextRange) {
if let Some(e) = e {
check_expr(src, e, parent);
@@ -1148,6 +1219,11 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
check_expr(src, base, here);
check_expr(src, arg, here);
}
ExprKind::StreamWith { base, range } => {
check_expr(src, base, here);
check_expr(src, &range.msb, here);
check_opt_expr(src, range.lsb.as_ref(), here);
}
ExprKind::WithConstraint { base, block, .. } => {
check_expr(src, base, here);
match &**block {