//! Classes and their constraint blocks: the class header and `extends` //! clause, and the `constraint` sub-grammar (IEEE 1800 §18.5) with its //! `dist`, `solve … before`, `soft` and `foreach` items. See //! `docs/features/classes/README.md` and //! `docs/features/constraint-bodies/README.md`. use super::stmt::ForeachTarget; use super::*; impl<'a> Parser<'a> { /// `[virtual] class [lifetime] name [#(params)] [extends base [#(...)]] /// [implements a, b]; items endclass [: label]`. /// /// The body is parsed by the ordinary item loop, so everything that /// already works at module scope — declarations, `typedef`, `localparam`, /// `import`, directives, macro invocations — works inside a class for /// free, and nesting is charged against the item budget by `parse_item`. pub(super) fn parse_class(&mut self) -> PResult { let mut prefix = self.take_member_prefix(); // `interface class ic; ... endclass` (IEEE 1800 §8.26). The word rides // in the prefix beside `virtual`, because that is what it is: a // keyword written in front of `class`, printed back in source order. // What it changes is the body's *legality* — only pure virtual method // prototypes, parameters and typedefs may stand in one — and legality // is a checker's business, not a formatter's. if self.cur().is_kw("interface") && self.nth(1).is_kw("class") { let text = self.bump().text; prefix.push(Qualifier { text, after: self.take_gap() }); } self.expect_kw("class")?; let mut before_name = self.take_gap(); let lifetime = if self.cur().is_kw("static") || self.cur().is_kw("automatic") { let kw = self.bump().text; before_name.append(&mut self.take_gap()); Some(kw) } else { None }; let Name { text: name, span: name_span } = self.expect_name()?; let param_comments = self.take_before_open("#"); let params = self.parse_param_port_list()?; let extends = if self.cur().is_kw("extends") { Some(self.parse_class_extends()?) } else { None }; let mut implements = Vec::new(); if self.eat_kw("implements") { loop { let (text, span) = self.parse_scoped_name()?; implements.push(Name { text, span }); if !self.eat_sym(",") { break; } } } let before_semi = self.gap_before(";"); self.expect_sym(";")?; let mut items = Vec::new(); while !self.at_body_end("endclass") { items.push(self.item_or_recover()?); } let dangling = self.take_dangling(); self.expect_closer("endclass")?; let (end_label_comments, end_name) = self.parse_label_with()?; let (end_label, end_label_span) = split_label(end_name); Ok(ClassDecl { prefix, before_name, lifetime, name, name_span, param_comments, param_after_hash: params.after_hash, param_ports: params.ports, param_directives: params.directives, param_dangling: params.dangling, extends, implements, before_semi, items, dangling, end_label_comments, end_label, end_label_span, }) } /// `extends base [#( overrides )]`. The overrides are the same /// [`Connection`] list an instantiation's `#( ... )` uses. fn parse_class_extends(&mut self) -> PResult { let start = self.here(); self.expect_kw("extends")?; let (name, name_span) = self.parse_scoped_name()?; let param_comments = self.take_before_open("#"); let mut params = None; let mut after_hash = Vec::new(); let mut param_directives = Vec::new(); if self.cur().is_sym("#") { self.bump(); after_hash = self.take_gap(); self.expect_sym("(")?; let mut list = Vec::new(); self.take_list_directives(&mut param_directives, 0); if !self.cur().is_sym(")") { loop { list.push(self.element_or_recover(|p| p.parse_connection())?); if let Some(ListElem::Ok(last)) = list.last_mut() { self.take_before_sep(&mut last.meta, ","); } let comma = self.eat_sym(","); if let Some(ListElem::Ok(last)) = list.last_mut() { last.comma = comma; if comma && last.meta.trailing.is_none() { last.meta.trailing = self.take_trailing(); } } let dirs = self.take_list_directives(&mut param_directives, list.len()); if self.list_ends(comma, dirs.any) { break; } } } let n = list.len(); self.take_last_entry_before_close( list.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta), &mut param_directives, n, ); self.close_list(list.iter().any(ListElem::is_error))?; params = Some(list); } Ok(ClassExtends { after_hash, name, name_span, param_comments, params, param_directives, span: self.span_from(start), }) } /// `[qualifiers] constraint [cls::]name { ... }` — or its `constraint c;` /// prototype (IEEE 1800 §18.5). /// /// The body is **parsed**: see [`Parser::parse_constraint_set`]. A body /// that does not fit the constraint grammar rewinds and is captured /// exactly as every constraint was before this round — /// `skip_balanced` over the braces, source bytes copied out by span, an /// [`ItemKind::Verbatim`] leaf whose `col` re-indent contract the /// formatter already honours. That fallback is what keeps this round /// tolerant by construction: the sub-grammar is large and half of it is /// written through macros lucisv does not expand, so the shapes real DV /// code writes are modelled and everything else still formats byte for /// byte and round-trips. /// /// The name may carry a `my_class::` scope — the out-of-block definition /// of an `extern constraint` prototype (IEEE 1800 §18.5.2), written at /// file or package scope, the constraint sibling of /// `function my_class::method(...)` — so it reuses the same scoped-name /// path. Unlike before, both halves are now kept. pub(super) fn parse_constraint(&mut self) -> PResult { let mark = self.rewind_mark(); match self.parse_constraint_decl() { Ok(decl) => Ok(ItemKind::Constraint(decl)), Err(_) => { self.rewind_to(mark); self.constraint_fallbacks += 1; self.parse_constraint_verbatim().map(ItemKind::Verbatim) } } } fn parse_constraint_decl(&mut self) -> PResult { let qualifiers = self.take_member_prefix(); self.expect_kw("constraint")?; let before_name = self.take_gap(); let (scope, name) = self.parse_method_name()?; let after_name = self.take_gap(); if self.eat_sym(";") { return Ok(ConstraintDecl { qualifiers, scope, name, before_name, after_name, body: None, before_semi: Vec::new(), semi: true, }); } let body = self.parse_constraint_block()?; // `constraint c { ... };` — a stray `;` is legal and belongs to the // block, not to the item that follows it. The gap before it is only // this item's when the `;` is really there; otherwise the comments // belong to whatever comes next. let before_semi = self.gap_before(";"); let semi = self.eat_sym(";"); Ok(ConstraintDecl { qualifiers, scope, name, before_name, after_name, body: Some(body), before_semi, semi, }) } /// The pre-`constraint-bodies` capture, unchanged, byte for byte: the /// fallback [`Parser::parse_constraint`] rewinds into, and the reason a /// constraint the grammar does not know still parses, formats and /// round-trips exactly as it did in v0.26.0. fn parse_constraint_verbatim(&mut self) -> PResult { let start = self.here(); let col = self.cur().col; self.take_member_prefix(); self.expect_kw("constraint")?; self.parse_method_name()?; if !self.eat_sym(";") { self.expect_sym("{")?; self.skip_balanced("{", "}")?; self.eat_sym(";"); } Ok(self.verbatim_since(start, col)) } /// A braced `{ constraint_item* }`. Gated, like every other body. fn parse_constraint_block(&mut self) -> PResult { self.enter()?; let out = self.parse_constraint_block_inner(); self.leave(); out } fn parse_constraint_block_inner(&mut self) -> PResult { let start = self.here(); self.expect_sym("{")?; let mut items = Vec::new(); while !self.cur().is_sym("}") { if self.at_eof() { return self.error("expected `}`"); } items.push(self.parse_constraint_item()?); } let dangling = self.take_dangling(); self.expect_sym("}")?; Ok(ConstraintSet { braced: true, items, dangling, span: self.span_from(start) }) } /// A `constraint_set` (IEEE 1800 A.1.10): `{ ... }`, or the single /// unbraced item an implication's right-hand side and a constraint `if` /// body may also be written as. fn parse_constraint_set(&mut self) -> PResult { if self.cur().is_sym("{") { return self.parse_constraint_block(); } let start = self.here(); self.enter()?; let item = self.parse_constraint_item(); self.leave(); Ok(ConstraintSet { braced: false, items: vec![item?], dangling: Vec::new(), span: self.span_from(start), }) } fn parse_constraint_item(&mut self) -> PResult { let start = self.here(); let mut meta = self.take_meta(); let kind = self.parse_constraint_item_kind()?; // One place owns the terminating `;`, so one place owns the gap in // front of it: a comment written there prints on the item's side of // the `;`, which is where the source put it. let mut before_semi = Vec::new(); if kind.takes_semi() { before_semi = self.take_gap(); self.expect_sym(";")?; } let span = self.span_from(start); if meta.trailing.is_none() { meta.trailing = self.take_trailing(); } Ok(ConstraintItem { meta, kind, before_semi, span }) } fn parse_constraint_item_kind(&mut self) -> PResult { // A directive keeps the posture it keeps at item and statement // position: passed through, never evaluated, both arms of an // `` `ifdef `` left standing as ordinary items of the one set. if self.cur().kind == TokenKind::Directive { return Ok(ConstraintItemKind::Directive(self.take_raw_text())); } if self.eat_sym(";") { return Ok(ConstraintItemKind::Empty); } if self.cur().is_kw("if") { return self.parse_constraint_if(); } if self.cur().is_kw("foreach") { return self.parse_constraint_foreach(); } if self.cur().is_kw("unique") && self.nth(1).is_sym("{") { self.bump(); let comments = self.take_gap(); let items = self.parse_constraint_expr_set()?; return Ok(ConstraintItemKind::Unique { items, comments }); } // `disable soft x;` (IEEE 1800 §18.5.14.1). `disable` is a keyword; // `soft` is matched by text, for the reason `parse_constraint_expr` // gives. if self.cur().is_kw("disable") && word_at(self.nth(1), "soft") { self.bump(); let before = self.take_gap(); self.bump(); let after = self.take_gap(); let expr = self.parse_expr()?; return Ok(ConstraintItemKind::DisableSoft { expr, comments: Box::new(BinaryComments { before, after }), }); } if self.at_solve_before() { return self.parse_solve_before(); } self.parse_constraint_expr() } /// `[soft ]expression_or_dist ;` and `expression -> constraint_set`. /// /// `soft` and `dist` are matched **by text**, not as lexer keywords, for /// the reason `restrict` is (`at_concurrent_assertion`): reserving four /// more words would make every file that spells one as an identifier stop /// parsing, and inside a constraint body their position leaves no other /// reading. See `docs/features/constraint-bodies/README.md`. fn parse_constraint_expr(&mut self) -> PResult { let soft = self.at_soft_constraint(); let mut after_soft = Vec::new(); if soft { self.bump(); after_soft = self.take_gap(); } let mark = self.pending_trailing.len(); let start = self.here(); // `parse_ternary`, not `parse_expr`: the implication level is read // here, because a constraint `->`'s right-hand side may be a braced // set, which is not an expression. let mut expr = self.parse_ternary()?; if self.at_dist() { let before = self.take_gap(); expr = self.parse_dist(start, expr, before)?; } else { // `<->` is an ordinary operator whose right-hand side is always an // expression, so it stays in the expression. Only `->` may take a // set. while self.cur().is_sym("<->") { let before = self.take_around(mark); let op = self.bump().text; let after = self.take_around(mark); let rhs = self.parse_ternary()?; expr = self.expr_at( start, ExprKind::Binary { lhs: Box::new(expr), op, rhs: Box::new(rhs), comments: Box::new(BinaryComments { before, after }), }, ); } if !soft && self.cur().is_sym("->") { let before = self.take_around(mark); self.bump(); let after = self.take_around(mark); let set = self.parse_constraint_set()?; return Ok(ConstraintItemKind::Implication { cond: expr, comments: Box::new(BinaryComments { before, after }), set, }); } } Ok(ConstraintItemKind::Expr { soft, after_soft, expr }) } /// `if ( expr ) constraint_set [ else constraint_set ]`. fn parse_constraint_if(&mut self) -> PResult { self.expect_kw("if")?; let mut comments = HeaderComments { after_kw: self.take_gap(), ..Default::default() }; self.expect_sym("(")?; comments.after_open = self.take_gap(); let cond = self.parse_expr()?; comments.before_close = self.gap_before(")"); self.expect_sym(")")?; comments.before_body = self.gap_before("{"); let then = self.parse_constraint_set()?; let mut else_comments = Vec::new(); let mut after_else = Vec::new(); let mut els = None; if self.cur().is_kw("else") { else_comments = self.take_dangling(); self.bump(); // The gap after `else` is this item's when the set it introduces // opens with a token of its own — a `{`, or the `if` of a chain. // A set written on the next line leaves it to that item's own // leading comments, which is where the source's line break // already put it. after_else = if self.cur().is_sym("{") || self.cur().is_kw("if") { self.take_gap() } else { Vec::new() }; els = Some(Box::new(self.parse_constraint_set()?)); } Ok(ConstraintItemKind::If { cond, comments: Box::new(comments), then, else_comments, after_else, els, }) } /// `foreach ( array [ i, j ] ) constraint_set`. The header is the /// statement `foreach`'s, so it reuses that parse — a skipped dimension /// is an empty-text `Name` there too. fn parse_constraint_foreach(&mut self) -> PResult { self.expect_kw("foreach")?; let mut comments = HeaderComments { after_kw: self.take_gap(), ..Default::default() }; self.expect_sym("(")?; comments.after_open = self.take_gap(); let ForeachTarget { expr: array, vars, comments: var_comments } = self.parse_foreach_target()?; comments.before_close = self.gap_before(")"); self.expect_sym(")")?; comments.before_body = self.gap_before("{"); let set = self.parse_constraint_set()?; Ok(ConstraintItemKind::Foreach { array, vars, var_comments, comments: Box::new(comments), set, }) } /// True when the cursor opens `solve a, b before c, d;`. Both words are /// matched by text; `solve` only counts when a name follows it, so a /// signal called `solve` compared to something else is still an ordinary /// expression. fn at_solve_before(&self) -> bool { word_at(self.cur(), "solve") && self.nth(1).kind == TokenKind::Ident } fn parse_solve_before(&mut self) -> PResult { self.bump(); // solve let solve = self.parse_solve_operands()?; if !word_at(self.cur(), "before") { return self.error("expected `before`"); } let before_comments = self.take_gap(); self.bump(); let before = self.parse_solve_operands()?; Ok(ConstraintItemKind::SolveBefore { solve, before_comments, before }) } /// The comma-separated operand list on either side of `before`. /// /// It deliberately does **not** claim the gap in front of the item's /// `;`: [`Parser::parse_constraint_item`] owns that for every kind, and /// two owners would mean two places to get it wrong. fn parse_solve_operands(&mut self) -> PResult> { let mut out: Vec = Vec::new(); loop { let start = self.here(); let mut meta = self.take_meta(); let expr = self.parse_ternary()?; let span = self.span_from(start); self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); } out.push(ExprItem { meta, expr, span }); if !more { break; } } Ok(out) } /// True when a `dist { ... }` set follows the expression just parsed. /// Both the word and the brace are demanded, which is what makes reading /// `dist` as an operator unambiguous without reserving it. pub(super) fn at_dist(&self) -> bool { word_at(self.cur(), "dist") && self.nth(1).is_sym("{") } /// True when `soft` at the cursor opens a soft constraint rather than /// naming something. It does exactly when a term follows it — a name, a /// literal, a `(`, a `{`, or a unary `!`/`~` — which no infix position /// can produce. fn at_soft_constraint(&self) -> bool { if !word_at(self.cur(), "soft") { return false; } let next = self.nth(1); match next.kind { TokenKind::Ident | TokenKind::SystemIdent | TokenKind::Number | TokenKind::String => { true } TokenKind::Symbol => matches!(next.text.as_str(), "(" | "{" | "!" | "~"), _ => false, } } /// `expr dist { value_range [ := | :/ weight ], ... }` (IEEE 1800 §18.5.4). pub(super) fn parse_dist( &mut self, start: u32, expr: Expr, before: Vec, ) -> PResult { self.bump(); // dist let after = self.take_gap(); self.expect_sym("{")?; let mut weights: Vec = Vec::new(); loop { let item_start = self.here(); let mut meta = self.take_meta(); let value = self.parse_range_or_expr()?; let mut op = None; let mut weight = None; let mut op_comments = BinaryComments::default(); if let Some(spelling) = self.dist_weight_op() { op_comments.before = self.take_gap(); self.bump(); self.bump(); op_comments.after = self.take_gap(); op = Some(spelling.to_string()); weight = Some(self.parse_ternary()?); } let span = self.span_from(item_start); self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); } weights.push(DistItem { meta, value, op, op_comments: Box::new(op_comments), weight, span, }); if !more { break; } } if let Some(last) = weights.last_mut() { self.take_before_sep(&mut last.meta, "}"); } self.expect_sym("}")?; Ok(self.expr_at( start, ExprKind::Dist { expr: Box::new(expr), comments: Box::new(BinaryComments { before, after }), weights, }, )) } /// The `:=` or `:/` of a `dist` weight, at the cursor. /// /// Both are lexed as **two** tokens, because the lexer's operator table /// deliberately does not join them: a `:/` entry would swallow the `/*` /// of `cond ? a :/* why */ b`, and a `:=` entry would buy nothing /// anywhere else in the language. Adjacency is checked by span, so a /// `0 : = 5` written with a space is not one and falls back with the rest /// of the body. fn dist_weight_op(&self) -> Option<&'static str> { if !self.cur().is_sym(":") { return None; } let end = self.cur().span.end; let next = self.nth(1); if next.span.start != end { return None; } match next.text.as_str() { "=" if next.kind == TokenKind::Symbol => Some(":="), "/" if next.kind == TokenKind::Symbol => Some(":/"), _ => None, } } /// The `{ a, [lo:hi], c }` element list an `inside`-style set is written /// with: what `unique` takes, and what one `dist` weight's value may be. pub(super) fn parse_constraint_expr_set(&mut self) -> PResult> { self.expect_sym("{")?; let mut items: Vec = Vec::new(); loop { let start = self.here(); let mut meta = self.take_meta(); let expr = self.parse_range_or_expr()?; let span = self.span_from(start); self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); } items.push(ExprItem { meta, expr, span }); if !more { break; } } if let Some(last) = items.last_mut() { self.take_before_sep(&mut last.meta, "}"); } self.expect_sym("}")?; Ok(items) } /// `[lo:hi]` or an ordinary expression — the `value_range` of a `dist` /// item or a `unique` list, spelled exactly as an `inside` set's is. pub(super) fn parse_range_or_expr(&mut self) -> PResult { if self.cur().is_sym("[") { return self.parse_value_range(); } self.parse_ternary() } /// The `{ ... }` of a `randomize() with { ... }` inline constraint /// (IEEE 1800 §18.7). /// /// It is a `constraint` body written inside an expression, so it gets /// exactly the same treatment: the constraint grammar first, and the /// pre-round byte-for-byte capture as the fallback. The `with` keyword /// itself is left outside the capture — the caller has already consumed /// it, together with the comments written on either side of it — and the /// formatter writes it back. pub(super) fn parse_with_constraint(&mut self) -> PResult { let mark = self.rewind_mark(); if let Ok(set) = self.parse_constraint_block() { return Ok(ConstraintBody::Items(set)); } self.rewind_to(mark); self.constraint_fallbacks += 1; let start = self.here(); let col = self.cur().col; self.expect_sym("{")?; self.skip_balanced("{", "}")?; Ok(ConstraintBody::Verbatim(self.verbatim_since(start, col))) } }