//! The operator grammar: precedence climbing from implication down through //! ternary, binary, unary and postfix. The leaves — literals, names, casts, //! concatenations, patterns — are [`super::primary`]. use super::*; impl<'a> Parser<'a> { pub fn parse_expr(&mut self) -> PResult { self.parse_implication() } /// The implication operators `->` and `<->` (IEEE 1800 §11.3.2): the /// lowest-precedence binary operators, below `? :`, right-associative. /// /// They sit above [`Parser::parse_ternary`] rather than in the /// precedence-climbing table because everything in that table binds /// tighter than `? :`. A `->` is only read as an operator here, *after* /// an operand — `-> ev;` at statement position is still an event trigger, /// which `parse_stmt_kind` takes before any expression is parsed. fn parse_implication(&mut self) -> PResult { let mark = self.pending_trailing.len(); let start = self.here(); let lhs = self.parse_ternary()?; if !self.cur().is_sym("->") && !self.cur().is_sym("<->") { return Ok(lhs); } let before = self.take_around(mark); let op = self.bump().text; let after = self.take_around(mark); // Right-associative: `a -> b -> c` is `a -> (b -> c)`, so the chain // recurses and is gated. Only the recursion is: an expression with no // `->` in it must cost no nesting budget, or every other construct's // depth limit would halve. self.enter()?; let rhs = self.parse_implication(); self.leave(); let rhs = rhs?; Ok(self.expr_at( start, ExprKind::Binary { lhs: Box::new(lhs), op, rhs: Box::new(rhs), comments: Box::new(BinaryComments { before, after }), }, )) } /// The gate for the whole expression grammar: every expression recursion /// (parens, concatenations, call arguments, index expressions, and the /// `? :` chain itself) comes back through here. pub(super) fn parse_ternary(&mut self) -> PResult { self.enter()?; let out = self.parse_ternary_inner(); self.leave(); out } fn parse_ternary_inner(&mut self) -> PResult { let mark = self.pending_trailing.len(); let start = self.here(); let cond = self.parse_binary(1)?; if self.cur().is_sym("?") { // Each of the four gaps inside a `? :` can hold comments; kept // apart so none of them drifts across the `?` or the `:`. let before_question = self.take_around(mark); self.bump(); let after_question = self.take_around(mark); let then = self.parse_expr()?; let before_colon = self.take_around(mark); self.expect_sym(":")?; let after_colon = self.take_around(mark); let els = self.parse_ternary()?; Ok(self.expr_at( start, ExprKind::Ternary { cond: Box::new(cond), then: Box::new(then), els: Box::new(els), comments: Box::new(TernaryComments { before_question, after_question, before_colon, after_colon, }), }, )) } else { Ok(cond) } } fn binary_prec(&self) -> Option { let t = self.cur(); if t.is_kw("inside") { return Some(7); } if t.kind != TokenKind::Symbol { return None; } // `|->` lexes as `|` + `->` and is the SVA implication operator, never // a bitwise or: `->` starts no expression, so `a | ->b` cannot be // written. Said here rather than behind an SVA flag because it is // true everywhere. Without it every `a |-> b` in the language reaches // this table, takes the `|`, and fails on the `->`. if t.is_sym("|") && self.nth(1).is_sym("->") && self.adjacent(2) { return None; } let p = match t.text.as_str() { "||" => 1, "&&" => 2, "|" => 3, "^" | "^~" | "~^" => 4, "&" => 5, "==" | "!=" | "===" | "!==" | "==?" | "!=?" => 6, "<" | "<=" | ">" | ">=" => 7, "<<" | ">>" | "<<<" | ">>>" => 8, "+" | "-" => 9, "*" | "/" | "%" => 10, "**" => 11, _ => return None, }; Some(p) } /// Operator chains grow the tree one layer per operator without any /// parser recursion, so they are bounded by [`MAX_CHAIN_LENGTH`]; the /// links this chain adds are released when it is finished. fn parse_binary(&mut self, min_prec: u8) -> PResult { let outer_links = self.links; let out = self.parse_binary_inner(min_prec); self.links = outer_links; out } fn parse_binary_inner(&mut self, min_prec: u8) -> PResult { let mark = self.pending_trailing.len(); let mut lhs = self.parse_unary()?; while let Some(prec) = self.binary_prec() { if prec < min_prec { break; } if self.cur().is_kw("inside") { // The word is an operator like any other, and keeps the // comments written on either side of it the same way. let before = self.take_around(mark); self.bump(); let after = self.take_around(mark); let comments = Box::new(BinaryComments { before, after }); // `x inside `MACRO` — the macro expands to the `{...}` set, // so it stands in for one (corpus // `opentitan/hw/ip/uart/dv/env/uart_scoreboard.sv:155`). if self.cur().is_macro() { let set = self.bump().text; self.link()?; let start = lhs.span.start; lhs = self.expr_at( start, ExprKind::InsideMacro { lhs: Box::new(lhs), set, comments }, ); continue; } self.expect_sym("{")?; let mut ranges: Vec = Vec::new(); loop { let item_start = self.here(); let mut meta = self.take_meta(); let expr = if self.cur().is_sym("[") { self.parse_value_range()? } else { self.parse_expr()? }; let item_span = self.span_from(item_start); self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); } ranges.push(ExprItem { meta, expr, span: item_span }); if !more { break; } } if let Some(last) = ranges.last_mut() { self.take_before_sep(&mut last.meta, "}"); } self.expect_sym("}")?; self.link()?; let start = lhs.span.start; lhs = self.expr_at(start, ExprKind::Inside { lhs: Box::new(lhs), ranges, comments }); continue; } // Comments between the operand and the operator belong to this // node; left where they are they would drift past the operator. let before = self.take_around(mark); let op = self.bump().text; // Comments between the operator and the right operand belong here // too; left where they are they would drift past the operand. let after = self.take_around(mark); let rhs = self.parse_binary(prec + 1)?; self.link()?; let start = lhs.span.start; lhs = self.expr_at( start, ExprKind::Binary { lhs: Box::new(lhs), op, rhs: Box::new(rhs), comments: Box::new(BinaryComments { before, after }), }, ); } Ok(lhs) } /// Stacked prefix operators (`~~~~x`) recurse here directly, without /// passing through `parse_ternary`. Gated. pub(super) fn parse_unary(&mut self) -> PResult { self.enter()?; let out = self.parse_unary_inner(); self.leave(); out } fn parse_unary_inner(&mut self) -> PResult { let t = self.cur(); if t.kind == TokenKind::Symbol && matches!( t.text.as_str(), "!" | "~" | "+" | "-" | "&" | "|" | "^" | "~&" | "~|" | "~^" | "^~" | "++" | "--" ) { let start = self.here(); let op = self.bump().text; let comments = self.take_gap(); let expr = self.parse_unary()?; return Ok(self.expr_at( start, ExprKind::Unary { op, comments: Box::new(comments), expr: Box::new(expr) }, )); } self.parse_postfix() } /// True if the current token continues a postfix chain. /// /// `base` is what has been parsed so far: a `#( ... )` only continues a /// *name* (`uvm_config_db#(virtual bus_if)::get(...)`), never an arbitrary /// expression, so `x #(y)` after anything else stays what it was. fn at_postfix_segment(&self, base: &Expr) -> bool { if self.at_type_params() && matches!(base.kind, ExprKind::Ident(_) | ExprKind::Scope { .. }) { return true; } let t = self.cur(); t.is_sym(".") || t.is_sym("::") || (t.is_sym("[") && !self.at_repeat_bracket()) || t.is_sym("(") || (t.is_sym("'") && self.nth(1).is_sym("(")) // `ty'{...}` — a cast over an assignment pattern. Only a base // that may stand left of a cast opens one, so a bare `'{...}` // literal still reaches `parse_primary` as the whole expression. || (t.is_sym("'{") && self.is_cast_base(base)) || t.is_sym("++") || t.is_sym("--") // `with ( ... )` (an array method's iterator argument), // `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("["))) } /// True when the `[` at the cursor opens a transition or consecutive /// repetition — `[* 3]`, `[-> 2]`, `[= 1]`, `[+]` (IEEE 1800 §19.5.1.2, /// §16.9.2) — rather than an index or a part select. /// /// No index expression can start with `*`, `->` or `=`, and none *is* the /// single token `+`, so this needs no context: it says "that `[` is not /// an index" everywhere, which was already true and is now acted on. /// Without it `1'b0[*1:10]` would send the whole covergroup down the /// verbatim fallback, because [`Parser::parse_postfix_inner`] would take /// the `[` and then fail on the `*`. pub(super) fn at_repeat_bracket(&self) -> bool { if !self.cur().is_sym("[") { return false; } let next = self.nth(1); if next.kind != TokenKind::Symbol { return false; } matches!(next.text.as_str(), "*" | "->" | "=") || (next.text == "+" && self.nth(2).is_sym("]")) } /// Postfix segments are parsed by a loop, but each one wraps the /// expression so far in another AST layer, so they are bounded by /// [`MAX_CHAIN_LENGTH`]; the links are released when the chain ends. pub(super) fn parse_postfix(&mut self) -> PResult { let outer_links = self.links; let out = self.parse_postfix_inner(); self.links = outer_links; out } /// One `.name`, `::name`, `[i]` or `[m:l]` segment wrapping `base`, with /// the comments written in each of its fixed slots. /// /// The cursor is on the segment's opening token and `start` is where the /// whole expression began — each segment wraps what came before it, so /// every node in the chain starts at the same offset. This is the single /// owner of the three-branch loop `parse_postfix_inner`, /// [`Parser::parse_foreach_target_inner`] and /// [`Parser::parse_bare_event_name`] each used to write out by hand, and /// each used to lose the same comments in. pub(super) fn parse_postfix_segment(&mut self, start: u32, base: Expr) -> PResult { let mut comments = SegmentComments { before_open: self.take_gap(), ..Default::default() }; let base = Box::new(base); if self.cur().is_sym(".") || self.cur().is_sym("::") { let scoped = self.cur().is_sym("::"); self.bump(); comments.after_open = self.take_gap(); let name = self.expect_ident()?; let comments = Box::new(comments); let kind = if scoped { ExprKind::Scope { base, name, comments } } else { ExprKind::Member { base, name, comments } }; return Ok(self.expr_at(start, kind)); } self.expect_sym("[")?; comments.after_open = self.take_gap(); let a = self.parse_expr()?; let t = self.cur(); if t.is_sym(":") || t.is_sym("+:") || t.is_sym("-:") { comments.before_op = self.take_gap(); let op = self.bump().text; comments.after_op = self.take_gap(); let b = self.parse_expr()?; comments.before_close = self.gap_before("]"); self.expect_sym("]")?; return Ok(self.expr_at( start, ExprKind::Range { base, op, msb: Box::new(a), lsb: Box::new(b), comments: Box::new(comments), }, )); } comments.before_close = self.gap_before("]"); self.expect_sym("]")?; Ok(self.expr_at( start, ExprKind::Index { base, index: Box::new(a), comments: Box::new(comments) }, )) } /// 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 { 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 { let mut expr = self.parse_primary()?; while self.at_postfix_segment(&expr) { self.link()?; // Every segment wraps what came before, so each new node starts // where the expression so far started. let start = expr.span.start; let t = self.cur(); if t.is_sym("#") { let params = self.parse_type_params()?; expr = self.expr_at(start, ExprKind::Parameterized { base: Box::new(expr), params }); } else if t.is_sym(".") || t.is_sym("::") || t.is_sym("[") { expr = self.parse_postfix_segment(start, expr)?; } else if t.is_sym("(") { // Comments written around the brackets have no element to // attach to: before the `(`, and inside an empty `()`. let mut comments = CallComments { before_open: self.take_before_open("("), ..CallComments::default() }; self.bump(); let mut args = Vec::new(); if !self.cur().is_sym(")") { let arg_start = self.here(); let meta = self.take_meta(); // A named first argument (`csr_wr(.ptr(x), ...)`) takes // the same dispatch later elements get in // `parse_expr_item`; anything else may be a type // (`$bits(int)`). let first_expr = if self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident { self.parse_named_arg()? } else if self.at_omitted_element() { self.expr_at(arg_start, ExprKind::Empty(Vec::new())) } else { self.parse_expr_or_type()? }; let first = ExprItem { meta, expr: first_expr, span: self.span_from(arg_start) }; args = self.parse_expr_list(first, ")")?; } else { // Only what was written *inside* the empty `()`: a comment // queued from before the callee belongs to whoever owns // the place it was written, not to this argument list. comments.dangling = self.take_gap(); } self.expect_sym(")")?; expr = self.expr_at( start, ExprKind::Call { callee: Box::new(expr), args, comments: Box::new(comments) }, ); } else if t.is_kw("with") { let mut comments = WithComments { before_kw: self.take_dangling(), ..WithComments::default() }; if self.nth(1).is_sym("{") { self.expect_kw("with")?; comments.after_kw = self.take_before_open("{"); let block = Box::new(self.parse_with_constraint()?); expr = self.expr_at( start, ExprKind::WithConstraint { base: Box::new(expr), block, comments: Box::new(comments), }, ); } else 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("("); // `( expression )` — an ordinary parenthesized primary, // which is what IEEE 1800 §7.12 spells here. let arg = self.parse_primary()?; expr = self.expr_at( start, ExprKind::With { base: Box::new(expr), arg: Box::new(arg), comments: Box::new(comments), }, ); } } else if (t.is_sym("'") && self.nth(1).is_sym("(")) || t.is_sym("'{") { // Cast: `expr'(x)`, or `expr'{...}` over an assignment // pattern (IEEE 1800 §10.9.1). The casting type is a // `constant_primary` (IEEE 1800 §6.24.1): a name, a // package-scoped or hierarchical name, a size, a // parenthesized constant expression — // `(NumLevels)'(unsigned'(j))` (corpus // `common_cells/src/lzc.sv:67`) — or a system function call, // `$bits(x)'(y)` / `$clog2(N)'(y)`. if !self.is_cast_base(&expr) { return self.error("unsupported cast base expression"); } let is_pattern = t.is_sym("'{"); let mut comments = CastComments { before_tick: self.take_gap(), ..Default::default() }; if is_pattern { let pattern_start = self.here(); let inner = self.parse_assign_pattern(pattern_start)?; expr = self.expr_at( start, ExprKind::Cast { ty: Box::new(expr), comments: Box::new(comments), expr: Box::new(inner), pattern: true, }, ); } else { self.bump(); // ' comments.after_tick = self.take_gap(); self.bump(); // ( comments.after_open = self.take_gap(); let inner = self.parse_expr()?; comments.before_close = self.gap_before(")"); self.expect_sym(")")?; expr = self.expr_at( start, ExprKind::Cast { ty: Box::new(expr), comments: Box::new(comments), expr: Box::new(inner), pattern: false, }, ); } } else { // `++` / `--`, the only remaining segment kind. let comments = self.take_gap(); let op = self.bump().text; expr = self.expr_at( start, ExprKind::Postfix { expr: Box::new(expr), op, comments: Box::new(comments) }, ); } } Ok(expr) } }