Files
lucisv/crates/vlog_semantic/src/bind.rs
T
lucioandClaude Fable 5 7f2e78fc1c Add classes: SystemVerilog class support, corpus 58.0% -> 70.5%
The top corpus blocker (142 extends-blocked UVM/DV files) falls.
Structural support: class/virtual class with parameter ports,
extends (named/ordered params), implements, property qualifiers
(rand/randc/local/protected/static/const), virtual interface
properties, parameterized types, method qualifiers with extern and
pure-virtual prototypes plus out-of-body cls::method definitions,
typedef class, scoped parameterized calls, disable fork. Class
bodies reuse the existing item loop, so Meta, directives, macros and
nesting work with no per-site code. Constraint blocks, covergroups
and parameterized-type #() arguments are span-sliced verbatim leaves
-- their internals are a distinct sub-language where formatting has
no payoff and corruption risk is highest, so 9 masked-corruption
rejection tests ship although verify.rs is byte-identical
(invariant-4 discipline, voluntarily; QA's sabotage recreated the
historical in-string corruption and exactly one pin turned red).

Corpus: 476 -> 578/820 formattable (70.5%), parse-error 344 -> 242,
zero regressions by path, all 578 formattable files round-tripped
individually. 72 of the 142 extends files format; 70 advance to
named next blockers -- queues/dynamic arrays are now the top corpus
blocker (41 files). Two verification failures fixed en route: a
pre-existing lexer blank-line-after-continuation bug (proven
pre-existing on a HEAD worktree) and raw_inline convergence for
mid-line verbatim starts.

Handshakes filed: fences inactive inside class bodies; the four
AST-walking lint rules skip class members (line-based rules still
fire); vlog_semantic treats class bodies as opaque -- the LSP
navigation gap is that crate's natural next round. parse() now takes
the source (verbatim capture in strict mode); single caller updated.

612 workspace tests (397 cases). Dev: Opus agent; QA: Sonnet agent
(pre-feature worktree diff, full 578-file round-trip, UVM torture,
two reverted sabotages); review in docs/features/classes/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-19 13:45:18 -07:00

845 lines
34 KiB
Rust

