Files
lucisv/crates/vlog_semantic/src/bind/item.rs
T
lucioandClaude Fable 5 6a15594ae8 WIP §32 header recovery — DO NOT MERGE: half-finished; a fuzz test loops without advancing and exhausts memory (crashed the machine 2026-09-03)
Checkpoint of the interrupted dev work (rate limit) so master stays
clean. Known state: a_half_typed_instantiation_is_one_error_node
(expected to invert) and tolerant_parse_equals_strict_parse_on_valid_
sources FAIL; the error_recovery test binary exceeds 6 GB under
tools/guard.sh (a non-advancing recovery loop under the delete-any-
character / truncate fuzzers). Resume in a worktree of this branch,
under tools/guard.sh, fixing the advance guarantee first.

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

557 lines
24 KiB
Rust

//! The item-level walk: a file or fragment, the `ItemKind` dispatch, modules
//! and interfaces (header, ports, modports, clocking blocks), packages and
//! imports, instantiations and `bind`, generate constructs, functions and
//! tasks. Every item that declares a typed name hands the name to `decl` and
//! every body to `stmt`; what stays here is the shape of the item and the
//! scope it opens.
use vlog_parser::ast::*;
use vlog_parser::span::TextRange;
use vlog_parser::token::is_keyword;
use crate::model::{Import, ScopeId, ScopeKind, SymbolKind};
use super::decl::param_kind;
use super::{Binder, Deferred, Target};
impl<'a> Binder<'a> {
pub(crate) fn bind_items(&mut self, items: &'a [Item], scope: ScopeId) {
for item in items {
self.bind_item(item, scope);
}
}
/// A file that is the bare middle of some body, bound as that body would
/// have bound it (`docs/features/fragment-mode/README.md`).
///
/// A statement list gets a [`ScopeKind::Block`] of its own, because that is
/// what its declarations are scoped by wherever the fragment is included —
/// a `begin ... end`, an `always` body, a task — and because a local of the
/// snippet has no business being a file-scope name. Enum members and cover
/// items bind in the file scope itself: an enum label belongs to the scope
/// *holding* the enum (IEEE 1800 §6.19, the rule
/// [`Binder::bind_enum_body`] already follows), and a labelled coverpoint
/// is the one name a cover-item fragment declares.
pub(crate) fn bind_fragment(
&mut self,
fragment: &'a Fragment,
scope: ScopeId,
span: TextRange,
) {
match fragment {
Fragment::Statements(stmts) => {
let inner = self.new_scope(ScopeKind::Block, scope, span);
self.bind_stmts(stmts, inner);
}
Fragment::EnumMembers { members, .. } => self.bind_enum_members(members, scope),
Fragment::CoverItems(items) => {
for item in items {
self.bind_cover_item(item, scope);
}
}
}
}
pub(super) fn bind_item(&mut self, item: &'a Item, scope: ScopeId) {
match &item.kind {
ItemKind::Module(m) => self.bind_module(m, item.span, scope),
ItemKind::Package { name, name_span, items, end_label, end_label_span, .. } => {
let inner = self.declare_with_scope(
scope,
name,
SymbolKind::Package,
*name_span,
item.span,
ScopeKind::Package,
);
self.bind_items(items, inner);
self.use_end_label(scope, inner, end_label.as_ref(), *end_label_span);
}
ItemKind::Import(paths) => {
for path in paths {
self.bind_import_path(path, scope);
}
}
// A `let` is a compile-time function: its ports are visible only
// inside its own body expression.
ItemKind::Let(l) => {
let inner = self.declare_with_scope(
scope,
&l.name,
SymbolKind::Function,
l.name_span,
item.span,
ScopeKind::Function,
);
self.bind_tf_args(&l.ports, inner);
self.bind_expr(&l.value, inner);
}
ItemKind::Typedef(t) => self.bind_typedef(t, item.span, scope),
ItemKind::ParamDecl(p) => {
self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, item.span, scope)
}
ItemKind::DataDecl(d) => self.bind_data_decl(d, item.span, scope),
ItemKind::PortDecl(p) => self.bind_port_decl(p, item.span, scope),
ItemKind::ContAssign(c) => {
self.bind_opt_expr(c.delay.as_ref(), scope);
for a in &c.assigns {
self.bind_expr(&a.lhs, scope);
self.bind_expr(&a.rhs, scope);
}
}
// The arguments name real parameters (`$error("...", W)`), so they
// resolve like any other expression.
ItemKind::ElabTask(e) => self.bind_expr(e, scope),
ItemKind::Always { stmt, .. } => self.bind_stmt(stmt, scope),
ItemKind::Initial(s) | ItemKind::Final(s) => self.bind_stmt(s, scope),
ItemKind::Instantiation(i) => self.bind_instantiation(i, scope),
ItemKind::Bind(b) => self.bind_bind(b, scope),
ItemKind::GateInstantiation(g) => {
for d in &g.delay {
self.bind_expr(d, scope);
}
for inst in &g.instances {
if let (Some(name), Some(ns)) = (&inst.name, inst.name_span) {
self.declare(scope, name, SymbolKind::Instance, ns, inst.span);
}
for a in &inst.args {
self.bind_expr(&a.expr, scope);
}
}
}
ItemKind::Genvar(names) => {
for name in names {
self.declare(scope, &name.text, SymbolKind::Genvar, name.span, item.span);
}
}
ItemKind::GenerateRegion { items, .. } => {
let inner = self.new_scope(ScopeKind::Generate, scope, item.span);
self.bind_items(items, inner);
}
ItemKind::GenIf(g) => self.bind_gen_if(g, scope),
ItemKind::GenFor(g) => self.bind_gen_for(g, item.span, scope),
ItemKind::GenCase(g) => {
self.bind_expr(&g.expr, scope);
for it in &g.items {
for l in &it.labels {
self.bind_expr(&l.expr, scope);
}
self.bind_gen_block(&it.body, scope);
}
}
ItemKind::Constraint(c) => self.bind_constraint(c, item.span, scope),
ItemKind::Covergroup(c) => self.bind_covergroup(c, item.span, scope),
ItemKind::PropSeqDecl(d) => self.bind_prop_seq_decl(d, item.span, scope),
ItemKind::Assertion(a) => self.bind_assertion(a, scope),
ItemKind::DefaultDisable(d) => self.bind_expr(&d.expr, scope),
ItemKind::Function(f) => self.bind_function(f, item.span, scope),
ItemKind::Task(t) => self.bind_task(t, item.span, scope),
ItemKind::Class(c) => self.bind_class(c, item.span, scope),
ItemKind::Modport(decls) => {
for d in decls {
self.bind_modport(d, scope);
}
}
ItemKind::Clocking(c) => self.bind_clocking(c, item.span, scope),
ItemKind::Defparam(pairs) => {
for (lhs, rhs) in pairs {
self.bind_expr(lhs, scope);
self.bind_expr(rhs, scope);
}
}
// Every term of an `alias` names an existing net — the item
// declares nothing — so all of them are references.
ItemKind::Alias(nets) => {
for net in nets {
self.bind_expr(net, scope);
}
}
// Opaque leaves: verbatim text this crate makes no claims about.
// `Verbatim` is a constraint or covergroup body — no symbol is
// bound for its name and nothing inside it is scanned, the same
// contract macro invocations have. `Export` is a leaf too: a DPI
// export names a function declared elsewhere in the same scope,
// and a package re-export does not bring the name into this scope
// (an `import` alongside it does that). Resolving either one is a
// vlog_semantic decision, not the parser's — see
// `docs/features/dpi-export/README.md` Handshakes.
ItemKind::Export(_)
| ItemKind::Directive(_)
| ItemKind::MacroItem(_)
| ItemKind::Timeunit(_)
| ItemKind::Error(_)
// A null item (`;`) declares nothing and references nothing.
| ItemKind::Empty
| ItemKind::Verbatim(_) => {}
}
}
fn bind_module(&mut self, m: &'a Module, span: TextRange, scope: ScopeId) {
// One AST node, three keywords. `interface` gets its own kind — its
// signals are its surface and another file may reach them, which is
// exactly what a module never grants. `program` stays a `Module`: it is
// a module body with a different closing keyword and no export rule of
// its own to write (`docs/features/interface-semantics/README.md`).
let kind = match m.kw.as_str() {
"interface" => SymbolKind::Interface,
_ => SymbolKind::Module,
};
let inner =
self.declare_with_scope(scope, &m.name, kind, m.name_span, span, ScopeKind::Module);
for import in &m.imports {
for path in &import.paths {
self.bind_import_path(path, inner);
}
}
self.bind_param_ports(m.param_ports.iter().flatten(), inner);
match &m.ports {
// An error element — a port a tolerant parse could not read —
// declares nothing, exactly as an `ItemKind::Error` does.
PortList::Ansi(ports) => {
for p in ports.iter().filter_map(ListElem::ok) {
self.bind_data_type(
&p.ty,
TextRange::new(p.span.start, p.name_span.start),
inner,
);
self.declare_typed(
inner,
&p.name,
SymbolKind::Port,
p.name_span,
p.span,
p.unpacked.is_empty().then_some(&p.ty),
);
self.bind_dims(&p.unpacked, inner);
self.bind_opt_expr(p.default.as_ref(), inner);
}
}
PortList::NonAnsi(ports) => {
for p in ports.iter().filter_map(ListElem::ok) {
self.declare(inner, &p.name, SymbolKind::Port, p.span, p.span);
}
}
PortList::None | PortList::Empty => {}
}
self.bind_items(&m.items, inner);
self.use_end_label(scope, inner, m.end_label.as_ref(), m.end_label_span);
}
/// Record one `pkg::item` / `pkg::*` path as an import of `scope`.
pub(super) fn bind_import_path(&mut self, path: &ImportPath, scope: ScopeId) {
let item = if path.item.text == "*" {
None
} else {
self.use_name(
scope,
&path.item.text,
path.item.span,
Target::UnitMember(path.pkg.text.clone()),
);
Some(path.item.text.clone())
};
self.use_name(scope, &path.pkg.text, path.pkg.span, Target::Package);
self.scopes[scope.0 as usize].imports.push(Import {
package: path.pkg.text.clone(),
item,
scope: None,
name_span: path.pkg.span,
});
}
fn bind_instantiation(&mut self, i: &Instantiation, scope: ScopeId) {
// `module_span` has the documented despace caveat for `pkg :: mod`,
// so it is taken only when it slices back to the stored name.
let ns = self.exact_or_empty(i.module_span, &i.module);
self.use_name(scope, &i.module, ns, Target::Module);
for c in i.params.iter().flatten().filter_map(ListElem::ok) {
self.bind_connection(c, &i.module, scope);
}
for inst in &i.instances {
let id =
self.declare(scope, &inst.name, SymbolKind::Instance, inst.name_span, inst.span);
// An instance's "declared type" is the module it instantiates, so
// `u.port` and `u.internal_sig` are looked up exactly as a class
// handle's members are — in the module's own scope, or in the
// workspace's member table when the module is another file's.
// An **array** of instances (`sub u[3:0] (...)`) is not one of
// them, on the same rule an unpacked declarator follows: the
// element is reached through an index, which is not a head this
// crate types.
// A macro standing where the module name belongs (`` `REGS u ()``)
// names no declaration, exactly as it names none in `use_name`.
let named =
!i.module.is_empty() && !i.module.starts_with('`') && !is_keyword(&i.module);
if let (Some(id), true) = (id, inst.dims.is_empty() && named) {
self.symbols[id.0 as usize].type_name = Some(i.module.clone());
}
self.bind_dims(&inst.dims, scope);
self.bind_connections(&inst.conns, &i.module, scope);
}
}
/// A `bind` directive (IEEE 1800 §23.11), which instantiates into
/// **another** scope.
///
/// Three halves, each resolved where the LRM says it lives:
///
/// * the **target**, when it is a lone name, is a module or interface —
/// `bind prim_fifo_sync …` names the declaration a `go to definition`
/// should jump to. A hierarchical *instance* path (`top.u_dut.u_core`,
/// `top.gen[0].u_core`) names a place in an elaborated hierarchy that no
/// single file knows, so it records nothing at all: the alternative is a
/// guess, and a guess here is a wrong answer.
/// * the **instantiated module**, exactly as before, so a bind still makes
/// the bound module a dependency of this file.
/// * each connection: the `.port` half against the module being bound in
/// (an ordinary [`Target::Port`], the same one a plain instantiation
/// uses), and the expression half in the target's scope
/// ([`Target::BindScope`]).
///
/// The instance name is still **not** declared here: it belongs to the
/// target scope, and declaring it in this one would put a name in a scope
/// that does not have it.
fn bind_bind(&mut self, b: &'a BindDirective, scope: ScopeId) {
let head = match &b.target[..] {
[only] if only.index.is_none() => Some(only),
_ => None,
};
if let Some(h) = head {
let ns = self.exact_or_empty(h.span, &h.name);
self.use_name(scope, &h.name, ns, Target::Module);
}
let i = &b.inst;
let ns = self.exact_or_empty(i.module_span, &i.module);
self.use_name(scope, &i.module, ns, Target::Module);
let previous = std::mem::replace(&mut self.bind_target, head.map(|h| h.name.clone()));
for c in i.params.iter().flatten().filter_map(ListElem::ok) {
self.bind_connection(c, &i.module, scope);
}
for inst in &i.instances {
self.bind_connections(&inst.conns, &i.module, scope);
}
self.bind_target = previous;
}
/// One instance's connection list, named or positional. An error element
/// — a connection a tolerant parse could not read — names nothing and
/// values nothing, so it binds nothing.
fn bind_connections(&mut self, conns: &Connections, module: &str, scope: ScopeId) {
match conns {
Connections::Named(conns) => {
for c in conns.iter().filter_map(ListElem::ok) {
self.bind_connection(c, module, scope);
}
}
Connections::Ordered(conns) => {
for c in conns.iter().filter_map(ListElem::ok) {
self.bind_opt_expr(c.expr.as_ref(), scope);
}
}
}
}
fn bind_connection(&mut self, c: &Connection, module: &str, scope: ScopeId) {
if c.name != "*" {
self.use_name(scope, &c.name, c.name_span, Target::Port(module.to_string()));
}
self.bind_opt_expr(c.expr.as_ref(), scope);
}
fn bind_gen_if(&mut self, g: &'a GenIf, scope: ScopeId) {
self.bind_expr(&g.cond, scope);
self.bind_gen_block(&g.then, scope);
match g.els.as_deref() {
Some(GenElse::If(_, inner)) => self.bind_gen_if(inner, scope),
Some(GenElse::Block(b)) => self.bind_gen_block(b, scope),
None => {}
}
}
fn bind_gen_for(&mut self, g: &'a GenFor, span: TextRange, scope: ScopeId) {
// The loop header opens a scope of its own so that `for (genvar i...)`
// does not leak `i` into the enclosing module.
let header = self.new_scope(ScopeKind::Generate, scope, span);
match (g.init_genvar, &g.init.lhs.kind) {
// `for (genvar i = 0; ...)` declares; `for (i = 0; ...)` uses a
// `genvar i;` written outside the loop.
(true, ExprKind::Ident(name)) => {
self.declare(header, name, SymbolKind::Genvar, g.init.lhs.span, g.init.lhs.span);
}
_ => self.bind_expr(&g.init.lhs, header),
}
self.bind_expr(&g.init.rhs, header);
self.bind_expr(&g.cond, header);
match &g.step {
ForStep::Assign(a) => {
self.bind_expr(&a.lhs, header);
self.bind_expr(&a.rhs, header);
}
ForStep::Expr(e) => self.bind_expr(e, header),
}
self.bind_gen_block(&g.body, header);
}
fn bind_gen_block(&mut self, b: &'a GenBlock, scope: ScopeId) {
let inner = match (&b.label, b.label_span) {
(Some(label), Some(ls)) => self.declare_with_scope(
scope,
label,
SymbolKind::Block,
ls,
b.span,
ScopeKind::Generate,
),
_ => self.new_scope(ScopeKind::Generate, scope, b.span),
};
self.bind_items(&b.items, inner);
self.use_end_label(scope, inner, b.end_label.as_ref(), b.end_label_span);
}
fn bind_function(&mut self, f: &'a FunctionDecl, span: TextRange, scope: ScopeId) {
if !f.scope.is_empty() {
// An out-of-body definition binds into its class's scope, which
// may not exist yet — deferred until the whole file is bound.
self.deferred.push(Deferred::Function(f, span, scope));
return;
}
if let Some(ret) = &f.ret {
self.bind_data_type(ret, TextRange::new(span.start, f.name_span.start), scope);
}
let inner = self.declare_with_scope(
scope,
&f.name,
SymbolKind::Function,
f.name_span,
span,
ScopeKind::Function,
);
self.bind_tf_args(&f.args, inner);
self.bind_stmts(&f.stmts, inner);
self.use_end_label(scope, inner, f.end_label.as_ref(), f.end_label_span);
}
fn bind_task(&mut self, t: &'a TaskDecl, span: TextRange, scope: ScopeId) {
if !t.scope.is_empty() {
self.deferred.push(Deferred::Task(t, span, scope));
return;
}
let inner = self.declare_with_scope(
scope,
&t.name,
SymbolKind::Task,
t.name_span,
span,
ScopeKind::Task,
);
self.bind_tf_args(&t.args, inner);
self.bind_stmts(&t.stmts, inner);
self.use_end_label(scope, inner, t.end_label.as_ref(), t.end_label_span);
}
/// One `modport mp (input a, output b)` of a `modport` declaration.
///
/// The name is a **declaration**: it is what an interface port's
/// `bus_if.mp` type names, what a connection's `b_if.mp` names, and what a
/// hover on either should show. Every name in the port list is a *use* of
/// something the interface itself declares — a signal for
/// `input`/`output`/`inout`/`ref`, a method for `import`/`export`, the
/// clocking block for `clocking cb` — and all of them are one lookup in
/// this very scope ([`Target::InScope`]), because IEEE 1800 §25.5 says a
/// modport port names a member of the interface and nothing else.
fn bind_modport(&mut self, d: &'a ModportDecl, scope: ScopeId) {
self.declare(scope, &d.name, SymbolKind::Modport, d.name_span, d.span);
for port in &d.ports {
for name in &port.names {
self.use_name(scope, &name.text, name.span, Target::InScope);
}
if let Some(p) = &port.prototype {
self.bind_modport_prototype(p, port.span, scope);
}
}
}
/// `modport mp (import task drive(int x))` — a method prototype in a
/// modport port list (IEEE 1800 §25.5.4).
///
/// The name it writes is the interface's own task or function, so it is
/// a *use* on exactly the terms the `import drive` spelling is: one lookup
/// in this very scope ([`Target::InScope`]), never outward. Its formals
/// are a re-statement of that subroutine's own, not new declarations of
/// the interface — but they must still bind, so they are declared in a
/// block scope opened for the prototype, where they neither leak nor go
/// unbound.
fn bind_modport_prototype(&mut self, p: &'a TfPrototype, span: TextRange, scope: ScopeId) {
self.use_name(scope, &p.name, p.name_span, Target::InScope);
if let Some(ret) = &p.ret {
self.bind_data_type(ret, TextRange::new(span.start, p.name_span.start), scope);
}
let inner = self.new_scope(ScopeKind::Block, scope, span);
self.bind_tf_args(&p.args, inner);
}
/// A `clocking cb @(posedge clk); … endclocking` block.
///
/// A **named** block with an event declares a symbol whose declared type is
/// the enclosing unit's own name. A clocking signal is an alias of the
/// same-named signal in that unit (IEEE 1800 §14.4), so pointing the
/// block's "type" back at the interface makes `vif.cb.data` and `cb.data`
/// answer with `data`'s own declaration — the honest answer — through
/// exactly the member chase round 2 already built, with no new machinery.
///
/// `default clocking cb;` selects a block declared elsewhere in the same
/// scope and is therefore a *use*; an anonymous `default clocking @(...)`
/// names nothing and declares nothing.
fn bind_clocking(&mut self, c: &ClockingDecl, span: TextRange, scope: ScopeId) {
match (&c.name, &c.event) {
(Some(name), Some(_)) => {
let ty = self.enclosing_unit_name(scope);
let id = self.declare(scope, &name.text, SymbolKind::Clocking, name.span, span);
if let Some(id) = id {
self.symbols[id.0 as usize].type_name = ty;
}
}
(Some(name), None) => self.use_name(scope, &name.text, name.span, Target::InScope),
(None, _) => {}
}
if let Some(event) = &c.event {
self.bind_sens_list(event, scope);
}
for item in &c.items {
let ClockingItemKind::Signals { signals, .. } = &item.kind else {
continue;
};
for signal in signals {
match &signal.value {
// `output tms = _tms_internal;` binds the clocking name to
// something *else*, so the name on the left is the block's
// own and names no signal of the enclosing scope
// (IEEE 1800 §14.4). Only the value is a use.
Some(value) => self.bind_expr(value, scope),
None => {
self.use_name(scope, &signal.name.text, signal.name.span, Target::InScope)
}
}
}
}
}
/// The name of the nearest enclosing `module` or `interface` — what a
/// clocking block records as its declared type. `None` at file scope, and
/// inside a class, where a clocking block cannot stand anyway.
fn enclosing_unit_name(&self, scope: ScopeId) -> Option<String> {
let mut current = Some(scope);
while let Some(id) = current {
let s = self.scopes.get(id.0 as usize)?;
if let Some(owner) = s.owner {
let symbol = self.symbols.get(owner.0 as usize)?;
if symbol.kind.is_instantiable() {
return Some(symbol.name.clone());
}
}
current = s.parent;
}
None
}
}