//! Statements. //! //! [`Parser::parse_stmt`] is the entry; [`Parser::parse_keyword_stmt`] is //! the dispatch table from a keyword to its grammar, and the rest are the //! statements with enough shape to deserve their own function: `if`, //! `case`, `for`/`foreach`, assignments, and the sensitivity lists an //! `always` or event control takes. use super::*; /// The three pieces a `foreach` header's `array[i, j]` yields: what is /// iterated, the loop variables, and the comments written around their /// bracket. Both callers — the statement and the constraint item — store all /// three. pub(super) struct ForeachTarget { pub(super) expr: Expr, pub(super) vars: Vec, pub(super) comments: Box, } impl<'a> Parser<'a> { /// Statements nest through blocks and every compound statement. Gated. pub(super) fn parse_stmt(&mut self) -> PResult { self.enter()?; let out = self.parse_stmt_inner(); self.leave(); out } fn parse_stmt_inner(&mut self) -> PResult { let start = self.here(); let mut meta = self.take_meta(); while self.cur().kind == TokenKind::Attribute { meta.attrs.push(self.take_raw_text()); let tok = &mut self.tokens[self.pos]; meta.leading.append(&mut tok.leading); } let mark = ItemMark { pos: self.pos, conds: self.open_conds, diags: self.diagnostics.len() }; // Nothing may leak from the statement before this one into this // statement's own `;` slot. self.semi_comments.clear(); let kind = match self.parse_stmt_kind() { Ok(kind) => kind, Err(e) => self.split_conditional_stmt(&mark, e)?, }; let before_semi = std::mem::take(&mut self.semi_comments); debug_assert!( before_semi.is_empty() || kind.takes_semi(), "only a kind that wrote a `;` may own the gap in front of it" ); let span = self.span_from(start); if meta.trailing.is_none() { meta.trailing = self.take_trailing(); } Ok(Stmt { meta, kind, before_semi, span }) } /// The statement half of [`Parser::split_conditional_item`]: a statement a /// region opened inside it splits becomes a verbatim block. /// /// `jtag_dtm_reg_block.sv:173` is the corpus shape — a `` `ifdef `` between /// two named arguments of a call, deep inside a function body: /// /// ```verilog /// abits.configure( /// .volatile(0), /// `ifdef USE_DMI_INTERFACE /// .reset(32'h10), /// `else /// .reset(32'h07), /// `endif /// .has_reset(1)); /// ``` /// /// Only the **opening** shape is recognized here. The closing one is /// item-scope by construction: [`Parser::open_conds`] counts the /// `` `ifdef ``s consumed as *items*, so `mark.conds` inside a body would /// be answering a question about a different scope. Nothing in the corpus /// asks for it, and guessing would widen the net for no evidence. /// /// Running here rather than only at item level is what keeps the capture /// at the innermost construct: a statement failure that reached /// `parse_item_inner` would be scanned from the enclosing `module` or /// `class` keyword instead. fn split_conditional_stmt(&mut self, mark: &ItemMark, err: ParseError) -> PResult { if self.at_opening_split(mark) { if let Some(end_pos) = self.scan_opening_split_extent(mark) { return Ok(StmtKind::Verbatim(self.capture_split(mark, end_pos))); } } Err(err) } fn parse_stmt_kind(&mut self) -> PResult { if self.at_macro_item() || self.at_spaced_macro_call() { return Ok(StmtKind::MacroStmt(self.parse_macro_call()?)); } // A concurrent assertion is legal wherever a statement is, and the // `property` keyword is what tells it apart from the immediate // `assert (expr)` handled below. if self.at_concurrent_assertion() { return self.parse_assertion_stmt(); } // `expect (a ##1 b) else $error;` — the one assertion whose keyword is // not reserved, so what is inside the parentheses is what tells it // from a task call. See [`Parser::at_expect_statement`]. if self.at_expect_statement() { return self.parse_expect_stmt(); } // A statement label (IEEE 1800 §9.3.5): `check_decode: assert (...)`. // It is read only here, where a statement is expected — a case item's // `LABEL:` is read by `parse_case_body`, which never reaches this // function with the label still in front of it. The concurrent // assertion above claims `label : assert property` first, because // that whole construct is captured verbatim, label included. if self.cur().kind == TokenKind::Ident && self.nth(1).is_sym(":") { let Name { text: name, span: name_span } = self.expect_name()?; self.expect_sym(":")?; let stmt = Box::new(self.parse_stmt()?); return Ok(StmtKind::Labeled { name, name_span, stmt }); } let t = self.cur(); if t.kind == TokenKind::Directive { return Ok(StmtKind::Directive(self.take_raw_text())); } if t.is_sym(";") { self.skip(); return Ok(StmtKind::Null); } if t.is_sym("#") { self.skip(); let after_hash = self.take_gap(); let delay = self.parse_delay_value()?; let stmt = if self.eat_stmt_semi() { None } else { Some(Box::new(self.parse_stmt()?)) }; return Ok(StmtKind::Timing { control: TimingControl::Delay { after_hash, expr: delay }, stmt, }); } if t.is_sym("@") { self.skip(); let sens = self.parse_sens_list()?; 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("->") || t.is_sym("->>") { return self.parse_event_trigger(); } if t.kind == TokenKind::Keyword { return self.parse_keyword_stmt(); } // Fallback: assignment or expression statement. 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 { 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> { 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) -> PResult { self.expect_kw("if")?; let after_kw = self.take_before_open("("); self.expect_sym("(")?; let cond = self.cond_or_recover()?; let recovered = cond.is_error(); self.expect_after_recovery(")", recovered)?; let then = Box::new(self.body_after_recovery(recovered)?); let mut else_comments = Vec::new(); let els = if self.cur().is_kw("else") { // Whatever was written in the gap before `else` stays on the // keyword's left; the then-branch has already taken its own // trailing comment. else_comments = self.take_dangling(); self.skip(); Some(Box::new(self.parse_stmt()?)) } else { None }; Ok(StmtKind::If { qualifier, after_kw, cond, then, else_comments, els }) } pub(super) fn parse_case_stmt(&mut self, qualifier: Option) -> PResult { let kw = self.bump().text; let after_kw = self.take_before_open("("); self.expect_sym("(")?; let expr = self.cond_or_recover()?; self.expect_after_recovery(")", expr.is_error())?; // `case (x) inside` — the same statement with one extra token, whose // labels may be `[lo:hi]` ranges (handled by `parse_expr_item`). let inside = self.eat_kw("inside"); let (items, dangling) = self.parse_case_body()?; Ok(StmtKind::Case { qualifier, kw, after_kw, expr, inside, items, dangling }) } /// The `label : statement` items of a `case`/`randcase` body, the /// comments left dangling before `endcase`, and the `endcase` itself. /// A `randcase` item's label is its weight expression, so the two bodies /// are the same grammar. pub(super) fn parse_case_body(&mut self) -> PResult<(Vec, Vec)> { let mut items = Vec::new(); while !self.at_body_end("endcase") { let start = self.here(); let mut meta = self.take_meta(); let mut before_colon = Vec::new(); let labels = if self.eat_kw("default") { // The `:` after `default` is optional (IEEE 1800 §12.5), so // the gap only belongs to the item when one was written. before_colon = self.gap_before(":"); let _ = self.eat_sym(":"); Vec::new() } else { let first = self.parse_expr_item()?; let labels = self.parse_expr_list(first, ":")?; self.expect_sym(":")?; labels }; let stmt = self.stmt_or_recover()?; let span = self.span_from(start); if meta.trailing.is_none() { meta.trailing = self.take_trailing(); } items.push(CaseItem { meta, labels, before_colon, stmt, span }); } let dangling = self.take_dangling(); self.expect_closer("endcase")?; Ok((items, dangling)) } /// The `arr [ i, j ]` of a `foreach` header, split into the array and the /// loop variables (IEEE 1800 §12.7.3). /// /// The array is a package-scoped or hierarchical name that may carry /// index and member selects along the way — `riscv_instr_pkg::supported_isa` /// (`riscv_instr.sv:156`), `program_h[id].sub_program_id` /// (`riscv_callstack_gen.sv:183`), `paths[0].slices` /// (`csr_utils_pkg.sv:290`) — so it is parsed as a postfix chain. The /// bracket group the `)` follows is the one that declares the loop /// variables; every earlier one is an ordinary select. pub(super) fn parse_foreach_target(&mut self) -> PResult { let outer_links = self.links; let out = self.parse_foreach_target_inner(); self.links = outer_links; out } fn parse_foreach_target_inner(&mut self) -> PResult { let start = self.here(); let name = self.expect_ident()?; let mut expr = self.expr_at(start, ExprKind::Ident(name)); loop { self.link()?; let t = self.cur(); if t.is_sym("[") { // The last bracket group is the loop-variable list, not a // segment of the target: it is the one whose `]` is followed // by the header's `)`. let after = self.scan_matching(self.pos, "[", "]"); if self.tokens.get(after).is_some_and(|t| t.is_sym(")")) { break; } } else if !t.is_sym(".") && !t.is_sym("::") { break; } expr = self.parse_postfix_segment(start, expr)?; } let mut comments = SegmentComments { before_open: self.take_gap(), ..Default::default() }; self.expect_sym("[")?; comments.after_open = self.take_gap(); let mut vars = Vec::new(); if !self.cur().is_sym("]") { vars.push(self.parse_foreach_var()?); while self.cur().is_sym(",") { if let Some(last) = vars.last_mut() { last.after = self.take_gap(); } self.skip(); vars.push(self.parse_foreach_var()?); } } if let Some(last) = vars.last_mut() { last.after = self.gap_before("]"); } else { comments.before_close = self.gap_before("]"); } self.expect_sym("]")?; Ok(ForeachTarget { expr, vars, comments: Box::new(comments) }) } /// One loop-variable slot of a `foreach`'s bracket list. A dimension may /// be **skipped** (IEEE 1800 §12.7.3) by writing nothing in its slot — /// `foreach (cfg.mem_bkdr_util_h[, bank])` /// (`ip_templates/flash_ctrl/dv/env/flash_ctrl_env.sv:43`) iterates only /// the second dimension. A skipped slot is an empty name at the point it /// was written: it declares nothing, and it prints as nothing. fn parse_foreach_var(&mut self) -> PResult { let before = self.take_gap(); if self.cur().is_sym(",") || self.cur().is_sym("]") { let here = self.here(); let name = Name { text: String::new(), span: self.span_from(here) }; return Ok(ForeachVar { name, before, after: Vec::new() }); } let name = self.expect_name()?; Ok(ForeachVar { name, before, after: Vec::new() }) } pub(super) fn parse_for_step(&mut self) -> PResult { let mark = self.pending_trailing.len(); let lhs = self.parse_unary()?; let op = self.cur().text.clone(); if self.cur().kind == TokenKind::Symbol && (ASSIGN_OPS.contains(&op.as_str()) || op == "<=") { let before = self.take_around(mark); self.skip(); let after = self.take_gap(); let rhs = self.parse_expr()?; Ok(ForStep::Assign(SimpleAssign { lhs, op, op_comments: Box::new(BinaryComments { before, after }), rhs, })) } else { Ok(ForStep::Expr(lhs)) } } pub(super) fn parse_assign_or_expr_stmt(&mut self) -> PResult { // Declaration with a user-defined type: `my_t x;` / `my_t x = e;` / // `my_t [N-1:0] x;`. An assignment (`x[i] = 1;`) is not one: nothing // that could be a declarator name follows its brackets. if self.cur().kind == TokenKind::Ident && self.at_typed_declarator() { let d = self.parse_data_decl()?; return Ok(StmtKind::VarDecl(d)); } // The statement's own meta drained the pending comments, so anything // trailing from here on was written inside this statement. let mark = self.pending_trailing.len(); let lhs = self.parse_unary()?; let op = self.cur().text.clone(); let is_assign = self.cur().kind == TokenKind::Symbol && (ASSIGN_OPS.contains(&op.as_str()) || op == "<="); if is_assign { // Comments on either side of the operator stay on their side of // it (`x[6:0] /* opcode */ = v;`); left in the pending buffers // they would be lost and the safety net would refuse the file. let op_comments = self.take_around(mark); self.skip(); let rhs_comments = self.take_around(mark); let timing = if self.cur().is_sym("#") { self.skip(); Some(TimingControl::Delay { after_hash: self.take_gap(), expr: self.parse_delay_value()?, }) } else if self.cur().is_sym("@") { self.skip(); Some(TimingControl::Event(self.parse_sens_list()?)) } else { None }; let rhs = self.parse_expr()?; self.expect_stmt_semi()?; Ok(StmtKind::Assign { lhs, op, op_comments, rhs_comments, timing, rhs }) } else { self.expect_stmt_semi()?; Ok(StmtKind::ExprStmt(lhs)) } } /// The `hierarchical_identifier` of a paren-less event control: /// `.`-separated names, each with an optional bit-select /// (IEEE 1800 §A.9.3) — `@cfg.agents["ping"].vif.sender_cb`. Both segment /// openers are safe to take greedily, because the statement that follows /// an event control cannot begin with `.` or `[`. /// /// One link per segment: the loop wraps what it has already built, which /// is the shape `docs/features/recursion-limit/README.md` requires the /// chain budget for. The caller restores the count it started from. fn parse_bare_event_name(&mut self) -> PResult { let start = self.here(); let name = self.expect_ident()?; let mut expr = self.expr_at(start, ExprKind::Ident(name)); loop { let dotted = self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident; if !dotted && !self.cur().is_sym("[") { return Ok(expr); } self.link()?; expr = self.parse_postfix_segment(start, expr)?; } } pub(super) fn parse_sens_list(&mut self) -> PResult { // The `@` is consumed by the caller, so the gap that ends here is the // one written after it. let after_at = self.take_gap(); if self.cur().is_sym("*") { // `@*` without parens — the gap after the `@` is the `*`'s own // `before` slot, which the formatter prints in the same place. self.skip(); return Ok(SensList::Star { before: after_at, after: Vec::new() }); } if self.cur().kind == TokenKind::Ident { // `@ident` / `@a.b` without parens; recorded as `Bare` so the // formatter prints no parens back — inventing them is a // token-stream change the safety net refuses. // A chain, so it carries the chain budget and releases it the way // `parse_postfix` does — by restoring the count it started from. let outer_links = self.links; let out = self.parse_bare_event_name(); self.links = outer_links; return out.map(|expr| SensList::Bare { expr, after_at }); } if self.cur().is_sym("(") && self.nth(1).is_sym("*") { // `@( /* c */ * /* d */ )`: the comments belong to the star, not // to whatever node comes next. let mut before = after_at; before.append(&mut self.take_trailing_here()); self.skip(); // ( before.append(&mut self.take_leading_here()); let mut after = self.take_trailing_here(); self.skip(); // * after.append(&mut self.take_leading_here()); self.expect_sym(")")?; return Ok(SensList::Star { before, after }); } self.expect_sym("(")?; let mut items = Vec::new(); let mut sep = None; loop { let mut meta = self.take_meta(); let mut after_edge = Vec::new(); let edge = { let t = self.cur(); if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") { let kw = self.bump().text; // `@(posedge /*c*/ clk)` — the gap after the keyword is // the item's, not the next node's. after_edge = self.take_gap(); Some(kw) } else { None } }; let expr = self.parse_expr()?; // `@(posedge clk iff enable)` — IEEE 1800 §9.4.2 lets each term // carry its own gating condition. `iff` is a keyword, so the // expression above stops in front of it on its own. let iff = if self.eat_kw("iff") { Some(self.parse_expr()?) } else { None }; // Comments written before the separator — either spelling — or // before the closing `)` stay on this item's side of it. if self.cur().is_sym(",") || self.cur().is_kw("or") || self.cur().is_sym(")") { self.take_before(&mut meta); } items.push(SensItem { meta, sep, edge, after_edge, expr, iff }); // Both separators are legal in the same list; each is kept as // written so the formatter never rewrites one as the other. sep = if self.eat_sym(",") { Some(SensSep::Comma) } else if self.eat_kw("or") { Some(SensSep::Or) } else { break; }; } self.expect_sym(")")?; Ok(SensList::List { items, after_at }) } /// [`Parser::take_gap`], but only when the cursor really is on `sym` — /// the gap belongs to this construct only if the token that closes it was /// written. [`Parser::take_before_open`] is the same idea; this is it /// spelled for a closer rather than an opener. /// Consume the `;` that ends a statement, recording the comments written /// in front of it on [`Parser::semi_comments`] for /// [`Parser::parse_stmt_inner`] to move onto the statement. pub(super) fn expect_stmt_semi(&mut self) -> PResult<()> { self.semi_comments = self.gap_before(";"); self.expect_sym(";")?; Ok(()) } /// The same for the sites that *read* the `;` to decide the statement's /// shape (`#10;` versus `#10 x = 1;`). Takes nothing when the cursor is /// not on a `;`, because [`Parser::gap_before`] does not. pub(super) fn eat_stmt_semi(&mut self) -> bool { let gap = self.gap_before(";"); if self.eat_sym(";") { self.semi_comments = gap; true } else { false } } }