Files
lucisv/crates/vlog_parser/src/parser/instance.rs
T
lucioandClaude Fable 5 f1d44a2a0c WIP checkpoint, §32 paused 2026-09-03 — runaway root cause fixed (list_ends on an unmoved cursor), strict parity restored; 32.1–32.5 done, 32.6 half, 32.7 + gates not run
Root cause of the 100 GB crash: a non-ANSI port loop took its trailing
comma from the element, an error element never got that far, the next
iteration failed on the same comma, consumed nothing and pushed another
empty error element - an allocating spin. Fix is structural: list_ends
ends the list whenever the cursor has not moved since the iteration
began; the two loops that read their own separator also eat it after an
error element. Truncate-anywhere + delete-any-character pass under
tools/guard.sh -m 4. Strict parity: element_or_recover declines on a
conditional-compilation directive so split.rs's verbatim rescue still
runs. cargo test -p vlog_parser 365 + 26 + 31 / 0 failed; workspace
suite NOT re-run since the last fixes. Not done: completion pin + the
three validity probes (32.6), measurements (32.7), README amendments,
coverage_gaps M10, TODO ticks, every gate. Handshake: three
vlog_linter arms (visit.rs walk_param_ports, signals.rs connection
loops) live in the earlier commit 6a15594.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 18:28:33 -07:00

622 lines
26 KiB
Rust

//! 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::*;
/// 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<ContAssign> {
self.expect_kw("assign")?;
let strength = self.parse_opt_drive_strength()?;
let delay = if self.cur().is_sym("#") {
self.bump();
Some(self.parse_delay_value()?)
} 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, 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.
fn parse_opt_drive_strength(&mut self) -> PResult<Option<DriveStrength>> {
if !self.cur().is_sym("(") || !is_drive_strength(self.nth(1)) {
return Ok(None);
}
self.bump(); // (
let first = self.bump().text;
if self.eat_sym(")") {
return Ok(Some(DriveStrength { first, second: None }));
}
self.expect_sym(",")?;
if !is_drive_strength(self.cur()) {
return self.error("expected a drive strength");
}
let second = Some(self.bump().text);
self.expect_sym(")")?;
Ok(Some(DriveStrength { first, second }))
}
/// 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<Vec<Expr>> {
if !self.cur().is_sym("(") {
return Ok(vec![self.parse_primary()?]);
}
let start = self.here();
self.bump(); // (
let mut out = Vec::new();
loop {
let inner_start = self.here();
let first = self.parse_expr()?;
out.push(if self.eat_sym(":") {
let typ = self.parse_expr()?;
self.expect_sym(":")?;
let max = self.parse_expr()?;
self.expr_at(
inner_start,
ExprKind::MinTypMax {
min: Box::new(first),
typ: Box::new(typ),
max: Box::new(max),
},
)
} else {
first
});
if !self.eat_sym(",") {
break;
}
}
self.expect_sym(")")?;
if out.len() == 1 {
let inner = out.remove(0);
return Ok(vec![self.expr_at(
start,
ExprKind::Paren { inner: Box::new(inner), before: Vec::new(), after: Vec::new() },
)]);
}
Ok(out)
}
/// 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<Expr> {
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");
}
Ok(values.remove(0))
}
/// 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 <target> [: <inst>, ...] <module> [#(...)] <name> (...);`
pub(super) fn parse_bind(&mut self) -> PResult<BindDirective> {
self.bump(); // `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.bump();
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<Name> {
let start = self.here();
let mut text = self.expect_ident()?;
while self.cur().is_sym(".") {
self.bump();
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<PathSegment> {
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<Instantiation> {
let module_start = self.here();
let mut module = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
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.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 {
let at = self.pos;
list.push(self.element_or_recover(|p| p.parse_connection())?);
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(",");
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.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<ListDirective>) -> PResult<Connections> {
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.element_or_recover(|p| p.parse_connection())?);
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(",");
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.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<OrderedConn> {
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<Connection> {
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();
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.bump();
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,
})
}
}
/// 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.bump();
}
let raw = self.verbatim_since(start, col);
self.expr_at(start, ExprKind::Verbatim(raw))
}
pub(super) fn parse_gate_instantiation(&mut self) -> PResult<GateInstantiation> {
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 delay = if self.cur().is_sym("#") {
self.bump();
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);
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, args, span });
if !more {
break;
}
}
self.expect_sym(";")?;
Ok(GateInstantiation { gate, strength, delay, instances })
}
}