// Author: Guoliang Chen, a Senior Digital Design Engineer //! The connection list of an instantiation: named (`.name(expr)`, `.name`, //! `.*`) and ordered connections, the comments written before the list's //! closing bracket, and — in tolerant mode — the value whose bracket was //! never closed and runs into the next instance. use super::recover::is_sync_stop; use super::*; impl<'a> Parser<'a> { /// 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. pub(super) 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. self.take_attrs(&mut meta); 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)) } } // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com