Files
lucisv/crates/vlog_parser/src/ast/expr.rs
T
lucioandClaude Fable 5.1 a69a1cb528 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]>
2026-09-07 01:12:49 -05:00

536 lines
21 KiB
Rust

//! 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,
}
impl Expr {
/// True for the leaf a tolerant parse leaves where a statement header's
/// condition did not parse; see [`ExprKind::Error`].
pub fn is_error(&self) -> bool {
matches!(self.kind, ExprKind::Error(_))
}
}
#[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>,
/// 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>,
/// 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),
/// Text a **tolerant** parse could not read as an expression, kept
/// verbatim: the `i <` of a half-typed `for (int i = 0; i <` header.
///
/// Built only inside a statement header's brackets, and only by
/// [`crate::parse_tolerant`] — the strict parser fails on the typo
/// instead, exactly as it does for [`ItemKind::Error`] — so the statement
/// keeps its shape and its body while the broken condition is one leaf.
/// See `docs/features/header-recovery/README.md`.
Error(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>,
/// What was written around the two `:`.
comments: Box<MinTypMaxComments>,
},
}
/// Comments written around the two `:` of a `min : typ : max` delay
/// (IEEE 1800 §28.14):
///
/// ```text
/// min /*before_typ*/ : /*after_typ*/ typ /*before_max*/ : /*after_max*/ max
/// ```
///
/// Boxed by its holder for the reason every expression-level slot is: `Expr`
/// is walked recursively and its size is pinned at 96 bytes.
#[derive(Debug, Clone, Default)]
pub struct MinTypMaxComments {
/// Between `min` and the first `:`.
pub before_typ: Vec<Comment>,
/// Just after the first `:`.
pub after_typ: Vec<Comment>,
/// Between `typ` and the second `:`.
pub before_max: Vec<Comment>,
/// Just after the second `:`.
pub after_max: Vec<Comment>,
}
/// 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>,
}
/// 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.
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,
}