//! The items that instantiate or drive: continuous assignments, module and //! gate instantiations with their parameter overrides and connections, and //! `bind` directives. Drive strengths and delay values live here because //! these are the only items that write them. use super::recover::is_sync_stop; use super::*; /// The strength keywords a drive strength is written from (IEEE 1800 §28.11). const DRIVE_STRENGTHS: &[&str] = &[ "supply0", "supply1", "strong0", "strong1", "pull0", "pull1", "weak0", "weak1", "highz0", "highz1", ]; /// True when `t` is one of the strength keywords a drive strength names. fn is_drive_strength(t: &Token) -> bool { t.kind == TokenKind::Keyword && DRIVE_STRENGTHS.contains(&t.text.as_str()) } impl<'a> Parser<'a> { pub(super) fn parse_cont_assign(&mut self) -> PResult { self.expect_kw("assign")?; let strength = self.parse_opt_drive_strength()?; let mut after_hash = Vec::new(); let mut after_delay = Vec::new(); let delay = if self.cur().is_sym("#") { self.skip(); after_hash = self.take_gap(); let delay = self.parse_delay_value()?; // The gap between the delay and the first left-hand side is the // delay's, not the pair's: a pair's leading comments print right // after the `assign`, which is in front of the delay. after_delay = self.take_gap(); Some(delay) } else { None }; let mut assigns = Vec::new(); loop { let start = self.here(); let mut meta = self.take_meta(); let mark = self.pending_trailing.len(); let lhs = self.parse_unary()?; // Whatever was written on either side of the `=` stays on its own // side of it, as a procedural assignment's does. let op_comments = self.take_around(mark); self.expect_sym("=")?; let rhs_comments = self.take_around(mark); let rhs = self.parse_expr()?; let span = self.span_from(start); // The last pair's separator is the statement's `;`, so a comment // written before it (`assign y = a /* c */;`) belongs on the // value's side of it, not after it. self.take_before_sep(&mut meta, ","); self.take_before_sep(&mut meta, ";"); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); } assigns.push(AssignPair { meta, lhs, rhs, op_comments, rhs_comments, span }); if !more { break; } } self.expect_sym(";")?; Ok(ContAssign { strength, after_hash, delay, after_delay, assigns }) } /// The optional `( strength0 , strength1 )` of a continuous assignment /// (IEEE 1800 §10.3.1), e.g. `assign (weak0, pull1) x = y;` (corpus /// `ibex/vendor/lowrisc_ip/ip/prim_generic/rtl/prim_usb_diff_rx.sv:39`), /// or of a gate — where a pull gate may also write one strength on its /// own, `pullup (weak1) p (x);` (§28.3's `pullup_strength`). /// /// Both orders are accepted, as the grammar allows; the `(` only opens a /// strength when a strength keyword follows it, so a parenthesized /// left-hand side — and a gate whose first argument is an expression — is /// untouched. pub(super) fn parse_opt_drive_strength(&mut self) -> PResult> { if !self.cur().is_sym("(") || !is_drive_strength(self.nth(1)) { return Ok(None); } let mut comments = Box::new(DriveStrengthComments { before_open: self.take_gap(), ..Default::default() }); self.skip(); // ( comments.after_open = self.take_gap(); let first = self.bump().text; // The gap after the first strength ends either at the `,` or at the // `)`, and it is that token which says which slot it belongs in. let gap = self.take_gap(); if self.eat_sym(")") { comments.before_close = gap; return Ok(Some(DriveStrength { first, second: None, comments })); } comments.before_comma = gap; self.expect_sym(",")?; comments.after_comma = self.take_gap(); if !is_drive_strength(self.cur()) { return self.error("expected a drive strength"); } let second = Some(self.bump().text); comments.before_close = self.gap_before(")"); self.expect_sym(")")?; Ok(Some(DriveStrength { first, second, comments })) } /// The value after a `#`: a bare primary, or a parenthesized delay — /// one value, `min:typ:max`, or the `(rise, fall[, turn-off])` list of /// IEEE 1800 §28.14. /// /// A single value keeps the [`ExprKind::Paren`] node the one-value /// spelling has always produced, so `#(5)` and `#(1:2:3)` still print /// exactly as written; only a real comma list yields more than one /// element. fn parse_delay_values(&mut self) -> PResult> { if !self.cur().is_sym("(") { let expr = self.parse_primary()?; return Ok(vec![DelayValue { leading: Vec::new(), expr, trailing: Vec::new() }]); } let start = self.here(); // What is written just inside the `(` belongs to the first value; the // gap before each `,` and the gap after it belong to the values either // side of it. self.skip(); let mut leading = self.take_gap(); let mut out: Vec = Vec::new(); loop { let inner_start = self.here(); let first = self.parse_expr()?; let expr = self.parse_min_typ_max_tail(inner_start, first)?; let trailing = self.gap_before(","); out.push(DelayValue { leading: std::mem::take(&mut leading), expr, trailing }); if !self.eat_sym(",") { break; } leading = self.take_gap(); } if let Some(last) = out.last_mut() { last.trailing = self.gap_before(")"); } self.expect_sym(")")?; if out.len() == 1 { // One value keeps the `( )` node the one-value spelling has always // produced, and its two comment slots are where the paren gaps go. let DelayValue { leading, expr, trailing } = out.remove(0); let paren = self.expr_at( start, ExprKind::Paren { inner: Box::new(expr), before: leading, after: trailing }, ); return Ok(vec![DelayValue { leading: Vec::new(), expr: paren, trailing: Vec::new() }]); } Ok(out) } /// The `: typ : max` tail of a `min : typ : max` expression, or `min` /// unchanged when no `:` follows it. /// /// One grammar for the two places that write it — a delay list and a /// parenthesized expression — so the four comment slots around the two /// colons exist in both. pub(super) fn parse_min_typ_max_tail(&mut self, start: u32, min: Expr) -> PResult { let before_typ = self.gap_before(":"); if !self.eat_sym(":") { return Ok(min); } let mut comments = MinTypMaxComments { before_typ, ..Default::default() }; comments.after_typ = self.take_gap(); let typ = self.parse_expr()?; comments.before_max = self.gap_before(":"); self.expect_sym(":")?; comments.after_max = self.take_gap(); let max = self.parse_expr()?; Ok(self.expr_at( start, ExprKind::MinTypMax { min: Box::new(min), typ: Box::new(typ), max: Box::new(max), comments: Box::new(comments), }, )) } /// The single delay value a net declaration or a continuous assignment /// takes. The multi-value list is a gate-instantiation spelling only — /// see [`Parser::parse_delay_values`]. pub(super) fn parse_delay_value(&mut self) -> PResult { let mut values = self.parse_delay_values()?; if values.len() > 1 { return self.error("a multi-value delay list is only allowed on a gate instantiation"); } // A lone value carries no comments of its own: `parse_delay_values` // folded the paren gaps into its `ExprKind::Paren`. Ok(values.remove(0).expr) } /// True when the cursor opens a `bind` directive (IEEE 1800 §23.11). /// /// `bind` is deliberately *not* in the lexer's keyword table — the same /// call lucisv makes for `new`/`this`/`super` — so that `obj.bind()` keeps /// parsing as the ordinary method call it is in existing testbenches. /// A directive is recognized from its shape instead: the word `bind`, /// then a target scope (a name, possibly a `.`-separated hierarchical /// path, each segment possibly carrying one `[…]` selector), then either /// the `:` of an instance list or the module name of the instantiation. /// A declaration of a variable called `bind` reaches `;`, `,`, `=` or a /// dimension there, so it never matches — a `bind [3:0] x;` declaration /// is a *dimension on the first name*, which is why the scan only steps /// over a `[…]` that has a `.` or the instantiation after it. pub(super) fn at_bind_directive(&self) -> bool { let t = self.cur(); if t.kind != TokenKind::Ident || t.text != "bind" { return false; } let mut p = self.pos + 1; if !self.tokens.get(p).is_some_and(|t| t.kind == TokenKind::Ident) { return false; } p += 1; loop { // `top.gen[0].u_core` (IEEE 1800 §23.11's bind_target_instance): // binding SVA into a generate array is the shape formal setups // write. One selector per segment; anything more is not a bind // this parser reads, and stays the clean error it always was. if self.tokens.get(p).is_some_and(|t| t.is_sym("[")) { let after = self.scan_matching(p, "[", "]"); if after == p { return false; } p = after; } if self.tokens.get(p).is_some_and(|t| t.is_sym(".")) && self.tokens.get(p + 1).is_some_and(|t| t.kind == TokenKind::Ident) { p += 2; continue; } break; } self.tokens.get(p).is_some_and(|t| t.is_sym(":") || t.kind == TokenKind::Ident) } /// `bind [: , ...] [#(...)] (...);` pub(super) fn parse_bind(&mut self) -> PResult { self.skip(); // `bind` // The target is a bare string, so a comment written before it has no // node to attach to: harvest it here, where source order is still // known, rather than letting it drift onto the instance below. let target_comments = self.take_dangling(); let start = self.here(); let mut target = vec![self.parse_path_segment()?]; while self.cur().is_sym(".") { self.skip(); target.push(self.parse_path_segment()?); } let target_span = self.span_from(start); let mut instances = Vec::new(); if self.eat_sym(":") { loop { instances.push(self.parse_bind_instance()?); if !self.eat_sym(",") { break; } } } let module_comments = self.take_dangling(); let inst = self.parse_instantiation()?; Ok(BindDirective { target, target_comments, target_span, instances, module_comments, inst }) } /// One entry of a `bind`'s `: instance_list`. The LRM spells these as bare /// instance names, but vendor tools accept — and OpenTitan writes — a /// hierarchical path: `bind prim_packer_fifo : /// dut.u_entropy_src_core.u_prim_packer_fifo_precon ...` /// (`entropy_src/dv/tb/tb.sv:94`). The dots are glued into the one name /// the list already carries, exactly as `bind`'s own target path is. fn parse_bind_instance(&mut self) -> PResult { let start = self.here(); let mut text = self.expect_ident()?; while self.cur().is_sym(".") { self.skip(); let segment = self.expect_ident()?; Self::push_path_segment(&mut text, &segment); } Ok(Name { text, span: self.span_from(start) }) } /// One segment of a `bind` target path: a name and the one `[…]` /// selector it may carry. fn parse_path_segment(&mut self) -> PResult { let Name { text: name, span } = self.expect_name()?; let mut index = None; if self.eat_sym("[") { index = Some(self.parse_expr()?); self.expect_sym("]")?; } Ok(PathSegment { name, span, index }) } pub(super) fn parse_instantiation(&mut self) -> PResult { let module_start = self.here(); let mut module = self.expect_ident()?; while self.cur().is_sym("::") { self.skip(); let segment = self.expect_ident()?; Self::push_scope_segment(&mut module, &segment); } let module_span = self.span_from(module_start); let mark = self.diags_mark(); 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.skip(); 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 { let at = self.pos; list.push(self.connection_or_recover()?); let recovered = list.last().is_some_and(ListElem::is_error); if let Some(ListElem::Ok(last)) = list.last_mut() { self.take_before_sep(&mut last.meta, ","); } let comma = self.eat_sym(","); self.note_trailing_comma(comma); 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()); // Same two break conditions as a header's lists (see // `Parser::parse_module`): no comma and no directive ends // the list, and after a directive only the closing bracket // does — an `` `ifdef`` arm may end without a comma and // still be followed by an `` `else`` arm. if self.connection_list_ends(at, comma, dirs.any, recovered) { break; } } } // Comments before the `)` of the override list belong inside it. 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(mark)?; params = Some(list); } let mut instances = Vec::new(); loop { let start = self.here(); let mut meta = self.take_meta(); let Name { text: name, span: name_span } = self.expect_name()?; let dims = self.parse_dims()?; let conn_comments = self.take_before_open("("); self.expect_sym("(")?; let conn_mark = self.diags_mark(); let mut conn_directives = Vec::new(); let conns = self.parse_connections(&mut conn_directives)?; self.close_list(conn_mark)?; let span = self.span_from(start); self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); } instances.push(Instance { meta, name, name_span, dims, conn_comments, conns, conn_directives, span, }); if !more { break; } } let before_semi = self.gap_before(";"); // As in a module header (`Parser::parse_module`): once something in // this instantiation has been reported, a missing `;` is part of the // same typo, and the item is worth more than a second message. It is // what leaves the `wire w;` under a half-typed `sub u (.a(` an item of // the module. self.expect_after_recovery(";", self.recovered_since(mark))?; Ok(Instantiation { module, module_span, param_comments, after_hash, params, param_directives, instances, before_semi, }) } /// Move the comments written before a list's closing bracket onto the last /// entry *in source order*, which is a trailing directive when the list has /// one and the last element otherwise. /// /// Without the directive case they would print before it, having moved /// backwards across a token; with an element-less list (`` #(`include /// "config.vh") ``) the directive is the only place they can go at all. pub(super) fn take_last_entry_before_close( &mut self, last_element: Option<&mut Meta>, directives: &mut [ListDirective], elements: usize, ) { if let Some(d) = directives.last_mut().filter(|d| d.before == elements) { self.take_before_sep(&mut d.meta, ")"); } else if let Some(meta) = last_element { self.take_before_sep(meta, ")"); } } /// The connections of one instance. `directives` collects the /// `` `ifdef``-style lines written between them; the harvest must run /// before the `.`-peek below, or a directive standing before the first /// connection would be read as a positional expression. fn parse_connections(&mut self, directives: &mut Vec) -> PResult { self.take_list_directives(directives, 0); if self.cur().is_sym(")") { return Ok(Connections::Ordered(Vec::new())); } if self.at_named_connection() { let mut conns = Vec::new(); loop { let at = self.pos; conns.push(self.connection_or_recover()?); let recovered = conns.last().is_some_and(ListElem::is_error); if let Some(ListElem::Ok(last)) = conns.last_mut() { self.take_before_sep(&mut last.meta, ","); } let comma = self.eat_sym(","); self.note_trailing_comma(comma); if let Some(ListElem::Ok(last)) = conns.last_mut() { last.comma = comma; if comma && last.meta.trailing.is_none() { last.meta.trailing = self.take_trailing(); } } let dirs = self.take_list_directives(directives, conns.len()); if self.connection_list_ends(at, comma, dirs.any, recovered) { break; } } // Comments before the closing `)` belong to the last entry: after // it they would sit outside the connection list entirely. let n = conns.len(); let last = conns.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta); self.take_last_entry_before_close(last, directives, n); Ok(Connections::Named(conns)) } else { let mut conns = Vec::new(); loop { let at = self.pos; conns.push(self.element_or_recover(|p| p.parse_ordered_connection())?); let recovered = conns.last().is_some_and(ListElem::is_error); let comma = match conns.last() { Some(ListElem::Ok(last)) => last.comma, // A positional connection reads its own separator; an // error element leaves the `,` for the list, as in a // non-ANSI port list. _ => self.eat_sym(","), }; let dirs = self.take_list_directives(directives, conns.len()); if self.list_ends(at, comma, dirs.any, recovered) { break; } } let n = conns.len(); let last = conns.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta); self.take_last_entry_before_close(last, directives, n); Ok(Connections::Ordered(conns)) } } /// One positional connection (`u (a, , c)`), its separator included: an /// omitted one writes no token at all, so the `,` is the only thing that /// says it was there. fn parse_ordered_connection(&mut self) -> PResult { let start = self.here(); let mut meta = self.take_meta(); let expr = if self.cur().is_sym(",") || self.cur().is_sym(")") { None } else { Some(self.parse_expr()?) }; // An omitted connection consumed no token, so this is the empty span // where it would have started. let span = self.span_from(start); self.take_before_sep(&mut meta, ","); let comma = self.eat_sym(","); if comma { meta.trailing = self.take_trailing(); } Ok(OrderedConn { meta, expr, comma, span }) } /// True when the connection list starts with a named connection. The /// leading `(* ... *)` attributes of the first entry are looked past: /// they belong to the connection, not to the list. fn at_named_connection(&self) -> bool { let mut i = self.pos; while i < self.tokens.len() && self.tokens[i].kind == TokenKind::Attribute { i += 1; } self.tokens.get(i).is_some_and(|t| t.is_sym(".")) } /// `.name(expr)`, `.name()`, `.name`, `.*`, or (for parameter lists and /// ordered parameter overrides) a bare expression. pub(super) fn parse_connection(&mut self) -> PResult { let start = self.here(); let mut meta = self.take_meta(); // `(* async *) .async_data_o (x)` — an attribute instance may precede // a port connection (IEEE 1800 §A.4.1.1), corpus // `common_cells/src/cdc_fifo_gray.sv:140`. Harvested exactly the way // an item's or a statement's attributes are. 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); } if self.eat_sym(".") { let after_dot = self.take_gap(); let star = self.cur().span; if self.eat_sym("*") { let span = self.span_from(start); return Ok(Connection { meta, after_dot, name: "*".to_string(), name_span: star, before_open: Vec::new(), after_open: Vec::new(), expr: None, close_comments: Vec::new(), comma: false, span, }); } let Name { text: name, span: name_span } = self.expect_name()?; let before_open = self.take_before_open("("); let mark = self.pending_trailing.len(); let paren_start = self.here(); // A half-typed `.NAME(` whose value would read as the next // instance: `sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x));`. Nothing // inside the list fails — `u0 (.a(x))` is a legal call with named // arguments — so the greedy parse swallows the instance and the // whole instantiation collapses into one error item. Failing the // element here costs the one connection and keeps everything // else. See `docs/features/small-items-3/README.md`. The same // failure covers a `.NAME(` left open at the end of its line while // the next line goes on with the list (`.po(` ⏎ `.b(y));`): the // entry ends with its line, and the diagnostic is on its `(` // (`docs/features/port-entry-grace/README.md`). if self.tolerant && self.cur().is_sym("(") && (self.value_runs_into_next_instance() || self.value_left_open()) { return self.error("unclosed `(` in a port or parameter connection"); } let mut close_comments = Vec::new(); let mut after_open = Vec::new(); let expr = if self.eat_sym("(") { if self.cur().is_sym(")") { // `.name(/* unused */)`: the comments were written inside // these parens and are printed back inside them. let inside = self.take_around(mark); self.skip(); Some(self.expr_at(paren_start, ExprKind::Empty(inside))) } else { after_open = self.take_gap(); let value_mark = self.pending_trailing.len(); let e = match self.conditional_region_end(")") { Some(end_pos) => self.parse_verbatim_expr(end_pos), None => self.parse_expr_or_type()?, }; // `.name(x /* c */)`: written inside the parens, so it is // printed inside them too. close_comments = self.take_around(value_mark); self.expect_sym(")")?; Some(e) } } else { None }; let span = self.span_from(start); meta.trailing = self.take_trailing(); Ok(Connection { meta, after_dot, name, name_span, before_open, after_open, expr, close_comments, comma: false, span, }) } else { let e = self.parse_expr_or_type()?; let span = self.span_from(start); meta.trailing = self.take_trailing(); Ok(Connection { meta, after_dot: Vec::new(), name: String::new(), name_span: TextRange::empty(span.start), before_open: Vec::new(), after_open: Vec::new(), expr: Some(e), close_comments: Vec::new(), comma: false, span, }) } } /// True when the `(` at the cursor — the one that opens a connection's /// value — is never closed **and** something that reads as the next /// instance sits inside it. /// /// Tolerant mode only, asked once per named connection before its value /// is parsed. The walk starts just past the `(` at depth zero and ends at /// the first of: a closer that would take the depth below zero (the /// value's own `)` — it closes, so nothing is wrong and the value is /// parsed as written), a `;` or a construct keyword at depth zero, or end /// of file. On a file that parses it therefore stops at the value's `)` /// after a handful of tokens; only a value whose bracket was never closed /// walks as far as the next `;`. /// /// The candidate is an identifier that opens its own line and is followed /// by `(` — how an instance is written, and how nothing written *inside* /// a value normally is. Only depth zero is read: a candidate inside a /// deeper unclosed bracket (`.DEPTH(f(g(` ⏎ `u0 (…)`) is not seen, and /// that shape falls back to the coarser item-level recovery, which keeps /// the `endmodule` but loses the instantiation. Deliberate — reading /// deeper would start guessing which of several unclosed brackets the /// user meant to close. fn value_runs_into_next_instance(&self) -> bool { let mut depth = 0u32; let mut candidate = false; let mut i = self.pos + 1; while let Some(t) = self.tokens.get(i) { if t.kind == TokenKind::Eof { break; } if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") { depth += 1; } else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") { if depth == 0 { return false; } depth -= 1; } else if depth == 0 { if t.is_sym(";") || is_sync_stop(t) { break; } if t.kind == TokenKind::Ident && self.tokens[i - 1].line != t.line && self.tokens.get(i + 1).is_some_and(|n| n.is_sym("(")) { candidate = true; } } i += 1; } candidate } /// Consume the tokens up to `end_pos` as one verbatim expression. /// /// [`Parser::open_conds`] is deliberately left alone: it counts *item* /// scope only, and a construct that walks its body through /// [`Parser::bump`] inherits "does not count" by doing nothing — see /// [`Parser::note_item_conditional`]. fn parse_verbatim_expr(&mut self, end_pos: usize) -> Expr { let start = self.here(); let col = self.cur().col; while self.pos < end_pos && !self.at_eof() { self.skip(); } let raw = self.verbatim_since(start, col); self.expr_at(start, ExprKind::Verbatim(raw)) } pub(super) fn parse_gate_instantiation(&mut self) -> PResult { let gate = self.bump().text; // `pullup (weak1) p (x);` — the strength stands where an unnamed // instance's argument list would, and only a strength keyword after // the `(` tells the two apart. let strength = self.parse_opt_drive_strength()?; let before_hash = self.take_before_open("#"); let mut after_hash = Vec::new(); let delay = if self.cur().is_sym("#") { self.skip(); after_hash = self.take_gap(); self.parse_delay_values()? } else { Vec::new() }; let mut instances = Vec::new(); loop { let start = self.here(); let mut meta = self.take_meta(); let name = if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None }; let (name, name_span) = split_label(name); let before_args = self.take_before_open("("); self.expect_sym("(")?; let mut args = Vec::new(); if !self.cur().is_sym(")") { let first = self.parse_expr_item()?; args = self.parse_expr_list(first, ")")?; } self.expect_sym(")")?; let span = self.span_from(start); self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); } instances.push(GateInstance { meta, name, name_span, before_args, args, span }); if !more { break; } } let before_semi = self.gap_before(";"); self.expect_sym(";")?; Ok(GateInstantiation { gate, strength, before_hash, after_hash, delay, instances, before_semi, }) } }