Files
lucisv/crates/vlog_semantic/src/resolve.rs
T
lucioandClaude Opus 5.5 7794d3938b TODO §65.1: rename and references through a generate block label; rename warnings and mentions scoped to the renamed declaration
A path segment naming a block (bare, indexed, nested, cross-file) is now a
reference to its label: vlog_semantic declares a `for` block's label in the
enclosing scope, makes `generate … endgenerate` no scope, gives a block a
member scope, walks an index in a path, and files blocks on a module's
hierarchical surface under `module.label` (FACTS_FORMAT 21). The LSP, CLI
and MCP rename/references get it through the engine; lucisv-mcp's `block`
refusal is lifted. No verifier normalization (attacks in
check/qa_block_paths.rs, qa_block_attacks.rs).

Reworks after QA: unresolved path segments warned in every file of the set;
sibling-arm members warned; a label beside a net is a duplicate-declaration;
function-local block keys never collide; file names path-qualified when base
names collide; rename warnings and lucisv-mcp mentions scoped to the
declaration's home set (rename/home.rs, scoped.rs), falling back to unscoped
on any doubt. TODO §65.4 and §65.6 filed.

docs/features/generate-label-rename. Workspace lib/bins/tests: 79 suites,
5 064 passed, 0 failed, 51 ignored (guard exit 0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:01:23 -07:00

946 lines
41 KiB
Rust

//! Pass two: turn every pending use into a [`Resolution`].
//!
//! Everything is bound before anything is resolved, so a name used before it
//! is declared resolves exactly like one used after — which is what Verilog
//! requires at module scope and what an editor needs mid-edit.
use crate::bind::{Pending, Target};
use crate::model::{MemberSite, Resolution, Scope, ScopeId, Surface, Symbol, SymbolId, SymbolKind};
/// Resolve one pending use against the finished scope tree.
///
/// `None` means **record no reference at all**: the targets that can arrive
/// here with nothing to say are [`Target::MemberOf`] (the tail of `a.b`),
/// [`Target::InScope`] (a modport or clocking name) and [`Target::TypeMember`]
/// (the `mp` of `bus_if.mp`) — each answered only when this crate can say
/// something honest about it. Every other target always produces a resolution,
/// `NotFound` included, exactly as it did before.
pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Option<Resolution> {
Some(match &p.target {
// An end label names the construct it closes; the binder already knew
// which symbol that is, so there is nothing to look up.
Target::Declaration(id) => Resolution::Resolved(*id),
Target::Lexical => lexical(scopes, p.scope, &p.name, false),
Target::Type => lexical(scopes, p.scope, &p.name, true),
Target::Package => named_at_file_scope(scopes, symbols, &p.name, is_package),
// An interface is instantiated, connected and hierarchically named
// exactly as a module is, so both kinds answer here.
Target::Module => named_at_file_scope(scopes, symbols, &p.name, is_instantiable),
Target::Unit => unit(scopes, symbols, p.scope, &p.name),
Target::UnitMember(unit) => unit_member(scopes, symbols, p.scope, unit, &p.name),
Target::Port(module) => match owning_scope(scopes, symbols, module, is_instantiable) {
Some(scope) => match scopes[scope.0 as usize].lookup_local(&p.name) {
Some(id) => Resolution::Resolved(id),
None => Resolution::NotFound,
},
// The port list lives in whatever file declares the module.
None => Resolution::ExternalCandidate {
paths: vec![module.clone()],
surface: Surface::Connection,
},
},
Target::InScope => return in_scope(scopes, p.scope, &p.name),
Target::TypeMember { unit } => return type_member(scopes, symbols, p.scope, unit, &p.name),
Target::MemberOf { head, mids } => {
return member_of(scopes, symbols, p.scope, head, mids, &p.name)
}
Target::InlineConstraint { head, mids } => {
let found = member_of(scopes, symbols, p.scope, head, mids, &p.name);
// A miss the object's own class settles — nothing there, and
// nothing anywhere else could be — falls back to the scope the
// block is written in. A candidate for another file is left
// alone: it may still be the member, and guessing the writing
// scope over it would be the wrong answer this crate refuses to
// give.
if matches!(found, None | Some(Resolution::NotFound)) {
let lex = lexical(scopes, p.scope, &p.name, false);
if matches!(lex, Resolution::Resolved(_)) {
return Some(lex);
}
}
return found;
}
Target::BindScope { target } => {
let found = in_bind_target(scopes, symbols, target, &p.name);
// The `Target::InlineConstraint` shape: the construct's own scope
// settles the question first, and only a miss there falls back to
// the scope the directive is *written* in — where a package
// constant or a testbench signal named in a connection really
// does resolve.
if found.is_none() {
let lex = lexical(scopes, p.scope, &p.name, false);
if matches!(lex, Resolution::Resolved(_)) {
return Some(lex);
}
}
return found;
}
Target::BindMember { target, head, mids } => {
return bind_member(scopes, symbols, target, head, mids, &p.name)
}
Target::ThisMember => this_member(scopes, symbols, p.scope, &p.name),
Target::SuperMember => super_member(scopes, p.scope),
})
}
/// A name written in the expression half of a `bind`'s connection, looked up
/// in the **target** scope (IEEE 1800 §23.11).
///
/// The target's own declaration when this file holds it — and a miss there is
/// `None`, never `NotFound`: a module opens a scope per generate block, so a
/// connection may legitimately name something the module's *own* scope does
/// not hold, and "absent from this scope" is not "absent". The target
/// declared somewhere else is the same question a hierarchical tail asks of
/// the workspace — "is `name` a member of this module?" — in the
/// `unit::name` path spelling `follow_one` reads.
///
/// The surface is the **hierarchical** one (IEEE 1800 §23.6): a bind's
/// connection may name any of the target's declarations, its internal nets
/// and variables included, which is exactly what `bind aes chk u
/// (.req(entropy_masking_req))` does and what the connection surface — ports
/// and parameters only — cannot answer. Asking the narrow surface is what
/// made such a connection resolve to nothing, and a `name`-less path is what
/// kept the miss silent: the warning scan names the unit a candidate was
/// searched in by splitting the path at its `::`.
fn in_bind_target(
scopes: &[Scope],
symbols: &[Symbol],
target: &str,
name: &str,
) -> Option<Resolution> {
match owning_scope(scopes, symbols, target, is_instantiable) {
Some(scope) => scopes.get(scope.0 as usize)?.lookup_local(name).map(Resolution::Resolved),
None => Some(Resolution::ExternalCandidate {
paths: vec![format!("{target}::{name}")],
surface: Surface::Hierarchical,
}),
}
}
/// A hierarchical path written in a `bind`'s connection, rooted where the
/// directive elaborates rather than where it is written.
///
/// `bind aes chk u (.s(u_aes_core.u_aes_prng_clearing.seed_en))` is
/// [`member_of`]'s walk with one substitution: the head starts in `aes`'s
/// scope instead of the writing scope's lexical chain. So `head` is simply
/// one more link of the spine, and the target is where the spine begins — its
/// own scope when this file declares the target, and otherwise the unit the
/// workspace answers hierarchical members of.
///
/// `None` — no reference at all — wherever [`member_of`] would record none:
/// a link this file declares as something with no members to search, or a
/// name genuinely absent from a scope this file holds whole.
fn bind_member(
scopes: &[Scope],
symbols: &[Symbol],
target: &str,
head: &str,
mids: &[String],
name: &str,
) -> Option<Resolution> {
let mut here = match owning_scope(scopes, symbols, target, is_instantiable) {
Some(scope) => MemberSite::Scope(scope),
None => MemberSite::Unit { path: target.to_string(), surface: Surface::Hierarchical },
};
for link in std::iter::once(head).chain(mids.iter().map(String::as_str)) {
here = descend(scopes, symbols, here, link)?;
}
// Never the `InheritedCandidate` shape: that is a class's business, and
// the head of this spine is a place in the design hierarchy.
member_at(scopes, symbols, here, name, false)
}
/// A name looked up **only** in the scope it is written in, never outward: a
/// modport's port list and a clocking block's signal list, both of which name
/// members of the interface (or module) they are written in and nothing else.
///
/// `None` — no reference recorded at all — when that scope does not bind the
/// name. The construct is written here whole, so no other file can supply the
/// name; and walking outward to find *something* is exactly the wrong answer
/// this crate refuses to give, because a file-scope `other_if` is not the
/// signal `modport mp (input other_if)` was meant to name.
fn in_scope(scopes: &[Scope], scope: ScopeId, name: &str) -> Option<Resolution> {
scopes.get(scope.0 as usize)?.lookup_local(name).map(Resolution::Resolved)
}
/// The `mp` of a glued `bus_if.mp` type name: a member of the *type*, looked
/// up on exactly the terms [`member_of`]'s last link is.
///
/// The interface's scope when this file declares it — a hit is the modport's
/// declaration, a miss is nothing at all, because this file has answered what
/// `bus_if` is and it holds no such modport. A name this file declares as
/// something without members ([`TypeHere::NotAUnit`]) is nothing either. Only a
/// name **nothing here declares** reaches the workspace, as the one composed
/// path `follow_one` reads back as `member(bus_if, mp)`.
fn type_member(
scopes: &[Scope],
symbols: &[Symbol],
from: ScopeId,
unit: &str,
name: &str,
) -> Option<Resolution> {
match type_here(scopes, symbols, from, unit) {
TypeHere::Scope(scope) => {
scopes.get(scope.0 as usize)?.lookup_local(name).map(Resolution::Resolved)
}
TypeHere::NotAUnit => None,
TypeHere::Absent => Some(Resolution::ExternalCandidate {
paths: vec![format!("{}::{name}", last_segment(unit))],
surface: Surface::Connection,
}),
}
}
/// The `member` of `head.mids….member`: the head is resolved on the ordinary
/// lexical chain, its **declared type** is resolved on the same chain, each
/// name in `mids` is looked up in that type's scope (and up its `extends`
/// chain) to give the next type, and the tail is looked up in the last one.
///
/// `None` — no reference recorded at all — whenever this crate has nothing to
/// say, which is the shape every pre-2026-09-01 hierarchical name had: a head
/// nothing in this file declares, a head that is neither typed nor a unit a
/// hierarchical name may start at (a `logic [3:0]`, a genvar, a
/// built-in), a type **this file declares** as something with no members to
/// search (a struct or enum typedef — see [`TypeHere::NotAUnit`]), or a
/// member genuinely absent from a class this file declares whole. Recording a
/// `NotFound` for those would move `reference_at` under every `a.b` in the
/// corpus to answer "a name that resolves to nothing", which is a different
/// claim than "not modelled". **A link that cannot be resolved honestly stops
/// the chain**: nothing is recorded for it or for anything after it.
///
/// Only a type name **nothing in this file declares** reaches the workspace.
/// The distinction is the whole of QA finding 1 (2026-09-01): a `bus_t` this
/// file declares as a struct typedef must not be asked about in a workspace
/// where some unrelated file declares a *class* `bus_t`, or `s.field` lands on
/// a stranger's property — a wrong answer, where recording nothing is merely a
/// missing one.
fn member_of(
scopes: &[Scope],
symbols: &[Symbol],
from: ScopeId,
head: &str,
mids: &[String],
name: &str,
) -> Option<Resolution> {
let site = member_site(scopes, symbols, from, head, mids)?;
member_at(scopes, symbols, site, name, mids.is_empty())
}
/// The **tail** of a spine: `name` looked up in the site the links before it
/// landed on.
///
/// `direct` says whether this is a plain `head.member` — the one shape that
/// may report an inherited candidate, because for a longer chain the base is
/// the owner of an earlier link, not of this name, and claiming it here would
/// send the overlay's inheritance chase after the wrong class.
///
/// Shared with [`bind_member`], which walks the same links from a different
/// start: two spellings of this lookup would eventually answer one name two
/// ways.
fn member_at(
scopes: &[Scope],
symbols: &[Symbol],
site: MemberSite,
name: &str,
direct: bool,
) -> Option<Resolution> {
match site {
MemberSite::Scope(scope) => match member_in_chain(scopes, symbols, scope, name) {
Ok(id) => Some(Resolution::Resolved(id)),
// The chain leaves this file: the base, plus the path the
// workspace's member table answers it by.
Err(Some(base)) if direct => Some(Resolution::InheritedCandidate {
paths: vec![format!("{}::{name}", last_segment(&base))],
base,
}),
Err(Some(base)) => Some(Resolution::ExternalCandidate {
paths: vec![format!("{}::{name}", last_segment(&base))],
surface: Surface::Connection,
}),
// A class this file declares whole, with no such member: nothing
// to say that `NotFound` would not overstate.
Err(None) => None,
},
// A type this file does not declare: the workspace's member table is
// the only layer that can say. The last `::` segment names the unit,
// the spelling `follow_one` turns back into `member(unit, name)`.
MemberSite::Unit { path, surface } => {
Some(Resolution::ExternalCandidate { paths: vec![format!("{path}::{name}")], surface })
}
}
}
/// **The prefix of [`member_of`]**, and the whole of what a completion list
/// after a `.` needs: where `head.mids….` puts the cursor, with no tail
/// looked up yet.
///
/// One walk, called by both — `member_of` is this function plus one lookup in
/// what it returns. Every stopping condition is therefore shared: a head
/// nothing here declares, a head with no type this crate can look members up
/// in, a mid that leaves the chain unfinishable. `None` means *nothing to
/// say*, which for a completion list means no popup and for a resolution
/// means no reference recorded.
///
/// `this` and `super` are heads here even though [`Target::MemberOf`] never
/// carries them (the binder sends those to [`this_member`]/[`super_member`],
/// which resolve one member and stop): a `this.` popup is asking the same
/// question about the same class, and answering it from the same walk is what
/// keeps the two from drifting. `super` names the first hop of the `extends`
/// chain — the base's scope when this file declares it, the base's *name*
/// when it does not, which is the unit the overlay's own chase starts at.
pub(crate) fn member_site(
scopes: &[Scope],
symbols: &[Symbol],
from: ScopeId,
head: &str,
mids: &[String],
) -> Option<MemberSite> {
let mut here = head_site(scopes, symbols, from, head)?;
for mid in mids {
here = descend(scopes, symbols, here, mid)?;
}
Some(here)
}
/// One more link of a spine: where `here`'s member `link` puts the cursor.
///
/// Shared with [`bind_member`] for the same reason [`member_at`] is — a
/// second spelling of the hop would eventually walk somewhere the first does
/// not.
fn descend(
scopes: &[Scope],
symbols: &[Symbol],
here: MemberSite,
link: &str,
) -> Option<MemberSite> {
match here {
MemberSite::Scope(scope) => match member_in_chain(scopes, symbols, scope, link) {
Ok(id) => link_type(scopes, symbols, id),
// The chain leaves this file at a base class: everything from
// here on is one composed path for the workspace to walk.
Err(Some(base)) => Some(MemberSite::Unit {
path: format!("{}::{link}", last_segment(&base)),
surface: Surface::Connection,
}),
Err(None) => None,
},
// Already outside this file — each further name is one more segment
// of the path `follow_one` walks member by member.
MemberSite::Unit { path, surface } => {
Some(MemberSite::Unit { path: format!("{path}::{link}"), surface })
}
}
}
/// Where the *first* segment of a spine puts the cursor.
fn head_site(
scopes: &[Scope],
symbols: &[Symbol],
from: ScopeId,
head: &str,
) -> Option<MemberSite> {
match head {
// Neither is a name this crate binds, so neither goes through
// `lexical`; both are the enclosing class, one hop apart.
"this" => nearest_class(scopes, from).map(MemberSite::Scope),
"super" => {
let class = nearest_class(scopes, from)?;
let (chain, base) = extends_chain(scopes, symbols, class);
match chain.get(1) {
Some(&base_scope) => Some(MemberSite::Scope(base_scope)),
None => Some(MemberSite::Unit {
path: last_segment(&base?).to_string(),
surface: Surface::Connection,
}),
}
}
_ => {
let Resolution::Resolved(id) = lexical(scopes, from, head, false) else {
return None;
};
link_type(scopes, symbols, id)
}
}
}
/// **The prefix of [`unit_member`]**: which unit `unit::` names, without
/// looking a member up in it.
///
/// The same outward walk, with the same kind filter — a package or class
/// declared here answers with its own scope, a `typedef class c;` forward
/// declaration and a name nothing here declares answer with the workspace
/// unit, and a non-unit shadower is stepped over. A `pkg::cls` path descends
/// segment by segment afterwards, on [`type_here`]'s terms: a segment missing
/// from a container this file holds is `None`, because this file has answered
/// what the container holds.
pub(crate) fn unit_site(
scopes: &[Scope],
symbols: &[Symbol],
from: ScopeId,
path: &str,
) -> Option<MemberSite> {
let mut segments = path.split("::");
let mut here = unit_scope(scopes, symbols, from, segments.next()?);
for segment in segments {
here = match here {
MemberSite::Scope(scope) => {
let id = scopes.get(scope.0 as usize)?.lookup_local(segment)?;
MemberSite::Scope(container_scope(symbols, id)?)
}
MemberSite::Unit { path, surface } => {
MemberSite::Unit { path: format!("{path}::{segment}"), surface }
}
};
}
Some(here)
}
/// One `::` segment: the scope this file opens for it, else the workspace
/// unit of that name. Never `None` — a name nothing here declares is exactly
/// what the index is for.
fn unit_scope(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, unit: &str) -> MemberSite {
let mut current = Some(from);
while let Some(id) = current {
let scope = &scopes[id.0 as usize];
if let Some(sym) = scope.lookup_local(unit) {
match symbols[sym.0 as usize].kind {
SymbolKind::Package | SymbolKind::Class => {
if let Some(child) = symbols[sym.0 as usize].child_scope {
return MemberSite::Scope(child);
}
}
// `typedef class c;` promises the class lives elsewhere.
SymbolKind::Typedef => break,
// A non-unit shadower; keep walking outward.
_ => {}
}
}
current = scope.parent;
}
MemberSite::Unit { path: unit.to_string(), surface: Surface::Connection }
}
/// Where the members of one declaration live: its **declared type**'s scope
/// when this file declares that type, else the workspace path for it.
///
/// A declaration with no declared type at all can still be a chain's head when
/// it opens a scope a `.` may name members of — a module or an interface,
/// which is how `tb.dut.u_core.sig` reaches into `tb` (IEEE 1800 §23.6: a
/// top-level module name is the root of a hierarchical path), or a class,
/// where the answer can only ever be that very class's own member. Everything
/// else — a `logic` net, a genvar, a package — answers `None`, which stops
/// the chain. A block label has no type either, and opens its own scope the
/// way a module does.
fn link_type(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option<MemberSite> {
let symbol = symbols.get(id.0 as usize)?;
let Some(type_name) = symbol.type_name.as_deref() else {
return member_scope(scopes, symbols, id).map(MemberSite::Scope);
};
// The type name is looked up where the declaration is written, by the same
// walk the type *reference* itself took.
match type_here(scopes, symbols, symbol.scope, type_name) {
TypeHere::Scope(scope) => Some(MemberSite::Scope(scope)),
// This file says what the type is, and it is not something with
// members. No other file can override that, so nothing is recorded.
TypeHere::NotAUnit => None,
TypeHere::Absent => Some(MemberSite::Unit {
path: last_segment(type_name).to_string(),
surface: head_surface(symbol.kind),
}),
}
}
/// Which member surface a link of a spine opens: the **hierarchical** one when
/// the link is an instance, the connection one for everything else.
///
/// `u_x.sig` is a hierarchical path (IEEE 1800 §23.6) and `sig` may be any of
/// `sub`'s own declarations; `handle.field` is a member access on a type, and
/// `pkt_t` has one surface anyway. The distinction only ever matters for a
/// module — the one unit whose two surfaces differ — and it is settled here,
/// in the file that can see what the head is, because the path handed to the
/// workspace is only a spelling.
fn head_surface(kind: SymbolKind) -> Surface {
match kind {
SymbolKind::Instance => Surface::Hierarchical,
_ => Surface::Connection,
}
}
/// `name` in a class (or interface) scope this file holds, then up its
/// `extends` chain as far as this file goes.
///
/// `Ok` is the declaration; `Err(Some(base))` means the chain left this file
/// at `base`, which the workspace index chases further
/// ([`crate::WorkspaceIndex::base_of`]); `Err(None)` means the chain ended
/// here — every class on it is declared in this file and none of them binds
/// the name.
fn member_in_chain(
scopes: &[Scope],
symbols: &[Symbol],
scope: ScopeId,
name: &str,
) -> Result<SymbolId, Option<String>> {
let (chain, base) = extends_chain(scopes, symbols, scope);
for id in chain {
if let Some(found) = scopes[id.0 as usize].lookup_local(name) {
return Ok(found);
}
}
Err(base)
}
/// **The walk [`member_in_chain`] does**, with the lookup left to the caller:
/// every scope a member of `scope` may be declared in, nearest first, and the
/// base the chain left this file at (`None` when it ended here — a class
/// extending nothing, a cycle, or a chain every link of which this file
/// declares).
///
/// Split out so that a completion list of *all* the members and a resolution
/// of *one* of them cannot walk different chains: [`member_in_chain`] is this
/// function plus a `lookup_local` in each scope it names, in the same order,
/// which is the same first-hit-wins shadowing it always had.
///
/// `extends` can be written in a cycle; the visited set is what makes this
/// terminate on `class a extends b; class b extends a;`.
pub(crate) fn extends_chain(
scopes: &[Scope],
symbols: &[Symbol],
scope: ScopeId,
) -> (Vec<ScopeId>, Option<String>) {
let mut visited: Vec<ScopeId> = Vec::new();
let mut current = scope;
loop {
if visited.contains(&current) {
return (visited, None);
}
visited.push(current);
let Some(base) = &scopes[current.0 as usize].extends else {
return (visited, None);
};
match type_here(scopes, symbols, enclosing(scopes, current), base) {
TypeHere::Scope(next) => current = next,
// Whether the base is absent from this file or declared here as
// something without a member scope — a `typedef class base;`
// forward declaration is exactly that — it is the workspace's to
// finish. `extends` names a class by the grammar's own claim, so
// asking the index about it is not the guess `member_of`'s
// `NotAUnit` arm refuses to make about a data declaration's type.
TypeHere::NotAUnit | TypeHere::Absent => return (visited, Some(base.clone())),
}
}
}
/// The scope enclosing one — a class's base is resolved from *outside* it, as
/// `extends` itself is (class-semantics rule 5).
fn enclosing(scopes: &[Scope], scope: ScopeId) -> ScopeId {
scopes[scope.0 as usize].parent.unwrap_or(ScopeId(0))
}
/// What **this file** says about a type name — the three-way answer
/// `handle.member` needs, where a two-way one is a wrong answer waiting to
/// happen (QA finding 1, 2026-09-01).
enum TypeHere {
/// Declared here as something with members to look in: a class, a module,
/// or an interface — so `virtual clk_rst_if vif; vif.clk` reaches the
/// interface's signals.
Scope(ScopeId),
/// Declared here as something else — a struct, enum or alias `typedef`, a
/// parameter, a variable shadowing the name. This file has *answered* the
/// question "what is this type", and the answer is one with no members
/// this crate models (struct fields are round 2, `docs/topo.md` §2.9-13).
/// No other file can override that answer, so the workspace is never
/// asked — which is what keeps a locally-declared `bus_t` from being
/// looked up in a stranger's class of the same name.
NotAUnit,
/// Nothing in this file declares the name at all — the only case the
/// workspace's tables can honestly answer.
Absent,
}
/// Look a written type name up in this file: on the lexical chain for its
/// first segment, then descended segment by segment for `pkg::cls`.
///
/// The first segment goes through [`lexical`] itself — the same walk, the same
/// shadowing, the same import precedence the type *reference* took — so what
/// this says and what go-to-definition on the type name answers cannot
/// disagree. A qualified path then descends only through containers: a
/// package, class or module scope. A segment missing from a container this
/// file holds is [`TypeHere::NotAUnit`], not [`TypeHere::Absent`] — the
/// container is fully known here, the same reason [`unit_member`] answers a
/// missing package member with `NotFound` rather than sending it to the
/// workspace (vlog-semantic rule 6).
///
/// A name landing on a `typedef` **that aliases another type** is followed to
/// what it aliases (`typedef c1 my_t;` → `c1`), from the typedef's own scope,
/// as many hops as are written; `seen` is what makes a chain of aliases that
/// meets itself terminate. A typedef with no aliased type — a `struct`, an
/// `enum`, an alias of a built-in, a `typedef class c;` forward declaration —
/// stays [`TypeHere::NotAUnit`] exactly as it was: this file has answered what
/// the type is, and the answer has no members this crate models.
fn type_here(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, path: &str) -> TypeHere {
type_here_seen(scopes, symbols, from, path, &mut Vec::new())
}
fn type_here_seen(
scopes: &[Scope],
symbols: &[Symbol],
from: ScopeId,
path: &str,
seen: &mut Vec<SymbolId>,
) -> TypeHere {
let mut segments = path.split("::");
let Some(head) = segments.next() else {
return TypeHere::Absent;
};
let Resolution::Resolved(mut current) = lexical(scopes, from, head, false) else {
return TypeHere::Absent;
};
for segment in segments {
let Some(scope) = container_scope(symbols, current) else {
return TypeHere::NotAUnit;
};
match scopes.get(scope.0 as usize).and_then(|s| s.lookup_local(segment)) {
Some(next) => current = next,
None => return TypeHere::NotAUnit,
}
}
if let Some(scope) = member_scope(scopes, symbols, current) {
return TypeHere::Scope(scope);
}
match alias_target(symbols, current) {
Some((aliased, written_in)) if !seen.contains(&current) => {
seen.push(current);
type_here_seen(scopes, symbols, written_in, &aliased, seen)
}
_ => TypeHere::NotAUnit,
}
}
/// The type a `typedef` aliases, and the scope the alias is written in —
/// `None` for every other declaration, and for a typedef whose target names no
/// declaration at all (a `struct` or `enum` body, an alias of a built-in, a
/// forward class declaration).
fn alias_target(symbols: &[Symbol], id: SymbolId) -> Option<(String, ScopeId)> {
let symbol = symbols.get(id.0 as usize)?;
if symbol.kind != SymbolKind::Typedef {
return None;
}
Some((symbol.type_name.clone()?, symbol.scope))
}
/// The scope a symbol opens when it is a container a type path may pass
/// *through*: a package, a class or a module.
fn container_scope(symbols: &[Symbol], id: SymbolId) -> Option<ScopeId> {
let symbol = symbols.get(id.0 as usize)?;
matches!(symbol.kind, SymbolKind::Package | SymbolKind::Class)
.then_some(symbol.child_scope)
.or_else(|| symbol.kind.is_instantiable().then_some(symbol.child_scope))?
}
/// The scope a symbol opens when a `.` may name its members: a class, a
/// module, or an interface — which is what makes `vif.sig` and `u.internal`
/// reach into one — a named block, which is what `g_lane[0].lane_q` and
/// `blk.tmp` reach into (IEEE 1800 §23.6), **or** a `struct`/`union` body,
/// whoever names it. A package is a container to pass through, never a thing
/// a handle can be.
///
/// The struct half is deliberately written as "any symbol whose child scope is
/// a struct body", not "a `Typedef` whose child scope is one": the same rule
/// then serves all three ways a body gets named — the `typedef` that names it,
/// an **anonymous** aggregate's own declarator (`struct { logic a; } s;`), and
/// an **inline nested** member (`struct { struct { logic q; } ctrl; }`), where
/// no type name exists to look anything up by. `docs/features/struct-members/README.md`.
fn member_scope(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option<ScopeId> {
let symbol = symbols.get(id.0 as usize)?;
if symbol.kind == SymbolKind::Class
|| symbol.kind == SymbolKind::Covergroup
|| symbol.kind == SymbolKind::Block
|| symbol.kind.is_instantiable()
{
return symbol.child_scope;
}
let child = symbol.child_scope?;
(scopes.get(child.0 as usize)?.kind == crate::model::ScopeKind::Struct).then_some(child)
}
/// The last `::` segment of a possibly-qualified path (`pkg::cls` → `cls`) —
/// the segment the workspace's member table is keyed by.
fn last_segment(path: &str) -> &str {
path.rsplit("::").next().unwrap_or(path)
}
/// Walk the scope chain outward: names declared in a scope first, then the
/// packages that scope imports, then the enclosing scope. A miss inside a
/// class whose header says `extends` becomes an inheritance candidate — the
/// base (which this crate never chases, in this file or out of it) could
/// supply the name, and so could any import path collected on the way out.
///
/// `promote` is set for [`Target::Type`] only. A **type** name nothing here
/// binds is exactly how a file-scope `interface`, a package-less `class` or a
/// cross-file `typedef` is written (`bus_if bus;`, `my_cls h;`), so its miss
/// ends carrying the **bare name** as its last path — last, so an import that
/// could supply the name still wins — and the workspace's unit table, the only
/// layer that can say, gets asked. A [`Target::Lexical`] miss is an identifier
/// in a *value* position: a name a `` `define`` would have produced, a typo, a
/// signal declared somewhere this crate does not model. Nothing about it says
/// "file-scope declaration", so it is not swept through the unit table, where a
/// mere name collision would make `rename` rewrite an unrelated file.
fn lexical(scopes: &[Scope], from: ScopeId, name: &str, promote: bool) -> Resolution {
let mut external = Vec::new();
let mut current = Some(from);
while let Some(id) = current {
let scope = &scopes[id.0 as usize];
if let Some(sym) = scope.lookup_local(name) {
return Resolution::Resolved(sym);
}
for import in &scope.imports {
if !import.supplies(name) {
continue;
}
match import.scope {
Some(pkg) => {
if let Some(sym) = scopes[pkg.0 as usize].lookup_local(name) {
return Resolution::Resolved(sym);
}
}
// A package this file does not declare: only the workspace
// index can say whether it holds the name.
None => {
let path = import.path();
if !external.contains(&path) {
external.push(path);
}
}
}
}
current = scope.parent;
}
if promote {
external.push(name.to_string());
}
miss(scopes, from, external, false)
}
/// 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 definition. Resolved on the lexical chain, non-unit shadowers
/// skipped; imports are consulted because a class can arrive through
/// `import p::*`. A miss always leaves at least the bare name as an external
/// path, so `extends Base` reaches the workspace's unit table — and it stays
/// an `ExternalCandidate` even inside an extending class, because a base
/// class supplies members, not unit names (see [`miss`]).
fn unit(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, name: &str) -> Resolution {
let mut external = Vec::new();
let mut current = Some(from);
while let Some(id) = current {
let scope = &scopes[id.0 as usize];
if let Some(sym) = scope.lookup_local(name) {
if is_unit_kind(symbols, sym) {
return Resolution::Resolved(sym);
}
}
for import in &scope.imports {
if !import.supplies(name) {
continue;
}
match import.scope {
Some(pkg) => {
if let Some(sym) = scopes[pkg.0 as usize].lookup_local(name) {
if is_unit_kind(symbols, sym) {
return Resolution::Resolved(sym);
}
}
}
None => {
let path = import.path();
if !external.contains(&path) {
external.push(path);
}
}
}
}
current = scope.parent;
}
external.push(name.to_string());
miss(scopes, from, external, true)
}
/// The `x` of `p::x`: looked up inside the named unit's scope only, never in
/// the lexical chain. The unit itself is found lexically (a class nested in
/// an in-file package is reachable from inside that package); in-file
/// imports are not consulted here — a unit reached through one is answered
/// by the head reference, and the member honestly stays external.
fn unit_member(
scopes: &[Scope],
symbols: &[Symbol],
from: ScopeId,
unit: &str,
name: &str,
) -> Resolution {
match unit_scope(scopes, symbols, from, unit) {
MemberSite::Scope(child) => {
if let Some(found) = scopes[child.0 as usize].lookup_local(name) {
return Resolution::Resolved(found);
}
// A static member may be inherited; the base is recorded, never
// chased. Only a class scope carries an `extends`, so this is the
// old `(SymbolKind::Class, Some(base))` arm exactly. A package
// fully known locally is `NotFound`: no workspace index could
// change the answer.
match &scopes[child.0 as usize].extends {
Some(base) => {
Resolution::InheritedCandidate { base: base.clone(), paths: Vec::new() }
}
None => Resolution::NotFound,
}
}
// Nothing here declares the unit, or a `typedef class c;` promises it
// lives elsewhere: the member is the workspace's to find.
MemberSite::Unit { .. } => Resolution::ExternalCandidate {
paths: vec![format!("{unit}::{name}")],
surface: Surface::Connection,
},
}
}
/// `this.x`: the enclosing class's own scope and the classes it extends — a
/// member access cannot name a method local or an enclosing module net, but it
/// can name an inherited member, and since 2026-09-01 the `extends` chain is
/// walked as far as this file declares it (topo §2.9-9). A chain that leaves
/// the file keeps the answer it has always given — the base, no paths — which
/// the workspace overlay now chases through the member tables.
fn this_member(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, name: &str) -> Resolution {
let Some(class) = nearest_class(scopes, from) else {
return Resolution::NotFound;
};
match member_in_chain(scopes, symbols, class, name) {
Ok(id) => Resolution::Resolved(id),
Err(Some(base)) => Resolution::InheritedCandidate { base, paths: Vec::new() },
Err(None) => Resolution::NotFound,
}
}
/// `super.x`: always the base class's business — recorded against it, never
/// chased. A `super` in a class without `extends` is illegal anyway.
fn super_member(scopes: &[Scope], from: ScopeId) -> Resolution {
match nearest_class(scopes, from).and_then(|c| scopes[c.0 as usize].extends.clone()) {
Some(base) => Resolution::InheritedCandidate { base, paths: Vec::new() },
None => Resolution::NotFound,
}
}
/// How a full miss ends. `unit_lookup` is set for [`Target::Unit`], whose
/// paths always hold at least the bare name — and whose misses stay
/// `ExternalCandidate` even inside an extending class, because a base class
/// supplies *members*, not package or class names (rules 5/8 of the
/// class-semantics README; QA-found, lead-ruled). For a member miss, the
/// nearest extends-carrying enclosing class's base could supply the name
/// (the LRM even puts it ahead of the enclosing scopes this walk already
/// searched — the deliberate inexactness the same README argues), so it
/// becomes `InheritedCandidate` — which keeps its base and its paths both,
/// because either could be the answer and nothing here picks between them.
/// A miss with nothing to name at all — no import in scope, no bare name
/// because the use was not a type — is `NotFound`.
fn miss(scopes: &[Scope], from: ScopeId, external: Vec<String>, unit_lookup: bool) -> Resolution {
if unit_lookup {
return Resolution::ExternalCandidate { paths: external, surface: Surface::Connection };
}
if let Some(base) = nearest_extends(scopes, from) {
return Resolution::InheritedCandidate { base, paths: external };
}
if external.is_empty() {
Resolution::NotFound
} else {
Resolution::ExternalCandidate { paths: external, surface: Surface::Connection }
}
}
/// The innermost enclosing class scope, extends or not.
fn nearest_class(scopes: &[Scope], from: ScopeId) -> Option<ScopeId> {
let mut current = Some(from);
while let Some(id) = current {
let scope = &scopes[id.0 as usize];
if scope.kind == crate::model::ScopeKind::Class {
return Some(id);
}
current = scope.parent;
}
None
}
/// The `extends` path of the innermost enclosing class that has one.
fn nearest_extends(scopes: &[Scope], from: ScopeId) -> Option<String> {
let mut current = Some(from);
while let Some(id) = current {
let scope = &scopes[id.0 as usize];
if scope.kind == crate::model::ScopeKind::Class {
if let Some(base) = &scope.extends {
return Some(base.clone());
}
}
current = scope.parent;
}
None
}
fn is_unit_kind(symbols: &[Symbol], sym: SymbolId) -> bool {
matches!(
symbols.get(sym.0 as usize).map(|s| s.kind),
Some(SymbolKind::Package | SymbolKind::Class | SymbolKind::Typedef)
)
}
/// The kind an `import p::…` may name.
fn is_package(kind: SymbolKind) -> bool {
kind == SymbolKind::Package
}
/// The kinds an instantiation may name — a module or an interface.
pub(crate) fn is_instantiable(kind: SymbolKind) -> bool {
kind.is_instantiable()
}
fn named_at_file_scope(
scopes: &[Scope],
symbols: &[Symbol],
name: &str,
wanted: fn(SymbolKind) -> bool,
) -> Resolution {
match file_symbol(scopes, symbols, name, wanted) {
Some(id) => Resolution::Resolved(id),
None => Resolution::ExternalCandidate {
paths: vec![name.to_string()],
surface: Surface::Connection,
},
}
}
/// The scope a file-scope declaration of `name` opens, when it is one of the
/// `wanted` kinds.
///
/// `pub(crate)` since 2026-09-02 for [`crate::Semantics::instantiable_scope`],
/// which is this function with [`is_instantiable`] passed in — the very call
/// [`Target::Port`] makes. A connection list's completion and a `.port`
/// resolution therefore look in one scope, found one way.
pub(crate) fn owning_scope(
scopes: &[Scope],
symbols: &[Symbol],
name: &str,
wanted: fn(SymbolKind) -> bool,
) -> Option<ScopeId> {
let id = file_symbol(scopes, symbols, name, wanted)?;
symbols[id.0 as usize].child_scope
}
/// Modules, interfaces and packages are file-scope names, so one lookup finds
/// them.
fn file_symbol(
scopes: &[Scope],
symbols: &[Symbol],
name: &str,
wanted: fn(SymbolKind) -> bool,
) -> Option<SymbolId> {
let id = scopes.first()?.lookup_local(name)?;
wanted(symbols.get(id.0 as usize)?.kind).then_some(id)
}