`tb.dut.g_sw[0].buf_q` written in a file that does not declare `tb` now resolves like an instance path: the binder marks a dotted path's head (Target::PathHead), resolve/root.rs answers a plain lexical miss with a hierarchical external candidate, head_site roots the spine there, and fold_path walks it — every hop a module/interface surface. find_references, LSP references and rename see every segment; $root.tb works; a local `tb` shadows. FACTS_FORMAT 22. Rooted only when the root is provable (owner's ruling: conservative): not when the head has an import candidate (so `import uvm_pkg::*` with uvm_pkg outside the project stays warned — opentitan's DV force paths behave as before), not from inside a class, not beside a macro that stands where a declaration could (item, statement, port list), not when the root name is also a package or ambiguous. The LSP rename set adds the files of the path's root and middle hops (sources.rs, WorkspaceIndex::path_units_to). An unresolved path is warned once. QA (Opus) x2: F1-F4 and R1 silent-wrong-rename shapes fixed with tests; QA's attack cases 1-6 each warned or correctly renamed; lucisv check hw byte-identical to master. Completion after `tb.` deferred (TODO §65.8). tools/gates.sh: PASS, 15 steps, 5 180 tests, corpus 814/820. docs/features/top-rooted-paths. Co-Authored-By: Claude Opus 5.5 <[email protected]>
452 lines
20 KiB
Rust
452 lines
20 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.
|
|
//!
|
|
//! This file holds what every part of the walk shares: the [`Pending`] record
|
|
//! and the [`Target`] pass two reads, the [`Binder`] state, and the table
|
|
//! plumbing — opening a scope, declaring a name, recording a use, an end
|
|
//! label, a derived span checked against the source. The walk itself is one
|
|
//! sibling per grammar domain, each an `impl Binder` block: `item` (the
|
|
//! item-level walk), `generate` (generate constructs and their blocks),
|
|
//! `decl` (declared names and their types), `class` (classes, constraints,
|
|
//! out-of-body definitions), `cover` (covergroups), `stmt`, `sva`
|
|
//! (assertions) and `expr`.
|
|
|
|
mod class;
|
|
mod cover;
|
|
mod decl;
|
|
mod expr;
|
|
mod generate;
|
|
mod item;
|
|
mod stmt;
|
|
mod sva;
|
|
|
|
use std::collections::HashMap;
|
|
use vlog_parser::ast::*;
|
|
use vlog_parser::span::TextRange;
|
|
use vlog_parser::token::is_keyword;
|
|
|
|
use crate::model::{Duplicate, Scope, ScopeId, ScopeKind, Symbol, SymbolId, SymbolKind};
|
|
|
|
/// 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),
|
|
/// A name that may only be looked up in the scope it is **written in**,
|
|
/// never outward: a modport's port list (IEEE 1800 §25.5 — every name it
|
|
/// governs is declared in that very interface) and a clocking block's
|
|
/// signal list (§14.4). Walking outward here would be a wrong answer
|
|
/// waiting to happen: `modport mp (input other_if)` must not find a
|
|
/// file-scope `other_if` because the interface itself declares no such
|
|
/// signal. A miss records **nothing**.
|
|
InScope,
|
|
/// The `mp` of a glued interface type name — `bus_if.mp bus`,
|
|
/// `virtual bus_if.mp vif` (IEEE 1800 §25.4/§25.9). `unit` is the
|
|
/// interface half, which [`Binder::bind_data_type`] binds beside this as
|
|
/// an ordinary [`Target::Type`]; the tail is a *member* of it, looked up
|
|
/// in the interface's own scope when this file declares it and handed to
|
|
/// the workspace as `unit::name` when it does not. A tail an interface
|
|
/// this file declares whole does not bind records nothing, on the same
|
|
/// rule [`Target::MemberOf`] follows.
|
|
TypeMember { unit: 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<String> },
|
|
/// The `x` of `obj.randomize() with { x < 5; }` — an unqualified name in
|
|
/// an inline constraint block (IEEE 1800 §18.7). It is a member of `obj`
|
|
/// **first**, on exactly the terms [`Target::MemberOf`] chases one, and
|
|
/// the scope the block is *written* in second, which is where §18.7 says
|
|
/// the name resolves next. The fallback is only taken when the object's
|
|
/// own class settles the miss — a candidate for another file is left
|
|
/// alone, because it may still be the member.
|
|
InlineConstraint { head: String, mids: Vec<String> },
|
|
/// A bare name in the **expression** half of a `bind` directive's
|
|
/// connection: `bind top chk u (.x(sig));`. The connection is elaborated
|
|
/// inside the *target* scope (IEEE 1800 §23.11), so `target`'s own scope
|
|
/// answers first and the scope the directive is written in second — the
|
|
/// [`Target::InlineConstraint`] shape, with the same refusal to guess.
|
|
BindScope { target: String },
|
|
/// A **hierarchical path** written in the expression half of a `bind`
|
|
/// directive's connection: `bind aes chk u (.s(u_core.u_prng.seed_en));`.
|
|
/// The spine is rooted in the target's scope exactly as a bare name is, so
|
|
/// `head` is looked up there (and not in the scope the directive is
|
|
/// written in, which is a bind module declaring nothing at all) and each
|
|
/// of `mids` walks one link further — the [`Target::MemberOf`] walk, with
|
|
/// its start moved from the writing scope to the target's.
|
|
BindMember { target: String, head: String, mids: Vec<String> },
|
|
/// The **head** of a dotted path — the `tb` of `tb.dut.sig`: looked up
|
|
/// exactly like [`Target::Lexical`], but a miss is a top-level module's
|
|
/// name (IEEE 1800 §23.6: a top-level module name is the root of a
|
|
/// hierarchical name), so it is handed to the workspace's unit table as
|
|
/// [`Target::Module`] hands an instantiation's type. A local of the name
|
|
/// still wins. `docs/features/top-rooted-paths/README.md`.
|
|
PathHead,
|
|
/// 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),
|
|
/// `constraint cls::c { ... }` — the constraint sibling, held for the
|
|
/// same reason and finished through the same stand-in scope.
|
|
Constraint(&'a ConstraintDecl, 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>,
|
|
/// Every name a scope bound a second time, in the order they were
|
|
/// written. Purely a record — see [`Duplicate`].
|
|
pub(crate) duplicates: Vec<Duplicate>,
|
|
deferred: Vec<Deferred<'a>>,
|
|
/// While a `randomize() with { ... }` block is being bound: the head of
|
|
/// the object being randomized, so a bare name inside the block is
|
|
/// recorded as a member of it. See [`Binder::bind_with_constraint`].
|
|
with_head: Option<(String, Vec<String>)>,
|
|
/// While a `bind` directive's connections are being bound: the target
|
|
/// scope they are elaborated in, so a bare name in a connection's value
|
|
/// is looked up there first. `None` for a hierarchical instance path,
|
|
/// which this crate does not resolve. See [`Binder::bind_bind`].
|
|
bind_target: Option<String>,
|
|
}
|
|
|
|
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(),
|
|
macro_items: false,
|
|
};
|
|
Binder {
|
|
src,
|
|
scopes: vec![file],
|
|
symbols: Vec::new(),
|
|
pending: Vec::new(),
|
|
duplicates: Vec::new(),
|
|
deferred: Vec::new(),
|
|
with_head: None,
|
|
bind_target: None,
|
|
}
|
|
}
|
|
|
|
pub(crate) fn file_scope(&self) -> ScopeId {
|
|
ScopeId(0)
|
|
}
|
|
|
|
/// Record that an unexpanded macro invocation stands in `scope` where a
|
|
/// declaration could stand — an item, a statement or block item, a port —
|
|
/// so it may declare names this crate never sees. A path head missing
|
|
/// from `scope`, or from a scope inside it, is then not proven a top
|
|
/// module (`resolve/root.rs`, top-rooted-paths QA F4 and R1).
|
|
pub(super) fn mark_macro_declarations(&mut self, scope: ScopeId) {
|
|
if let Some(s) = self.scopes.get_mut(scope.0 as usize) {
|
|
s.macro_items = true;
|
|
}
|
|
}
|
|
|
|
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(),
|
|
macro_items: false,
|
|
});
|
|
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 let Some(&first) = self.scopes[scope.0 as usize].names.get(name) {
|
|
self.duplicates.push(Duplicate {
|
|
name: name.to_string(),
|
|
name_span,
|
|
decl_span,
|
|
kind,
|
|
first,
|
|
scope,
|
|
});
|
|
// A redeclaration names the first declaration — unless exactly one
|
|
// of the two is a block label. Two arms of one generate `if`
|
|
// carrying one label are one label; a label spelled like a net of
|
|
// the same scope is a collision (`duplicate-declaration`), and
|
|
// counting it as a *use* of the net would call the net read.
|
|
let first_is_block = self.symbols[first.0 as usize].kind == SymbolKind::Block;
|
|
if first_is_block == (kind == SymbolKind::Block) {
|
|
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<SymbolId> {
|
|
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;
|
|
}
|
|
// Inside `obj.randomize() with { ... }` a bare name is a member of
|
|
// `obj` before it is anything else (IEEE 1800 §18.7), so the one
|
|
// funnel every use goes through redirects it there. A name written
|
|
// with a head of its own already carries the right target and is left
|
|
// alone.
|
|
let target = match (&self.with_head, &self.bind_target, &target) {
|
|
(Some((head, mids)), _, Target::Lexical | Target::PathHead) => {
|
|
Target::InlineConstraint { head: head.clone(), mids: mids.clone() }
|
|
}
|
|
// Same funnel, same rule, for a `bind`'s connection expressions:
|
|
// a bare name there is the target scope's before it is anything
|
|
// else. A name written with a head of its own already carries the
|
|
// right target and is left alone.
|
|
(None, Some(scope), Target::Lexical | Target::PathHead) => {
|
|
Target::BindScope { target: scope.clone() }
|
|
}
|
|
// And the same rule for a hierarchical path in one: its head is a
|
|
// name in the target's scope, so the whole spine is rooted there
|
|
// rather than in the scope the directive is written in.
|
|
(None, Some(scope), Target::MemberOf { head, mids }) => {
|
|
Target::BindMember { target: scope.clone(), head: head.clone(), mids: mids.clone() }
|
|
}
|
|
_ => target,
|
|
};
|
|
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<TextRange>,
|
|
) {
|
|
// `None` when the declaration was a redeclaration and bound no symbol
|
|
// of its own; the label is then left unrecorded.
|
|
let owner = self.scopes[body.0 as usize].owner;
|
|
self.record_end_label(scope, owner, label, span);
|
|
}
|
|
|
|
/// [`Self::use_end_label`] for a block (`begin`/`fork`, a generate
|
|
/// block), whose own opening label is `opening` — the `begin : lbl` name
|
|
/// or the `lbl:` prefix. An unowned block may still close with its opening
|
|
/// label: the second arm of a generate `if`/`case` carrying the first's
|
|
/// label (IEEE 1800 §27.5), whose opening label is already a use of the
|
|
/// first declaration, and the prefix form, which declares a label but no
|
|
/// owned scope. That closing label is a use of the first same-scope
|
|
/// **block** of the name, or a rename rewrites one of the pair and leaves
|
|
/// `end : old` closing `begin : new`. A closing label that does not spell
|
|
/// the opening one records nothing (review L-1).
|
|
pub(super) fn use_block_end_label(
|
|
&mut self,
|
|
scope: ScopeId,
|
|
body: ScopeId,
|
|
opening: Option<&str>,
|
|
label: Option<&String>,
|
|
span: Option<TextRange>,
|
|
) {
|
|
let owner = self.scopes[body.0 as usize].owner.or_else(|| {
|
|
let label = label.filter(|l| opening == Some(l.as_str()))?;
|
|
let first = *self.scopes[scope.0 as usize].names.get(label)?;
|
|
(self.symbols[first.0 as usize].kind == SymbolKind::Block).then_some(first)
|
|
});
|
|
self.record_end_label(scope, owner, label, span);
|
|
}
|
|
|
|
/// Records an end label as a use of `owner` when it spells its name.
|
|
fn record_end_label(
|
|
&mut self,
|
|
scope: ScopeId,
|
|
owner: Option<SymbolId>,
|
|
label: Option<&String>,
|
|
span: Option<TextRange>,
|
|
) {
|
|
let (Some(label), Some(span), Some(sym)) = (label, span, 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)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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<String> {
|
|
let name = ty.name.split_once('.').map_or(ty.name.as_str(), |(iface, _)| iface);
|
|
(!name.is_empty() && !is_keyword(name)).then(|| name.to_string())
|
|
}
|