//! Pass one: walk the tree, open scopes, bind declarations, and record every //! identifier *use* as a pending reference. Nothing is resolved here — that is //! `resolve.rs`, and the split is what makes forward references work. use std::collections::HashMap; use vlog_parser::ast::*; use vlog_parser::span::TextRange; use vlog_parser::token::is_keyword; use crate::model::{Import, Scope, ScopeId, ScopeKind, Symbol, SymbolId, SymbolKind}; use crate::scan::{name_after_kw, NameScanner}; /// A recorded use, waiting for pass two to say what it names. pub(crate) struct Pending { pub name: String, pub name_span: TextRange, pub scope: ScopeId, pub target: Target, } /// Where pass two must look for a pending use. pub(crate) enum Target { /// The lexical chain from `scope` outward, imports included. Lexical, /// A name written where a **type** goes — the user-defined type of a /// declaration, a port, a parameter, a return type, a `virtual` interface /// property. Looked up exactly like [`Target::Lexical`], but a miss also /// carries the bare name to the workspace, because that is how a /// cross-file `interface`, `class` or `typedef` is spelled. Every type /// position reaches this through [`Binder::bind_data_type`]; an /// identifier in a *value* position never does. Type, /// A package name: the `p` of `import p::x`. Only a package can be /// imported, so this stays narrower than [`Target::Unit`]. Package, /// A module name: the type of an instantiation. Module, /// A unit name — package or class (or a `typedef class` forward /// declaration): the head of `p::x`, an `extends`/`implements` base, the /// `cls` of an out-of-body method definition. Unit, /// The `x` of `p::x` (and an `extends base #(.x(...))` override): looked /// up inside the named unit's scope only, never in the lexical chain. UnitMember(String), /// The `.port` of a connection to the named module. Port(String), /// The `member` of `head.mids….member`, where `head` is a plain /// identifier this file may declare: looked up in the scope of the head's /// **declared type**, then up that type's `extends` chain, one hop per /// name in `mids`. /// /// Carries the *spellings* rather than the inner tails' resolutions, /// because the type of a link is only known once the link before it is /// resolved, which is pass two's job — and because a spelling is all the /// workspace layer gets either way: a chain that leaves this file becomes /// one composed path (`pkt_t::hdr::addr`), read by the same /// `follow_one` every other path goes through. MemberOf { head: String, mids: Vec }, /// The `x` of `this.x`: the enclosing class's scope only. ThisMember, /// The `x` of `super.x`: always the base class's business. SuperMember, /// Exactly this declaration, with no lookup at all: an end label /// (`endmodule : m`, `endfunction : f`, `end : blk`) names the construct /// it closes and nothing else. Declaration(SymbolId), } /// An out-of-body method definition (`function void cls::method(...)`), held /// until the whole file is bound so `cls` can be looked up wherever it is /// declared — before or after the definition. enum Deferred<'a> { Function(&'a FunctionDecl, TextRange, ScopeId), Task(&'a TaskDecl, TextRange, ScopeId), } pub(crate) struct Binder<'a> { src: &'a str, pub(crate) scopes: Vec, pub(crate) symbols: Vec, pub(crate) pending: Vec, deferred: Vec>, } impl<'a> Binder<'a> { pub(crate) fn new(src: &'a str, file_span: TextRange) -> Self { let file = Scope { kind: ScopeKind::File, parent: None, owner: None, span: file_span, symbols: Vec::new(), children: Vec::new(), imports: Vec::new(), extends: None, names: HashMap::new(), }; Binder { src, scopes: vec![file], symbols: Vec::new(), pending: Vec::new(), deferred: Vec::new(), } } pub(crate) fn file_scope(&self) -> ScopeId { ScopeId(0) } // ------------------------------------------------------------------ // Tables // ------------------------------------------------------------------ fn new_scope(&mut self, kind: ScopeKind, parent: ScopeId, span: TextRange) -> ScopeId { let id = ScopeId(self.scopes.len() as u32); self.scopes.push(Scope { kind, parent: Some(parent), owner: None, span, symbols: Vec::new(), children: Vec::new(), imports: Vec::new(), extends: None, names: HashMap::new(), }); self.scopes[parent.0 as usize].children.push(id); id } /// Bind `name` in `scope`. A name already bound there becomes a reference /// to the first declaration instead of a second symbol — which is how a /// non-ANSI port's body declaration attaches to its header port, and how /// an out-of-body method definition attaches to its `extern` prototype. fn declare( &mut self, scope: ScopeId, name: &str, kind: SymbolKind, name_span: TextRange, decl_span: TextRange, ) -> Option { if name.is_empty() { return None; } if self.scopes[scope.0 as usize].names.contains_key(name) { self.use_name(scope, name, name_span, Target::Lexical); return None; } let id = SymbolId(self.symbols.len() as u32); self.symbols.push(Symbol { name: name.to_string(), kind, name_span, decl_span, detail_span: None, type_name: None, scope, child_scope: None, }); let s = &mut self.scopes[scope.0 as usize]; s.symbols.push(id); s.names.insert(name.to_string(), id); Some(id) } /// [`Binder::declare`] for a declaration written with a type, recording /// that type's name on the symbol — what `handle.member` is looked up /// with. A redeclaration binds nothing and records nothing here either. /// /// `ty` is `None` where the declared name is not itself a value of the /// type: an **unpacked** declarator (`c1 q[$]`, `item_t pool[4]`) names a /// container, and `q.size()` is a built-in array method, not a member of /// `c1` — the element is reached through an index, which is a head this /// crate does not type (TODO.md §15, round 2). fn declare_typed( &mut self, scope: ScopeId, name: &str, kind: SymbolKind, name_span: TextRange, decl_span: TextRange, ty: Option<&DataType>, ) -> Option { let id = self.declare(scope, name, kind, name_span, decl_span); if let Some(id) = id { self.symbols[id.0 as usize].type_name = ty.and_then(type_name_of); } id } /// Declare `name` and open the scope it owns. fn declare_with_scope( &mut self, scope: ScopeId, name: &str, kind: SymbolKind, name_span: TextRange, decl_span: TextRange, child_kind: ScopeKind, ) -> ScopeId { let sym = self.declare(scope, name, kind, name_span, decl_span); let child = self.new_scope(child_kind, scope, decl_span); if let Some(sym) = sym { self.symbols[sym.0 as usize].child_scope = Some(child); self.scopes[child.0 as usize].owner = Some(sym); } child } /// Record a use — unless it is not a name this crate can say anything /// about: a system task (`$display`), a macro standing where a name /// belongs (`` `PICORV32_REGS regs (...) ``), a keyword the parser kept /// in an identifier slot, or one of the four class words the lexer leaves /// as identifiers (`this`/`super` are modelled through their member /// accesses, `null` is a literal, and a bare `new` names the constructor /// of the *assigned* class, which needs types this crate does not have). fn use_name(&mut self, scope: ScopeId, name: &str, name_span: TextRange, target: Target) { if matches!(name, "this" | "super" | "null" | "new") { return; } self.use_member(scope, name, name_span, target); } /// Like [`Binder::use_name`], but keeps `new`: the tail of `super.new(...)` /// really does name the base class's constructor. fn use_member(&mut self, scope: ScopeId, name: &str, name_span: TextRange, target: Target) { if name.is_empty() || name.starts_with('$') || name.starts_with('`') || is_keyword(name) { return; } self.pending.push(Pending { name: name.to_string(), name_span, scope, target }); } /// `endmodule : m`, `endfunction : f`, `end : blk`: an end label names the /// declaration it closes, so it is recorded as a use of exactly that /// symbol — never looked up, so it can never attach to a same-named /// declaration somewhere else. A label that does not spell the declared /// name is an error the linter owns, and records nothing. fn use_end_label( &mut self, scope: ScopeId, body: ScopeId, label: Option<&String>, span: Option, ) { let (Some(label), Some(span)) = (label, span) else { return; }; // `None` when the declaration was a redeclaration and bound no symbol // of its own; the label is then left unrecorded, as it was before. let Some(sym) = self.scopes[body.0 as usize].owner else { return; }; if self.symbols[sym.0 as usize].name != *label { return; } let span = self.exact_or_empty(span, label); if span.is_empty() { return; } self.use_member(scope, label, span, Target::Declaration(sym)); } /// `span` when it slices to exactly `name`, else an empty range at its /// start. Guards the ranges this crate derives instead of receiving — /// a source spelling `pkg :: mod` must cost a span, never mislocate one. fn exact_or_empty(&self, span: TextRange, name: &str) -> TextRange { let range = span.as_range(); if range.end <= self.src.len() && self.src.get(range.clone()).is_some_and(|s| s == name) { span } else { TextRange::empty(span.start) } } // ------------------------------------------------------------------ // Items // ------------------------------------------------------------------ pub(crate) fn bind_items(&mut self, items: &'a [Item], scope: ScopeId) { for item in items { self.bind_item(item, scope); } } 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, SymbolKind::Param, &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), // A `bind` directive instantiates into *another* scope, so its // instance name and connections do not belong to this one. Only // the instantiation's module name is indexed, which is what makes // the bound module show up as a dependency of this file. Whether // the target scope and the connections should resolve too is a // vlog_semantic decision — see `docs/features/bind/README.md` // Handshakes. ItemKind::Bind(b) => self.bind_instantiation_module(&b.inst, 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::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::Defparam(pairs) => { for (lhs, rhs) in pairs { self.bind_expr(lhs, scope); self.bind_expr(rhs, 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. // `modport` and `clocking` are leaves here for now: both name // signals that are declared in the enclosing interface, so // resolving them is a reference-binding question rather than a // declaration one, and whether a modport or a clocking block // should itself be a symbol is a vlog_semantic decision — see // `docs/features/interfaces/README.md` Handshakes. ItemKind::Modport(_) | ItemKind::Clocking(_) | 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) { let inner = self.declare_with_scope( scope, &m.name, SymbolKind::Module, 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 { PortList::Ansi(ports) => { for p in ports { 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 { 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); } /// A `#( ... )` header parameter list — module and class headers share it. fn bind_param_ports(&mut self, ports: impl Iterator, scope: ScopeId) { for p in ports { self.bind_data_type(&p.ty, TextRange::new(p.span.start, p.name_span.start), scope); let ty = p.unpacked.is_empty().then_some(&p.ty); self.declare_typed(scope, &p.name, SymbolKind::Param, p.name_span, p.span, ty); self.bind_dims(&p.unpacked, scope); self.bind_opt_expr(p.default.as_ref(), scope); } } /// Record one `pkg::item` / `pkg::*` path as an import of `scope`. 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_typedef(&mut self, t: &Typedef, span: TextRange, scope: ScopeId) { let ns = t.name_span; match &t.kind { // The aliased type is recorded on the alias, so `typedef c1 my_t; // my_t h; h.x` can follow the alias to the class (round 2). An // alias **with unpacked dimensions** (`typedef c1 q_t[4];`) names // a container, not a value of the type, and is left untyped on // the same rule every other unpacked declarator follows. TypedefKind::Alias(ty) => { self.bind_data_type(ty, TextRange::new(span.start, ns.start), scope); let ty = t.unpacked.is_empty().then_some(ty); self.declare_typed(scope, &t.name, SymbolKind::Typedef, ns, span, ty); } TypedefKind::Enum(e) => { self.declare(scope, &t.name, SymbolKind::Typedef, ns, span); if let Some(base) = &e.base { self.bind_data_type(base, TextRange::new(span.start, ns.start), scope); } // LRM: enum names belong to the scope holding the enum. for m in &e.members { self.declare(scope, &m.name, SymbolKind::EnumVariant, m.name_span, m.span); self.bind_opt_expr(m.value.as_ref(), scope); } } TypedefKind::Struct(s) => { let inner = self.declare_with_scope( scope, &t.name, SymbolKind::Typedef, ns, span, ScopeKind::Struct, ); for m in &s.members { let first = m.declarators.first().map(|d| d.span.start).unwrap_or(m.span.end); self.bind_data_type(&m.ty, TextRange::new(m.span.start, first), scope); for d in &m.declarators { self.declare(inner, &d.name, SymbolKind::StructMember, d.name_span, d.span); self.bind_dims(&d.unpacked, scope); self.bind_opt_expr(d.init.as_ref(), scope); } } } // `typedef class c;` promises a class declared elsewhere; the // name is declared here so a reference to it resolves to the // forward declaration. TypedefKind::ForwardClass => { self.declare(scope, &t.name, SymbolKind::Typedef, ns, span); } } self.bind_dims(&t.unpacked, scope); } fn bind_data_decl(&mut self, d: &DataDecl, span: TextRange, scope: ScopeId) { let kind = if d.net.is_some() { SymbolKind::Net } else { SymbolKind::Var }; self.bind_opt_expr(d.delay.as_ref(), scope); self.bind_declarators(&d.declarators, kind, &d.ty, span, scope); } fn bind_port_decl(&mut self, p: &PortDecl, span: TextRange, scope: ScopeId) { let kind = match self.scopes[scope.0 as usize].kind { ScopeKind::Function | ScopeKind::Task => SymbolKind::TfArg, _ => SymbolKind::Port, }; // A non-ANSI port's body declaration (`input signed [31:0] data_in;`) // completes a port the header only named (`data_in,`). `declare` // below attaches it as a reference to that header symbol — and here, // the whole declaration's span is recorded on the symbol as where its // direction, type and width are written. First writer wins, so a // header that names a port twice is the linter's to complain about // and this stays deterministic. // // An old-style task or function argument (`task t(a);` finished by // `input [7:0] a;`) is the same header-names-it, body-completes-it // shape and merges through the same `declare`, so it is recorded on // the same terms — matching on `kind` rather than on `Port` alone. // // The type is recorded on the same terms: a header port is named // without one, and the body declaration is where it is written. let names = &self.scopes[scope.0 as usize].names; let existing: Vec<(SymbolId, bool)> = p .declarators .iter() .filter_map(|d| Some((names.get(d.name.as_str()).copied()?, d.unpacked.is_empty()))) .collect(); for (id, plain) in existing { let type_name = plain.then(|| type_name_of(&p.ty)).flatten(); let symbol = &mut self.symbols[id.0 as usize]; if symbol.kind != kind { continue; } if symbol.detail_span.is_none() { symbol.detail_span = Some(span); } if symbol.type_name.is_none() { symbol.type_name = type_name; } } self.bind_declarators(&p.declarators, kind, &p.ty, span, scope); } fn bind_declarators( &mut self, declarators: &[Declarator], kind: SymbolKind, ty: &DataType, span: TextRange, scope: ScopeId, ) { let first = declarators.first().map(|d| d.span.start).unwrap_or(span.end); self.bind_data_type(ty, TextRange::new(span.start, first), scope); for d in declarators { self.declare_typed( scope, &d.name, kind, d.name_span, d.span, d.unpacked.is_empty().then_some(ty), ); self.bind_dims(&d.unpacked, scope); self.bind_opt_expr(d.init.as_ref(), scope); } } 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() { 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); match &inst.conns { Connections::Named(conns) => { for c in conns { self.bind_connection(c, &i.module, scope); } } Connections::Ordered(conns) => { for c in conns { self.bind_opt_expr(c.expr.as_ref(), scope); } } } } } /// The module-name half of [`Self::bind_instantiation`], for a `bind` /// directive: the instance and its connections live in the target scope, /// not in `scope`, so only the instantiated module is recorded. fn bind_instantiation_module(&mut self, i: &Instantiation, scope: ScopeId) { let ns = self.exact_or_empty(i.module_span, &i.module); self.use_name(scope, &i.module, ns, Target::Module); } 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_some() { // 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_some() { 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); } fn bind_tf_args(&mut self, args: &'a [TfArg], scope: ScopeId) { for a in args { self.bind_data_type(&a.ty, TextRange::new(a.span.start, a.name_span.start), scope); let ty = a.unpacked.is_empty().then_some(&a.ty); self.declare_typed(scope, &a.name, SymbolKind::TfArg, a.name_span, a.span, ty); self.bind_dims(&a.unpacked, scope); self.bind_opt_expr(a.default.as_ref(), scope); } } // ------------------------------------------------------------------ // Classes // ------------------------------------------------------------------ fn bind_class(&mut self, c: &'a ClassDecl, span: TextRange, scope: ScopeId) { let inner = self.declare_with_scope( scope, &c.name, SymbolKind::Class, c.name_span, span, ScopeKind::Class, ); // Header `#( ... )` parameters bind like a module's. self.bind_param_ports(c.param_ports.iter().flatten(), inner); if let Some(ext) = &c.extends { self.scopes[inner.0 as usize].extends = Some(ext.name.clone()); // The base name resolves from the *enclosing* scope — a class is // not visible to its own header. self.use_scoped_unit(&ext.name, ext.name_span, scope); // Overrides: `.W` is the base's parameter; the value may name the // class's own parameters (`extends base #(.W(W))`), so it binds // in the class scope. let base = last_segment(&ext.name); for conn in ext.params.iter().flatten() { if conn.name != "*" { self.use_name( inner, &conn.name, conn.name_span, Target::UnitMember(base.to_string()), ); } self.bind_opt_expr(conn.expr.as_ref(), inner); } } for n in &c.implements { self.use_scoped_unit(&n.text, n.span, scope); } // The body is an ordinary item list; everything the item walk already // does — declarations, typedefs, localparams, imports, methods, // nested classes — works here unchanged. Verbatim members // (constraints, covergroups) stay opaque through the item arm. self.bind_items(&c.items, inner); self.use_end_label(scope, inner, c.end_label.as_ref(), c.end_label_span); } /// Record a unit name that may be scope-qualified: `base`, `pkg::base`. /// A qualified spelling records head and tail (middle segments of a /// longer chain are not recorded; the corpus has none). Both spans are /// derived from the glued text, so each is verified before use and the /// reference is skipped when the source spelled spaces around the `::`. fn use_scoped_unit(&mut self, name: &str, span: TextRange, scope: ScopeId) { match name.rsplit_once("::") { Some((head_path, tail)) => { let head = head_path.split("::").next().unwrap_or(head_path); let head_span = self.exact_or_empty( TextRange::new(span.start, span.start.saturating_add(head.len() as u32)), head, ); if !head_span.is_empty() { self.use_name(scope, head, head_span, Target::Unit); } let tail_span = self.exact_or_empty( TextRange::new(span.end.saturating_sub(tail.len() as u32), span.end), tail, ); let owner = head_path.rsplit("::").next().unwrap_or(head_path); if !tail_span.is_empty() { self.use_name(scope, tail, tail_span, Target::UnitMember(owner.to_string())); } } None => self.use_name(scope, name, span, Target::Unit), } } /// Bind the out-of-body method definitions collected during the walk. /// Runs after everything else is bound, so the class scope exists no /// matter where the class is written. pub(crate) fn bind_deferred(&mut self) { let deferred = std::mem::take(&mut self.deferred); for d in deferred { match d { Deferred::Function(f, span, scope) => { let path = f.scope.as_deref().unwrap_or(""); self.bind_out_of_body( path, &f.name, f.name_span, span, scope, SymbolKind::Function, ScopeKind::Function, f.ret.as_ref(), &f.args, &f.stmts, ); } Deferred::Task(t, span, scope) => { let path = t.scope.as_deref().unwrap_or(""); self.bind_out_of_body( path, &t.name, t.name_span, span, scope, SymbolKind::Task, ScopeKind::Task, None, &t.args, &t.stmts, ); } } } } /// One `function void cls::method(...)` definition: the method symbol /// binds into `cls`'s scope (an `extern` prototype already there makes /// the definition-site name a reference to it — the same /// redeclaration-becomes-reference rule non-ANSI ports use), and the body /// scope hangs under `cls`'s scope so properties resolve. // The allow: one call shape, two callers; a parameter struct would // outweigh the function. #[allow(clippy::too_many_arguments)] fn bind_out_of_body( &mut self, path: &str, name: &str, name_span: TextRange, span: TextRange, decl_scope: ScopeId, kind: SymbolKind, scope_kind: ScopeKind, ret: Option<&DataType>, args: &'a [TfArg], stmts: &'a [Stmt], ) { // The written class path is a reference of its own — navigation from // `cls::method` to the class. Its span is derived (the parser glues // the path), so it is verified and skipped when inexact. let cls = last_segment(path); let cls_span = TextRange::new( name_span.start.saturating_sub(2).saturating_sub(cls.len() as u32), name_span.start.saturating_sub(2), ); let cls_span = self.exact_or_empty(cls_span, cls); if !cls_span.is_empty() { self.use_name(decl_scope, cls, cls_span, Target::Unit); } // The method's home: the class scope when the class is in this file, // else a scope standing in for that class — empty, so every lookup // falls straight through it to the writing scope, but marked with the // class path as its `extends`, so a name nothing else binds is an // `InheritedCandidate` against the class rather than a `NotFound`. // That is what lets `task c2::update(...)` see `c2`'s properties when // `c2` is declared in another file: the workspace index finishes the // candidate through its member table. let home = match self.find_unit_scope(decl_scope, path) { Some(scope) => scope, None if path.is_empty() => decl_scope, None => { let stand_in = self.new_scope(ScopeKind::Class, decl_scope, span); self.scopes[stand_in.0 as usize].extends = Some(path.to_string()); stand_in } }; let sym = self.declare(home, name, kind, name_span, span); let body = self.new_scope(scope_kind, home, span); match sym { Some(sym) => { self.symbols[sym.0 as usize].child_scope = Some(body); self.scopes[body.0 as usize].owner = Some(sym); } // The prototype owns the name; mark the body scope as owned by it // (without touching the prototype's own scope) so method locals // do not spill into the class outline. None => { self.scopes[body.0 as usize].owner = self.scopes[home.0 as usize].lookup_local(name); } } // Return type, arguments and body all resolve from inside the class, // as the LRM says an out-of-body declaration does. if let Some(ret) = ret { self.bind_data_type(ret, TextRange::new(span.start, name_span.start), body); } self.bind_tf_args(args, body); self.bind_stmts(stmts, body); } /// The scope of the unit `path` names, resolved lexically from `from` and /// descended segment by segment (`pkg::cls`). fn find_unit_scope(&self, from: ScopeId, path: &str) -> Option { let mut segments = path.split("::"); let mut scope = self.lookup_unit_scope(from, segments.next()?)?; for seg in segments { let sym = self.scopes[scope.0 as usize].lookup_local(seg)?; let s = self.symbols.get(sym.0 as usize)?; if !matches!(s.kind, SymbolKind::Class | SymbolKind::Package) { return None; } scope = s.child_scope?; } Some(scope) } /// The scope of the class or package `name`, found on the lexical chain /// from `from`; non-unit shadowers are skipped. fn lookup_unit_scope(&self, from: ScopeId, name: &str) -> Option { let mut current = Some(from); while let Some(id) = current { let scope = self.scopes.get(id.0 as usize)?; if let Some(sym) = scope.lookup_local(name) { if let Some(s) = self.symbols.get(sym.0 as usize) { if matches!(s.kind, SymbolKind::Class | SymbolKind::Package) { if let Some(child) = s.child_scope { return Some(child); } } } } current = scope.parent; } None } // ------------------------------------------------------------------ // Statements // ------------------------------------------------------------------ fn bind_stmts(&mut self, stmts: &'a [Stmt], scope: ScopeId) { for s in stmts { self.bind_stmt(s, scope); } } fn bind_stmt(&mut self, stmt: &'a Stmt, scope: ScopeId) { match &stmt.kind { StmtKind::Block { label, label_span, stmts, end_label, end_label_span, .. } | StmtKind::ForkJoin { label, label_span, stmts, end_label, end_label_span, .. } => { let inner = match (label, *label_span) { (Some(label), Some(ls)) => self.declare_with_scope( scope, label, SymbolKind::Block, ls, stmt.span, ScopeKind::Block, ), _ => self.new_scope(ScopeKind::Block, scope, stmt.span), }; self.bind_stmts(stmts, inner); self.use_end_label(scope, inner, end_label.as_ref(), *end_label_span); } StmtKind::If { cond, then, els, .. } => { self.bind_expr(cond, scope); self.bind_stmt(then, scope); if let Some(e) = els { self.bind_stmt(e, scope); } } StmtKind::Case { expr, items, .. } => { self.bind_expr(expr, scope); self.bind_case_items(items, scope); } StmtKind::RandCase { items, .. } => self.bind_case_items(items, scope), // A statement label names the statement the way a block name // names its block (IEEE 1800 §9.3.5). StmtKind::Labeled { name, name_span, stmt: inner } => { self.declare(scope, name, SymbolKind::Block, *name_span, stmt.span); self.bind_stmt(inner, scope); } StmtKind::Import(paths) => { for path in paths { self.bind_import_path(path, scope); } } StmtKind::For { init, cond, step, body } => { let inner = self.new_scope(ScopeKind::Block, scope, stmt.span); for i in init { match &i.ty { Some(ty) => { if let ExprKind::Ident(name) = &i.assign.lhs.kind { self.bind_data_type( ty, TextRange::new(stmt.span.start, i.assign.lhs.span.start), scope, ); self.declare( inner, name, SymbolKind::Var, i.assign.lhs.span, i.assign.lhs.span, ); } } None => self.bind_expr(&i.assign.lhs, inner), } self.bind_expr(&i.assign.rhs, inner); } self.bind_opt_expr(cond.as_ref(), inner); for s in step { match s { ForStep::Assign(a) => { self.bind_expr(&a.lhs, inner); self.bind_expr(&a.rhs, inner); } ForStep::Expr(e) => self.bind_expr(e, inner), } } self.bind_stmt(body, inner); } StmtKind::While { cond, body } | StmtKind::DoWhile { body, cond } => { self.bind_expr(cond, scope); self.bind_stmt(body, scope); } StmtKind::Repeat { count, body } => { self.bind_expr(count, scope); self.bind_stmt(body, scope); } StmtKind::Forever { body } => self.bind_stmt(body, scope), StmtKind::Foreach { target, vars, body } => { let inner = self.new_scope(ScopeKind::Block, scope, stmt.span); self.bind_expr(target, scope); // A skipped dimension (`arr[, j]`) arrives as an empty name; // `declare` already ignores those, so it declares nothing. for v in vars { self.declare(inner, &v.text, SymbolKind::Var, v.span, v.span); } self.bind_stmt(body, inner); } StmtKind::Assign { lhs, timing, rhs, .. } => { self.bind_expr(lhs, scope); if let Some(t) = timing { self.bind_timing(t, scope); } self.bind_expr(rhs, scope); } StmtKind::ForceRelease { lhs, rhs, .. } => { self.bind_expr(lhs, scope); self.bind_opt_expr(rhs.as_ref(), scope); } StmtKind::Timing { control, stmt } => { self.bind_timing(control, scope); if let Some(s) = stmt { self.bind_stmt(s, scope); } } StmtKind::Wait { cond, stmt } => { self.bind_expr(cond, scope); if let Some(s) = stmt { self.bind_stmt(s, scope); } } StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => self.bind_expr(e, scope), StmtKind::VarDecl(d) => self.bind_data_decl(d, stmt.span, scope), // A block-scoped type binds exactly as an item-level one does; the // scope it lands in is the enclosing block's, which is what // IEEE 1800 §6.18 asks for. StmtKind::Typedef(t) => self.bind_typedef(t, stmt.span, scope), StmtKind::ParamDecl(p) => { self.bind_declarators(&p.declarators, SymbolKind::Param, &p.ty, stmt.span, scope) } StmtKind::PortDecl(p) => self.bind_port_decl(p, stmt.span, scope), StmtKind::Return(e) => self.bind_opt_expr(e.as_ref(), scope), StmtKind::Disable(name) => { // A use, not a declaration, so name-spans deliberately gave it // no range — the one statement still located by scanning. let ns = name_after_kw(self.src, stmt.span, "disable", name); self.use_name(scope, name, ns, Target::Lexical); } StmtKind::Assert { cond, then, els, .. } => { self.bind_expr(cond, scope); if let Some(s) = then { self.bind_stmt(s, scope); } if let Some(s) = els { self.bind_stmt(s, scope); } } StmtKind::Break | StmtKind::Continue | StmtKind::WaitFork | StmtKind::Directive(_) | StmtKind::MacroStmt(_) | StmtKind::Null // Verbatim source: opaque to name resolution, exactly as the // item-level `ItemKind::Verbatim` is. | StmtKind::Verbatim(_) | StmtKind::Error(_) => {} } } /// The labels and bodies of a `case`/`randcase` body. fn bind_case_items(&mut self, items: &'a [CaseItem], scope: ScopeId) { for it in items { for l in &it.labels { self.bind_expr(&l.expr, scope); } self.bind_stmt(&it.stmt, scope); } } fn bind_timing(&mut self, t: &'a TimingControl, scope: ScopeId) { match t { TimingControl::Delay(e) => self.bind_expr(e, scope), TimingControl::Event(SensList::List(items)) => { for i in items { self.bind_expr(&i.expr, scope); // `@(posedge clk iff enable)` reads `enable` as ordinarily // as it reads `clk`. if let Some(iff) = &i.iff { self.bind_expr(iff, scope); } } } TimingControl::Event(SensList::Star { .. }) => {} // `@name;` without parens — the expression is an ordinary use. TimingControl::Event(SensList::Bare(e)) => self.bind_expr(e, scope), } } // ------------------------------------------------------------------ // Expressions // ------------------------------------------------------------------ fn bind_opt_expr(&mut self, e: Option<&Expr>, scope: ScopeId) { if let Some(e) = e { self.bind_expr(e, scope); } } fn bind_dims(&mut self, dims: &[Dim], scope: ScopeId) { for d in dims { match &d.kind { DimKind::Range { a, b } => { self.bind_expr(a, scope); self.bind_opt_expr(b.as_ref(), scope); } // `[]` and `[*]` hold no expressions — nothing to bind. DimKind::Dynamic | DimKind::Wildcard => {} } } } fn bind_expr(&mut self, e: &Expr, scope: ScopeId) { match &e.kind { ExprKind::Ident(name) => self.use_name(scope, name, e.span, Target::Lexical), ExprKind::Number(_) | ExprKind::Str(_) | ExprKind::Empty(_) => {} ExprKind::Unary { expr, .. } | ExprKind::Postfix { expr, .. } => { self.bind_expr(expr, scope) } ExprKind::Binary { lhs, rhs, .. } => { self.bind_expr(lhs, scope); self.bind_expr(rhs, scope); } ExprKind::Ternary { cond, then, els, .. } => { self.bind_expr(cond, scope); self.bind_expr(then, scope); self.bind_expr(els, scope); } ExprKind::Call { callee, args, .. } => { self.bind_expr(callee, scope); for a in args { self.bind_expr(&a.expr, scope); } } // `new src` — the source handle is an ordinary reference. ExprKind::New(src) => self.bind_expr(src, scope), ExprKind::Index { base, index } => { self.bind_expr(base, scope); self.bind_expr(index, scope); } ExprKind::Range { base, msb, lsb, .. } => { self.bind_expr(base, scope); self.bind_expr(msb, scope); self.bind_expr(lsb, scope); } // `a.b`, `a.b.c`, `tb.dut.u_core.sig`: every link is bound — // the head as an ordinary use, each `.name` as a tail against the // type of what precedes it (`Target::MemberOf`) — because the // recursion below meets each `Member` node in turn. `this.b` and // `super.b` go to the enclosing class instead, and a spine that // starts at one of them stops there: `this.a.b` records `a` and // nothing more (`this` is not a name this crate binds, so there // is no head to walk from). An indexed or called head // (`a[i].b`, `f().b`) still resolves its own head and stops: // chasing those needs the element type of a container, which // this crate does not model (TODO.md §15). ExprKind::Member { base, name } => match &base.kind { ExprKind::Ident(head) if head == "this" => { self.use_member(scope, name, member_tail(e.span, name), Target::ThisMember) } ExprKind::Ident(head) if head == "super" => { self.use_member(scope, name, member_tail(e.span, name), Target::SuperMember) } _ => { self.bind_expr(base, scope); if let Some((head, mids)) = spine(base) { // The tail's range is derived from the whole // expression's, so it is verified before use: a // spelling this crate cannot place costs a reference, // never a wrong span. let tail = self.exact_or_empty(member_tail(e.span, name), name); if !tail.is_empty() { self.use_member(scope, name, tail, Target::MemberOf { head, mids }); } } } }, ExprKind::Scope { base, name } => self.bind_scoped(base, name, e.span, scope), // The `#( ... )` is verbatim text this crate makes no claims // about; the name it parameterizes is still an ordinary use. ExprKind::Parameterized { base, .. } => self.bind_expr(base, scope), ExprKind::Concat(items) => { for i in items { self.bind_expr(&i.expr, scope); } } ExprKind::Inside { lhs, ranges } => { self.bind_expr(lhs, scope); for i in ranges { self.bind_expr(&i.expr, scope); } } ExprKind::Repl { count, inner } | ExprKind::AssignPatternRepl { count, inner } => { self.bind_expr(count, scope); for i in inner { self.bind_expr(&i.expr, scope); } } // The slice size of a streaming concatenation is a constant // expression or a type; both are ordinary uses. ExprKind::Stream { slice, inner, .. } => { if let Some(s) = slice { self.bind_expr(s, scope); } for i in inner { self.bind_expr(&i.expr, scope); } } // The set is a macro invocation this crate makes no claims about. ExprKind::InsideMacro { lhs, .. } => self.bind_expr(lhs, scope), ExprKind::With { base, arg, .. } => { self.bind_expr(base, scope); self.bind_expr(arg, scope); } // The constraint block is verbatim source: opaque to name // resolution, exactly as `StmtKind::Verbatim` is. ExprKind::WithConstraint { base, .. } => self.bind_expr(base, scope), ExprKind::Paren { inner, .. } => self.bind_expr(inner, scope), // Only the cast's operand is bound. The casting type names a // type — a keyword (`int'(x)`), a typedef or a parameter — and // resolving those is the type-name work this crate does not do // anywhere else either. ExprKind::Cast { expr, .. } => self.bind_expr(expr, scope), ExprKind::AssignPattern(items) => { for i in items { self.bind_opt_expr(i.key.as_ref(), scope); self.bind_expr(&i.value, scope); } } ExprKind::ValueRange { lo, hi } => { self.bind_expr(lo, scope); self.bind_expr(hi, scope); } // A named call argument: the value is an ordinary use; the name // is the callee's formal, which this crate does not model (the // same rule connection port names follow). ExprKind::NamedArg { value, .. } => self.bind_expr(value, scope), ExprKind::Type(ty) => self.bind_data_type(ty, e.span, scope), ExprKind::MinTypMax { min, typ, max } => { self.bind_expr(min, scope); self.bind_expr(typ, scope); self.bind_expr(max, scope); } } } /// `p::x`: the head names a unit (package or class), the tail is looked /// up inside it. fn bind_scoped(&mut self, base: &Expr, name: &str, span: TextRange, scope: ScopeId) { let tail = TextRange::new(span.end.saturating_sub(name.len() as u32), span.end); match &base.kind { ExprKind::Ident(unit) => { self.use_name(scope, unit, base.span, Target::Unit); self.use_member(scope, name, tail, Target::UnitMember(unit.clone())); } _ => self.bind_expr(base, scope), } } /// A user-defined type name is a use like any other. `window` is the /// source range the name was written in — everything before the declared /// name, which is where a data type always sits. A `DataType` has no span /// of its own (vlog-semantic handshake item 2, still open), so this is /// the one declaration surface still located by scanning. fn bind_data_type(&mut self, ty: &DataType, window: TextRange, scope: ScopeId) { if !ty.name.is_empty() && !is_keyword(&ty.name) { match ty.name.split_once("::") { Some((unit, item)) => { let mut scanner = NameScanner::new(self.src, window); let unit_span = scanner.find(unit).unwrap_or(TextRange::empty(window.start)); let item_span = scanner.find(item).unwrap_or(TextRange::empty(window.start)); self.use_name(scope, unit, unit_span, Target::Unit); self.use_name(scope, item, item_span, Target::UnitMember(unit.to_string())); } None => { // `bus_if.mp bus` — the parser glues an interface port's // modport onto the type name (IEEE 1800 §25.4). The // interface is the type; the modport is a member of it, // and this crate declares no symbol for a modport // (`ItemKind::Modport` is a leaf here), so the tail is // left unbound rather than recorded as a name that can // never resolve. let name = ty.name.split_once('.').map_or(ty.name.as_str(), |(iface, _)| iface); let ns = crate::scan::name_span(self.src, window, name); self.use_name(scope, name, ns, Target::Type); } } } self.bind_dims(&ty.packed, scope); } } /// The chain of names written before a member access's tail: the plain /// identifier it starts at, and the members already selected from it, in the /// order they are written (`a.b.c`'s tail `c` gives `("a", ["b"])`). /// /// `None` for a spine this crate cannot start walking — an index, a call, a /// cast, or `this`/`super`, which name no declaration to take a type from. fn spine(base: &Expr) -> Option<(String, Vec)> { let mut mids = Vec::new(); let mut current = base; loop { match ¤t.kind { ExprKind::Ident(name) if matches!(name.as_str(), "this" | "super") => return None, ExprKind::Ident(name) => { mids.reverse(); return Some((name.clone(), mids)); } ExprKind::Member { base, name } => { mids.push(name.clone()); current = base; } _ => return None, } } } /// The byte range of a member access's tail: the construct's last token, so /// its range is exactly the last `name.len()` bytes of the whole span. fn member_tail(span: TextRange, name: &str) -> TextRange { TextRange::new(span.end.saturating_sub(name.len() as u32), span.end) } /// The type name to record on a declaration: the name as written, minus the /// interface port's glued-on modport (`bus_if.mp bus` — the interface is the /// type, exactly as [`Binder::bind_data_type`] reads it). `None` for a /// built-in type, whose keyword names no declaration to look members up in. fn type_name_of(ty: &DataType) -> Option { let name = ty.name.split_once('.').map_or(ty.name.as_str(), |(iface, _)| iface); (!name.is_empty() && !is_keyword(name)).then(|| name.to_string()) } /// The last `::` segment of a possibly-qualified path (`pkg::cls` → `cls`). fn last_segment(path: &str) -> &str { path.rsplit("::").next().unwrap_or(path) }