Files
lucisv/crates/vlog_semantic/src/bind.rs
T
lucioandClaude Fable 5 e24d33afab Add concurrent assertions, sequence and property as verbatim items
assert/assume/cover/restrict property (...) [action block], optionally labeled, at item and statement position; sequence...endsequence and property...endproperty declarations. Verbatim pass-through like constraint/covergroup; verify.rs untouched, attack tests added.

Coverage loop round 1, cluster 4: 699 -> 712 / 820 (85.2% -> 86.8%).
Feature README: docs/features/assertions/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-20 23:38:22 -07:00

1136 lines
46 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, 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 `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 `x` of `this.x`: the enclosing class's scope only.
ThisMember,
/// The `x` of `super.x`: always the base class's business.
SuperMember,
}
/// 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<Scope>,
pub(crate) symbols: Vec<Symbol>,
pub(crate) pending: Vec<Pending>,
deferred: Vec<Deferred<'a>>,
}
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<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 (...) ``), 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 });
}
/// `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, .. } => {
let inner = self.declare_with_scope(
scope,
name,
SymbolKind::Package,
*name_span,
item.span,
ScopeKind::Package,
);
self.bind_items(items, inner);
}
ItemKind::Import(paths) => {
for path in paths {
self.bind_import_path(path, 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);
}
}
// 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) => {
self.bind_opt_expr(g.delay.as_ref(), 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.
ItemKind::Export(_)
| ItemKind::Directive(_)
| ItemKind::MacroItem(_)
| ItemKind::Timeunit(_)
| ItemKind::Error(_)
| 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(inner, &p.name, SymbolKind::Port, p.name_span, 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);
}
/// A `#( ... )` header parameter list — module and class headers share it.
fn bind_param_ports(&mut self, ports: impl Iterator<Item = &'a ParamPort>, scope: ScopeId) {
for p in ports {
self.bind_data_type(&p.ty, TextRange::new(p.span.start, p.name_span.start), scope);
self.declare(scope, &p.name, SymbolKind::Param, p.name_span, p.span);
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 {
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 {
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,
};
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(scope, &d.name, kind, d.name_span, d.span);
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 {
self.declare(scope, &inst.name, SymbolKind::Instance, inst.name_span, 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);
}
}
}
}
}
/// 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);
}
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);
}
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);
}
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);
self.declare(scope, &a.name, SymbolKind::TfArg, a.name_span, a.span);
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);
}
/// 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 the scope the definition is written in.
let home = self.find_unit_scope(decl_scope, path).unwrap_or(decl_scope);
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<ScopeId> {
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<ScopeId> {
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, .. }
| StmtKind::ForkJoin { label, label_span, stmts, .. } => {
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);
}
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);
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),
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::Directive(_)
| StmtKind::MacroStmt(_)
| StmtKind::Null
// Verbatim source: opaque to name resolution, exactly as the
// item-level `ItemKind::Verbatim` is.
| StmtKind::Verbatim(_)
| StmtKind::Error(_) => {}
}
}
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);
}
}
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);
}
}
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) — except
// `this.b` and `super.b`, whose member is the whole point.
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),
},
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);
}
// 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 => {
let ns = crate::scan::name_span(self.src, window, &ty.name);
self.use_name(scope, &ty.name, ns, Target::Lexical);
}
}
}
self.bind_dims(&ty.packed, scope);
}
}
/// 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 last `::` segment of a possibly-qualified path (`pkg::cls` → `cls`).
fn last_segment(path: &str) -> &str {
path.rsplit("::").next().unwrap_or(path)
}