Files
lucisv/crates/vlog_semantic/src/workspace/external.rs
T
lucioandClaude Fable 5 b57ae35be4 Decomposition, lane D: vlog_semantic's bind.rs and workspace.rs, vlog_refactor's ports.rs and rename.rs become modules, a pure move
TODO section 28, lane D (the file-size rule in CLAUDE.md).
bind.rs (1 718 production lines) becomes bind/{mod, item, decl, class,
cover, stmt, sva, expr}.rs; workspace.rs (1 111) becomes workspace/
{mod, index, update, record, external}.rs with facts.rs and
FACTS_FORMAT untouched; ports.rs (1 391) becomes ports/{mod, find, add,
remove, propagate, list}.rs, one file per refactoring; rename.rs (760)
becomes rename/{mod, scope, warnings, tests}.rs. No function split, no
file over 600 production lines (largest add.rs at 432), every public
path unchanged (crate-root doc pages identical; only private-module
pages relocated). Carved by a range manifest that had to tile the
original byte for byte. Proof: per-binary test counts identical
(vlog_semantic 345 / 17, vlog_refactor 206 / 5, workspace 3 215 / 48),
corpus --stdout byte-identical, and the lucisv check finding lists
byte-identical between this build and the base over the corpus and the
opentitan hw tree - done by the dev and redone from scratch by QA.

docs/features/decomposition-semantic/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 21:55:55 -07:00

302 lines
13 KiB
Rust

