//! 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), 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>, expr: Box, }, Binary { lhs: Box, op: String, rhs: Box, /// Boxed to keep `Expr` small, as for `TernaryComments`. comments: Box, }, Ternary { cond: Box, then: Box, els: Box, /// Boxed to keep `Expr` small: a ternary with comments in it is rare, /// but every `Expr` would otherwise carry four empty vectors. comments: Box, }, Call { callee: Box, args: Vec, /// 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, }, /// 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), Index { base: Box, index: Box, /// `q /*a*/ [ /*b*/ i /*c*/ ]`. comments: Box, }, Range { base: Box, op: String, msb: Box, lsb: Box, /// Every slot of `q /*a*/ [ /*b*/ m /*c*/ : /*d*/ l /*e*/ ]`. comments: Box, }, Member { base: Box, name: String, /// `a /*a*/ . /*b*/ b`. comments: Box, }, Scope { base: Box, name: String, /// `pkg /*a*/ :: /*b*/ item`. comments: Box, }, /// 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, params: RawText, }, Concat(Vec), Repl { count: Box, /// Elements carry their comments the way a concatenation's do, so a /// comment inside a replication stays inside it. inner: Vec, }, /// 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>, /// The stream expressions, carrying their comments the way a /// concatenation's elements do. inner: Vec, /// The three gaps the two nested brace pairs open. Boxed to keep /// `Expr` small, as for `TernaryComments`. comments: Box, }, /// `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, range: Box, }, Paren { inner: Box, /// Comments written just inside the `(`. before: Vec, /// Comments left over just before the `)`. after: Vec, }, /// `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, /// Comments written in the cast's own four slots. comments: Box, expr: Box, /// 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), /// 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, inner: Vec, }, Postfix { expr: Box, op: String, /// Comments written between the operand and the operator /// (`i /*c*/ ++`). Boxed for the reason [`ArgComments`] gives. comments: Box>, }, Inside { lhs: Box, ranges: Vec, /// Comments written on either side of the `inside` word, kept per /// side the way every other binary operator's are. comments: Box, }, /// `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, /// 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, }, /// `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, arg: Box, /// Boxed to keep `Expr` small, as for `TernaryComments`. comments: Box, }, /// `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, block: Box, /// Boxed to keep `Expr` small, as for `TernaryComments`. comments: Box, }, /// `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, /// Comments written on either side of the `dist` word, kept per side /// the way a binary operator's are. comments: Box, weights: Vec, }, /// 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, /// 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, }, /// `[a:b]` inside an `inside` range list or value range. ValueRange { lo: Box, hi: Box, /// `[ /*a*/ lo /*b*/ : /*c*/ hi /*d*/ ]` — the same four inner slots /// an [`ExprKind::Range`] has, read by the same shared parse. comments: Box, }, /// 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, typ: Box, max: Box, /// What was written around the two `:`. comments: Box, }, } /// 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, /// Just after the first `:`. pub after_typ: Vec, /// Between `typ` and the second `:`. pub before_max: Vec, /// Just after the second `:`. pub after_max: Vec, } /// 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, /// Just after that token. pub after_open: Vec, /// Between the first operand and the `:` / `+:` / `-:` of a range. pub before_op: Vec, /// Just after that operator. pub after_op: Vec, /// Just before the closing `]`. pub before_close: Vec, } 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, /// Between the `'` and the `(` (or the `{` of a pattern). pub after_tick: Vec, /// Just inside the `(`. pub after_open: Vec, /// Just before the `)`. pub before_close: Vec, } 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, /// After `tagged`, if written. pub after_tagged: Vec, /// After `packed`, if written. pub after_packed: Vec, /// After the signing word, if written. pub after_signing: Vec, } /// 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, /// Between the name and the `(`. pub before_open: Vec, /// Just inside the `(`. pub after_open: Vec, /// Between the value and the closing `)` (`.src(5'd0 /* x0 */)`), /// printed back inside the parens. pub close: Vec, } /// 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, /// Between the operator and the right operand. These force the chain to /// break, with the right operand starting the new line. pub after: Vec, } /// 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, /// Between `?` and the then-branch. pub after_question: Vec, /// Between the then-branch and `:`. pub before_colon: Vec, /// Between `:` and the else-branch. pub after_colon: Vec, } /// 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, /// 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, } 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, /// Between `with` and the `(` or `{` that follows it. pub after_kw: Vec, } /// 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, /// Between the direction (or the slice size) and the inner `{`. pub before_inner: Vec, /// Between the inner `}` and the outer `}`. pub before_close: Vec, } /// 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, /// The range's second operand; `None` for the single-index spelling. pub lsb: Option, /// `[ /*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, 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, }