//! 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, name_span, 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 package name: the `p` of `p::x` or of `import p::x`.
Package,
/// A module name: the type of an instantiation.
Module,
/// The `x` of `p::x`: looked up in package `p`'s scope only.
PackageMember(String),
/// The `.port` of a connection to the named module.
Port(String),
}
pub(crate) struct Binder<'a> {
src: &'a str,
pub(crate) scopes: Vec<Scope>,
pub(crate) symbols: Vec<Symbol>,
pub(crate) pending: Vec<Pending>,
}
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(),
names: HashMap::new(),
};
Binder { src, scopes: vec![file], symbols: Vec::new(), pending: 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(),
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.
fn declare(
&mut self,
scope: ScopeId,
name: &str,
kind: SymbolKind,
name_span: TextRange,
decl_span: TextRange,
) -> Option<SymbolId> {
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,
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)
}
/// 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 (...) ``), or a keyword the parser kept
/// in an identifier slot.
fn use_name(&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 });
}
// ------------------------------------------------------------------
// Items
// ------------------------------------------------------------------
pub(crate) fn bind_items(&mut self, items: &[Item], scope: ScopeId) {
for item in items {
self.bind_item(item, scope);
}
}
fn bind_item(&mut self, item: &Item, scope: ScopeId) {
match &item.kind {
ItemKind::Module(m) => self.bind_module(m, item.span, scope),
ItemKind::Package { kw, name, items, .. } => {
let ns = name_after_kw(self.src, item.span, kw, name);
let inner = self.declare_with_scope(
scope,
name,
SymbolKind::Package,
ns,
item.span,
ScopeKind::Package,
);
self.bind_items(items, inner);
}
ItemKind::Import(paths) => self.bind_imports(paths, item.span, scope),
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);
}
}
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, item.span, scope),
ItemKind::GateInstantiation(g) => {
self.bind_opt_expr(g.delay.as_ref(), scope);
for inst in &g.instances {
if let Some(name) = &inst.name {
let ns = name_span(self.src, inst.span, name);
self.declare(scope, name, SymbolKind::Instance, ns, inst.span);
}
for a in &inst.args {
self.bind_expr(&a.expr, scope);
}
}
}
ItemKind::Genvar(names) => {
let mut scanner = NameScanner::new(self.src, item.span);
for name in names {
let ns = scanner.find(&name.text).unwrap_or(TextRange::empty(item.span.start));
self.declare(scope, &name.text, SymbolKind::Genvar, ns, 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::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.
ItemKind::Directive(_)
| ItemKind::MacroItem(_)
| ItemKind::Timeunit(_)
| ItemKind::Error(_)
| ItemKind::Verbatim(_) => {}
// Classes are parsed and formatted but deliberately not modelled
// here: their scoping rules (inheritance, `this`/`super`, static
// vs. instance members) are a separate design question, and a
// half-model would resolve names wrongly rather than not at all.
// See `docs/features/classes/README.md`.
ItemKind::Class(_) => {}
}
}
fn bind_module(&mut self, m: &Module, span: TextRange, scope: ScopeId) {
let ns = name_after_kw(self.src, span, &m.kw, &m.name);
let inner = self.declare_with_scope(
scope,
&m.name,
SymbolKind::Module,
ns,
span,
ScopeKind::Module,
);
// Header imports, then parameters, then ports: the order they are
// written in, so one scanner walks the header left to right.
let header = TextRange::new(ns.end, span.end);
let mut scanner = NameScanner::new(self.src, header);
for import in &m.imports {
for path in &import.paths {
self.bind_import_path(&path.text(), &mut scanner, inner);
}
}
for p in m.param_ports.iter().flatten() {
let name = self.decl_name(p.span, &p.ty, &p.unpacked, p.default.as_ref(), &p.name);
self.bind_data_type(&p.ty, TextRange::new(p.span.start, name.start), inner);
self.declare(inner, &p.name, SymbolKind::Param, name, p.span);
self.bind_dims(&p.unpacked, inner);
self.bind_opt_expr(p.default.as_ref(), inner);
}
match &m.ports {
PortList::Ansi(ports) => {
for p in ports {
let name =
self.decl_name(p.span, &p.ty, &p.unpacked, p.default.as_ref(), &p.name);
self.bind_data_type(&p.ty, TextRange::new(p.span.start, name.start), inner);
self.declare(inner, &p.name, SymbolKind::Port, name, p.span);
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);
}
fn bind_imports(&mut self, paths: &[ImportPath], span: TextRange, scope: ScopeId) {
let mut scanner = NameScanner::new(self.src, span);
for path in paths {
self.bind_import_path(&path.text(), &mut scanner, scope);
}
}
/// Record one `pkg::item` / `pkg::*` path as an import of `scope`.
fn bind_import_path(&mut self, path: &str, scanner: &mut NameScanner, scope: ScopeId) {
let (package, item) = match path.split_once("::") {
Some((p, i)) => (p, i),
None => (path, "*"),
};
let pkg_span = scanner.find(package).unwrap_or(TextRange::empty(0));
let item = if item == "*" {
None
} else {
// Consume the imported name so the next path starts after it.
let item_span = scanner.find(item).unwrap_or(TextRange::empty(pkg_span.end));
self.use_name(scope, item, item_span, Target::PackageMember(package.to_string()));
Some(item.to_string())
};
self.use_name(scope, package, pkg_span, Target::Package);
self.scopes[scope.0 as usize].imports.push(Import {
package: package.to_string(),
item,
scope: None,
name_span: pkg_span,
});
}
fn bind_typedef(&mut self, t: &Typedef, span: TextRange, scope: ScopeId) {
// The typedef's own name is written last (`typedef enum {...} name;`),
// so it is the last identifier of the construct, not the first.
let ns = self.typedef_name_span(t, span);
match &t.kind {
TypedefKind::Alias(ty) => {
self.bind_data_type(ty, TextRange::new(span.start, ns.start), scope);
self.declare(scope, &t.name, SymbolKind::Typedef, ns, span);
}
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 {
let mns = name_span(self.src, m.span, &m.name);
self.declare(scope, &m.name, SymbolKind::EnumVariant, mns, 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 {
let dns = name_span(self.src, d.span, &d.name);
self.declare(inner, &d.name, SymbolKind::StructMember, dns, d.span);
self.bind_dims(&d.unpacked, scope);
self.bind_opt_expr(d.init.as_ref(), scope);
}
}
}
// `typedef class c;` promises a class this crate does not model
// (see `ItemKind::Class` above); the name is still declared, 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);
}
/// The name of a `typedef` is the last identifier before its `;`.
fn typedef_name_span(&self, t: &Typedef, span: TextRange) -> TextRange {
let mut scanner = NameScanner::new(self.src, span);
let mut last = TextRange::empty(span.start);
while let Some(found) = scanner.find(&t.name) {
last = found;
}
last
}
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,
};
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 {
let ns = name_span(self.src, d.span, &d.name);
self.declare(scope, &d.name, kind, ns, d.span);
self.bind_dims(&d.unpacked, scope);
self.bind_opt_expr(d.init.as_ref(), scope);
}
}
fn bind_instantiation(&mut self, i: &Instantiation, span: TextRange, scope: ScopeId) {
let ns = name_span(self.src, 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 ins = name_span(self.src, inst.span, &inst.name);
self.declare(scope, &inst.name, SymbolKind::Instance, ins, inst.span);
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);
}
}
}
}
}
fn bind_connection(&mut self, c: &Connection, module: &str, scope: ScopeId) {
if c.name != "*" {
let ns = name_span(self.src, c.span, &c.name);
self.use_name(scope, &c.name, ns, Target::Port(module.to_string()));
}
self.bind_opt_expr(c.expr.as_ref(), scope);
}
fn bind_gen_if(&mut self, g: &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: &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: &GenBlock, scope: ScopeId) {
let inner = match &b.label {
Some(label) => {
let ns = name_span(self.src, b.span, label);
self.declare_with_scope(
scope,
label,
SymbolKind::Block,
ns,
b.span,
ScopeKind::Generate,
)
}
None => self.new_scope(ScopeKind::Generate, scope, b.span),
};
self.bind_items(&b.items, inner);
}
fn bind_function(&mut self, f: &FunctionDecl, span: TextRange, scope: ScopeId) {
let ns = name_after_kw(self.src, span, "function", &f.name);
if let Some(ret) = &f.ret {
self.bind_data_type(ret, TextRange::new(span.start, ns.start), scope);
}
let inner = self.declare_with_scope(
scope,
&f.name,
SymbolKind::Function,
ns,
span,
ScopeKind::Function,
);
self.bind_tf_args(&f.args, inner);
self.bind_stmts(&f.stmts, inner);
}
fn bind_task(&mut self, t: &TaskDecl, span: TextRange, scope: ScopeId) {
let ns = name_after_kw(self.src, span, "task", &t.name);
let inner =
self.declare_with_scope(scope, &t.name, SymbolKind::Task, ns, span, ScopeKind::Task);
self.bind_tf_args(&t.args, inner);
self.bind_stmts(&t.stmts, inner);
}
fn bind_tf_args(&mut self, args: &[TfArg], scope: ScopeId) {
for a in args {
let name = self.decl_name(a.span, &a.ty, &a.unpacked, a.default.as_ref(), &a.name);
self.bind_data_type(&a.ty, TextRange::new(a.span.start, name.start), scope);
self.declare(scope, &a.name, SymbolKind::TfArg, name, a.span);
self.bind_dims(&a.unpacked, scope);
self.bind_opt_expr(a.default.as_ref(), scope);
}
}
// ------------------------------------------------------------------
// Statements
// ------------------------------------------------------------------
fn bind_stmts(&mut self, stmts: &[Stmt], scope: ScopeId) {
for s in stmts {
self.bind_stmt(s, scope);
}
}
fn bind_stmt(&mut self, stmt: &Stmt, scope: ScopeId) {
match &stmt.kind {
StmtKind::Block { label, stmts, .. } | StmtKind::ForkJoin { label, stmts, .. } => {
let inner = match label {
Some(label) => {
let ns = name_span(self.src, stmt.span, label);
self.declare_with_scope(
scope,
label,
SymbolKind::Block,
ns,
stmt.span,
ScopeKind::Block,
)
}
None => self.new_scope(ScopeKind::Block, scope, stmt.span),
};
self.bind_stmts(stmts, inner);
}
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);
for it in items {
for l in &it.labels {
self.bind_expr(&l.expr, scope);
}
self.bind_stmt(&it.stmt, 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);
let mut scanner =
NameScanner::new(self.src, TextRange::new(target.span.end, stmt.span.end));
for v in vars {
let ns = scanner.find(&v.text).unwrap_or(TextRange::empty(target.span.end));
self.declare(inner, &v.text, SymbolKind::Var, ns, ns);
}
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),
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) => {
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::Directive(_)
| StmtKind::MacroStmt(_)
| StmtKind::Null
| StmtKind::Error(_) => {}
}
}
fn bind_timing(&mut self, t: &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);
}
}
TimingControl::Event(SensList::Star { .. }) => {}
}
}
// ------------------------------------------------------------------
// 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 {
self.bind_expr(&d.a, scope);
self.bind_opt_expr(d.b.as_ref(), scope);
}
}
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);
}
}
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`: only the head is resolved — see the README.
ExprKind::Member { base, .. } => self.bind_expr(base, scope),
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 } => {
self.bind_expr(count, scope);
for i in inner {
self.bind_expr(&i.expr, scope);
}
}
ExprKind::Paren { inner, .. } => self.bind_expr(inner, scope),
// The cast type is raw text with no span of its own.
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);
}
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 package, 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(pkg) => {
self.use_name(scope, pkg, base.span, Target::Package);
self.use_name(scope, name, tail, Target::PackageMember(pkg.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.
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((pkg, item)) => {
let mut scanner = NameScanner::new(self.src, window);
let pkg_span = scanner.find(pkg).unwrap_or(TextRange::empty(window.start));
let item_span = scanner.find(item).unwrap_or(TextRange::empty(window.start));
self.use_name(scope, pkg, pkg_span, Target::Package);
self.use_name(scope, item, item_span, Target::PackageMember(pkg.to_string()));
}
None => {
let ns = name_span(self.src, window, &ty.name);
self.use_name(scope, &ty.name, ns, Target::Lexical);
}
}
}
self.bind_dims(&ty.packed, scope);
}
/// The range of a declared name that sits between its type and its
/// dimensions/default (a port, a parameter port, a task/function argument).
fn decl_name(
&self,
span: TextRange,
ty: &DataType,
unpacked: &[Dim],
default: Option<&Expr>,
name: &str,
) -> TextRange {
let start = ty.packed.last().map(|d| d.span.end).unwrap_or(span.start);
let end = unpacked
.first()
.map(|d| d.span.start)
.or_else(|| default.map(|e| e.span.start))
.unwrap_or(span.end);
name_span(self.src, TextRange::new(start, end), name)
}
}