//! The overlay: [`resolve_external`] finishes one file's external candidates
//! against the index, and [`ExternalResolutions`] holds the answers beside
//! that file's `Semantics`. The walks it is made of — a member lookup up the
//! `extends` chain, the chain itself, a `MemberSite::Unit` path folded to one
//! unit — are the same functions `index` lists members with, so a completion
//! list and a lookup cannot disagree.
use std::collections::HashMap;
use crate::model::{ReferenceId, Resolution, Symbol, SymbolKind};
use crate::Semantics;
use super::{Def, WorkspaceIndex};
/// What the workspace layer made of one external-candidate reference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExternalTarget {
/// Exactly one workspace declaration answers it.
Resolved(Def),
/// Several files declare the name; they are listed in disambiguation
/// order (by file path), so a caller that must pick one picks the first.
Ambiguous(Vec<Def>),
/// Nothing in the workspace declares it — the package or module lives
/// outside the indexed files.
StillUnresolved,
}
impl ExternalTarget {
/// Every declaration this reference could name, in disambiguation order.
pub fn defs(&self) -> &[Def] {
match self {
ExternalTarget::Resolved(def) => std::slice::from_ref(def),
ExternalTarget::Ambiguous(defs) => defs,
ExternalTarget::StillUnresolved => &[],
}
}
/// The declaration to jump to: the only one, or the first of several.
pub fn best(&self) -> Option<&Def> {
self.defs().first()
}
}
/// The workspace layer's answers for one file, keyed by reference id.
///
/// Kept beside the file's [`Semantics`] rather than folded into it: a
/// `Semantics` describes one file and stays true while the workspace churns,
/// and an overlay is cheap to throw away and rebuild when it does.
#[derive(Debug, Clone, Default)]
pub struct ExternalResolutions {
targets: HashMap<ReferenceId, ExternalTarget>,
}
/// Where a definition lives, once both layers have had their say.
#[derive(Debug, Clone)]
pub enum Definition<'a> {
/// Declared in the file the [`Semantics`] came from.
Local(&'a Symbol),
/// Declared in other workspace files, in disambiguation order.
External(&'a [Def]),
}
/// Finish one file's external candidates against the workspace index.
///
/// `sem` is not modified: the answers come back as an overlay the caller
/// composes with it (see [`ExternalResolutions::definition_of`]).
///
/// An [`Resolution::InheritedCandidate`] is not an external candidate and does
/// not become one: its base class is the single-file layer's answer and stays
/// the answer. But its paths are real — the imports the lexical walk collected
/// and the use's own name — so they are tried first, and when they say nothing
/// the **base itself is chased** through the workspace's member tables and up
/// its own `extends` chain ([`chase_inherited`], topo §2.9-9). An entry is
/// recorded **only when one of the two lands on a declaration**. A name the
/// index cannot answer is left exactly as it was, absent from the overlay,
/// which is what keeps "the overlay holds what the workspace was asked to
/// finish" true.
pub fn resolve_external(sem: &Semantics, index: &WorkspaceIndex) -> ExternalResolutions {
let mut targets = HashMap::new();
for (i, reference) in sem.references().iter().enumerate() {
let target = match &reference.resolution {
Resolution::ExternalCandidate { paths } => follow_paths(index, &reference.name, paths),
Resolution::InheritedCandidate { base, paths } => {
match resolve_fact(index, &reference.name, Some(base), paths) {
ExternalTarget::StillUnresolved => continue,
answered => answered,
}
}
_ => continue,
};
targets.insert(ReferenceId(i as u32), target);
}
ExternalResolutions { targets }
}
/// One recorded use against the index: its paths first, in the order
/// `analyze` wrote them, then — for an inherited-member miss — the base class
/// it was recorded against, chased upward through the member tables.
///
/// The **one** function both layers ask, so the overlay (hover, definition)
/// and the index's own reference postings (cross-file find-references, and the
/// rename that fans out from them) cannot name different declarations for one
/// use.
pub(super) fn resolve_fact(
index: &WorkspaceIndex,
name: &str,
base: Option<&str>,
paths: &[String],
) -> ExternalTarget {
match follow_paths(index, name, paths) {
ExternalTarget::StillUnresolved => match base {
Some(base) => target(member_chain(index, last_segment(base), name)),
None => ExternalTarget::StillUnresolved,
},
answered => answered,
}
}
/// `name` in `unit`'s member table, else in the member table of what `unit`
/// extends, and so on upward — because **a class's member table is incomplete
/// without its bases**, and every caller that asks a unit for a member wants
/// the inherited ones too. A unit that extends nothing (every package, every
/// module) is one map lookup, exactly as before.
///
/// Map reads only — [`WorkspaceIndex::member`] and
/// [`WorkspaceIndex::base_of`], both `BTreeMap`s — so a hover pays a handful
/// of comparisons and no file is read. The walk is bounded by the visited set
/// as well as by the workspace: `class a extends b; class b extends a;`
/// terminates, and so does a chain that meets itself further up.
pub(super) fn member_chain<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str) -> &'i [Def] {
let found = index.member(unit, name);
if !found.is_empty() {
return found;
}
for hop in base_chain(index, unit) {
let found = index.member(hop, name);
if !found.is_empty() {
return found;
}
}
&[]
}
/// **The hops [`member_chain`] takes past `unit` itself**, with the lookup
/// left to the caller: what `unit` extends, then what *that* extends, and so
/// on upward.
///
/// Split out so that listing a unit's members
/// ([`WorkspaceIndex::members_of_chain`]) and resolving one of them walk the
/// same units in the same order — a second spelling of the chain would
/// eventually offer a name the lookup does not find, or miss one it does.
/// `unit` is left out of the returned list because it is the caller's own
/// string and need not outlive the index; every caller searches it first.
///
/// The hop is what the unit extends, else what it is an alias *of*: a
/// file-scope `typedef c1 my_t;` in one file is how another file's
/// `my_t h;` reaches `c1`'s members, and it is the same one-name hop. Map
/// reads only, and bounded by the visited set as well as by the workspace, so
/// `class a extends b; class b extends a;` terminates. Nothing is allocated
/// for the overwhelmingly common unit that extends nothing.
pub(super) fn base_chain<'i>(index: &'i WorkspaceIndex, unit: &str) -> Vec<&'i str> {
let hop =
|from: &str| index.base_of(from).or_else(|| aliased_unit(index, from)).map(last_segment);
let mut out: Vec<&'i str> = Vec::new();
let mut current = hop(unit);
while let Some(next) = current {
if next == unit || out.contains(&next) {
break;
}
out.push(next);
current = hop(next);
}
out
}
/// A [`crate::MemberSite::Unit`] path folded down to the one unit its members
/// live in: the first segment, then one [`WorkspaceIndex::member_unit`] hop
/// per segment after it.
///
/// The same fold [`follow_one`] runs before its own lookup — shared, so a
/// list and a lookup of the same path cannot land in different units.
pub(super) fn fold_path(index: &WorkspaceIndex, path: &str) -> Option<String> {
let mut segments = path.split("::");
let mut unit = segments.next()?.to_string();
for segment in segments {
unit = index.member_unit(&unit, segment)?;
}
Some(unit)
}
/// The type a file-scope `typedef` names, when the workspace declares the name
/// exactly once and as a typedef. Two declarations of the name are two
/// answers, and this layer picks between candidates nowhere else either.
fn aliased_unit<'i>(index: &'i WorkspaceIndex, unit: &str) -> Option<&'i str> {
match index.units(unit) {
[def] if def.kind == SymbolKind::Typedef => def.type_name.as_deref(),
_ => None,
}
}
/// What one table lookup means: nothing, one declaration, or several equally
/// plausible ones.
fn target(defs: &[Def]) -> ExternalTarget {
match defs {
[] => ExternalTarget::StillUnresolved,
[def] => ExternalTarget::Resolved(def.clone()),
defs => ExternalTarget::Ambiguous(defs.to_vec()),
}
}
/// The last `::` segment of a possibly-qualified path — the name the member
/// and inheritance tables are keyed by.
pub(super) fn last_segment(path: &str) -> &str {
path.rsplit("::").next().unwrap_or(path)
}
/// Try the recorded paths in the order `analyze` wrote them — which is the
/// order the imports are written in — and take the first that has an answer.
fn follow_paths(index: &WorkspaceIndex, name: &str, paths: &[String]) -> ExternalTarget {
for path in paths {
match target(follow_one(index, name, path)) {
ExternalTarget::StillUnresolved => continue,
answered => return answered,
}
}
ExternalTarget::StillUnresolved
}
/// One recorded path against the index. `p::*` and `p::x` both mean "the name
/// this use spells, inside `p`". A bare path is the unit itself when the use
/// spells the unit's name (an instantiated module, an imported package), and
/// otherwise a member of it (the `.port` of a connection to that module, the
/// member of a class-typed handle).
///
/// A path of **more than two** segments is a member chain: `pkt_t::hdr::addr`
/// means "`addr` in the type of `hdr` in `pkt_t`", so every segment between
/// the first and the last is one [`WorkspaceIndex::member_unit`] hop before
/// the final lookup — [`fold_path`]'s job, shared with the list side. A
/// two-segment path takes no hop at all and is exactly what it was.
///
/// Every member lookup goes through [`member_chain`], so a unit that extends
/// another answers with its inherited members too — which is what makes
/// `handle.member` and `this.member` reach a base class in a third file, and
/// what keeps the overlay and the index's own reference postings (which run
/// through this same function) from disagreeing about what a use names.
fn follow_one<'i>(index: &'i WorkspaceIndex, name: &str, path: &str) -> &'i [Def] {
let mut segments: Vec<&str> = path.split("::").collect();
if segments.is_empty() {
return &[];
}
if segments.len() < 2 {
return if path == name { index.units(name) } else { member_chain(index, path, name) };
}
// The last segment is the use's own name, which `name` already carries
// (and which a `p::*` import spells as a wildcard); the ones before it are
// the hops.
segments.pop();
let Some(unit) = fold_path(index, &segments.join("::")) else {
return &[];
};
member_chain(index, &unit, name)
}
impl ExternalResolutions {
/// The answer for one reference, or `None` if it was not an external
/// candidate.
pub fn get(&self, id: ReferenceId) -> Option<&ExternalTarget> {
self.targets.get(&id)
}
/// Every answer, in reference order.
pub fn iter(&self) -> impl Iterator<Item = (ReferenceId, &ExternalTarget)> {
let mut ids: Vec<ReferenceId> = self.targets.keys().copied().collect();
ids.sort();
ids.into_iter().filter_map(|id| self.targets.get(&id).map(|t| (id, t)))
}
/// How many of the references handed to the workspace layer it answered,
/// out of how many it was handed — every external candidate, plus the
/// inherited candidates it had something to say about.
pub fn counts(&self) -> (usize, usize) {
let answered = self.targets.values().filter(|t| !t.defs().is_empty()).count();
(answered, self.targets.len())
}
/// Go-to-definition across both layers: the in-file declaration when
/// there is one, else the workspace declaration, else the declaration the
/// cursor is sitting on itself.
pub fn definition_of<'a>(&'a self, sem: &'a Semantics, offset: u32) -> Option<Definition<'a>> {
if let Some(id) = sem.reference_id_at(offset) {
if let Some(symbol) = sem.reference(id).and_then(|r| r.resolved()) {
return sem.symbol(symbol).map(Definition::Local);
}
match self.targets.get(&id).map(ExternalTarget::defs) {
Some([]) | None => {}
Some(defs) => return Some(Definition::External(defs)),
}
}
sem.symbol_at(offset).and_then(|id| sem.symbol(id)).map(Definition::Local)
}
}