DV round 1 (TODO section 15). The tail of head.member gets a reference when the head is a plain identifier whose declared type (Symbol::type_name, new) is a class or module: the member is found in that scope, else up the in-file extends chain, else the workspace's member table chases WorkspaceIndex::base_of (a subclass-to-base map rebuilt from the existing inheritance census, no new facts field) - cycle-guarded on both sides and placed in follow_one so hover, cross-file references and rename cannot disagree. this.x/super.x misses ride the same loop, delivering topo 2.9-9. An out-of-class method body (task c2::update) sees its class's members through a stand-in Class scope. FACTS_FORMAT 5 -> 6: the layout is unchanged but the reference census grew. Honesty by construction, after QA's one REWORK: a head whose type is declared in-file as anything without a member scope (typedef, alias, enum, param) records nothing - a two-state Option had stood in for the three-state TypeHere question, and a typedef named bus_t could have been answered by an unrelated class bus_t elsewhere. The fix removed exactly 438 wrong postings from the corpus with unresolved unchanged at 1256. Hover 7-143 us; opentitan tl_seq_item member 0.12 ms cold, 0.01 ms warm; store +2.85 percent. docs/features/class-member-access/README.md. Co-Authored-By: Claude Fable 5 <[email protected]>
273 lines
11 KiB
Rust
273 lines
11 KiB
Rust
//! Single-file symbol tables and reference resolution for Verilog/
|
|
//! SystemVerilog.
|
|
//!
|
|
//! This crate plays the role of `ruff_python_semantic` in ruff's architecture:
|
|
//! it takes the AST `vlog_parser` produced for **one** file and answers the
|
|
//! questions a language server asks — what is declared here, what does this
|
|
//! identifier name, where else is it used, what is the outline of this file.
|
|
//! [`analyze`] itself resolves nothing across files; a name that only another
|
|
//! file can supply is reported as [`Resolution::ExternalCandidate`]. The
|
|
//! second layer, [`WorkspaceIndex`] + [`resolve_external`], scans the whole
|
|
//! workspace and finishes those references in an overlay beside the
|
|
//! single-file tables — see `docs/features/workspace-index/README.md`.
|
|
//!
|
|
//! [`analyze`] never fails and never panics: an error-tolerant parse's
|
|
//! `Error` nodes are opaque leaves, exactly like macro invocations.
|
|
//! See `docs/features/vlog-semantic/README.md` for the resolution rules and
|
|
//! the simplifications taken.
|
|
|
|
mod bind;
|
|
pub mod classes;
|
|
mod facts;
|
|
pub mod instantiations;
|
|
mod model;
|
|
mod resolve;
|
|
mod scan;
|
|
mod workspace;
|
|
|
|
pub use facts::{record_path, FACTS_FORMAT};
|
|
pub use model::{
|
|
DocumentSymbol, Import, Reference, ReferenceId, Resolution, Scope, ScopeId, ScopeKind, Symbol,
|
|
SymbolId, SymbolKind,
|
|
};
|
|
pub use workspace::{
|
|
index_order, resolve_external, DeclLines, DeclPositions, DeclSite, Def, Definition,
|
|
DefinitionKey, ExternalResolutions, ExternalTarget, FileFacts, FileId, IndexBuilder,
|
|
IndexCounts, InheritanceEdge, InstanceOccurrence, InstantiationEdge, ReferenceSite, Utf16Pos,
|
|
Utf16Range, WorkspaceIndex, WorkspaceSymbol,
|
|
};
|
|
|
|
use std::collections::HashMap;
|
|
use vlog_parser::ast::SourceFile;
|
|
use vlog_parser::span::TextRange;
|
|
|
|
/// Everything known about one file: its scopes, its declarations and its uses.
|
|
#[derive(Debug, Clone)]
|
|
pub struct Semantics {
|
|
scopes: Vec<Scope>,
|
|
symbols: Vec<Symbol>,
|
|
references: Vec<Reference>,
|
|
/// symbol → indices into `references`, in source order.
|
|
uses: HashMap<SymbolId, Vec<usize>>,
|
|
/// Non-empty declaration-name spans, sorted by start for cursor lookup.
|
|
symbol_positions: Vec<(TextRange, SymbolId)>,
|
|
/// Non-empty reference-name spans, sorted by start for cursor lookup.
|
|
reference_positions: Vec<(TextRange, ReferenceId)>,
|
|
/// Every symbol id, sorted by the name it declares, ties in declaration
|
|
/// order — so looking a name up is a binary search rather than a walk of
|
|
/// every symbol. A side table rather than a `HashMap<String, _>` because
|
|
/// this way `Semantics` does not carry a second copy of every name it
|
|
/// already holds, and it is cloned per document.
|
|
by_name: Vec<SymbolId>,
|
|
}
|
|
|
|
/// Build the symbol table for one parsed file. `src` must be the text the
|
|
/// file was parsed from — spans index into it.
|
|
pub fn analyze(file: &SourceFile, src: &str) -> Semantics {
|
|
let mut binder = bind::Binder::new(src, file.span);
|
|
let file_scope = binder.file_scope();
|
|
binder.bind_items(&file.items, file_scope);
|
|
// Out-of-body method definitions bind into their class's scope, which is
|
|
// only guaranteed to exist once the whole file is bound.
|
|
binder.bind_deferred();
|
|
|
|
let bind::Binder { mut scopes, symbols, pending, .. } = binder;
|
|
link_imports(&mut scopes, &symbols);
|
|
|
|
let mut references = Vec::with_capacity(pending.len());
|
|
for p in &pending {
|
|
// A pending use pass two has nothing to say about is not a reference
|
|
// at all — the member tail of `a.b` where `a`'s type is not one this
|
|
// crate can look members up in (`resolve::member_of`). Every other
|
|
// target always resolves, `NotFound` included.
|
|
let Some(resolution) = resolve::resolve(&scopes, &symbols, p) else {
|
|
continue;
|
|
};
|
|
references.push(Reference {
|
|
name: p.name.clone(),
|
|
name_span: p.name_span,
|
|
scope: p.scope,
|
|
resolution,
|
|
});
|
|
}
|
|
|
|
let mut uses: HashMap<SymbolId, Vec<usize>> = HashMap::new();
|
|
for (i, r) in references.iter().enumerate() {
|
|
if let Some(id) = r.resolved() {
|
|
uses.entry(id).or_default().push(i);
|
|
}
|
|
}
|
|
let mut symbol_positions: Vec<(TextRange, SymbolId)> = symbols
|
|
.iter()
|
|
.enumerate()
|
|
.filter(|(_, symbol)| !symbol.name_span.is_empty())
|
|
.map(|(i, symbol)| (symbol.name_span, SymbolId(i as u32)))
|
|
.collect();
|
|
symbol_positions.sort_by_key(|(span, _)| (span.start, span.end));
|
|
let mut reference_positions: Vec<(TextRange, ReferenceId)> = references
|
|
.iter()
|
|
.enumerate()
|
|
.filter(|(_, reference)| !reference.name_span.is_empty())
|
|
.map(|(i, reference)| (reference.name_span, ReferenceId(i as u32)))
|
|
.collect();
|
|
reference_positions.sort_by_key(|(span, _)| (span.start, span.end));
|
|
// A *stable* sort by name, so symbols sharing a name keep the order they
|
|
// were declared in — the order a caller filtering `symbols()` by name
|
|
// would have seen, which is what makes swapping the two an identity.
|
|
let mut by_name: Vec<SymbolId> = (0..symbols.len() as u32).map(SymbolId).collect();
|
|
by_name.sort_by(|a, b| symbols[a.0 as usize].name.cmp(&symbols[b.0 as usize].name));
|
|
Semantics { scopes, symbols, references, uses, symbol_positions, reference_positions, by_name }
|
|
}
|
|
|
|
/// Point every import at the package it names, when this file declares it.
|
|
fn link_imports(scopes: &mut [Scope], symbols: &[Symbol]) {
|
|
let packages: HashMap<&str, ScopeId> = symbols
|
|
.iter()
|
|
.filter(|s| s.kind == SymbolKind::Package)
|
|
.filter_map(|s| s.child_scope.map(|c| (s.name.as_str(), c)))
|
|
.collect();
|
|
for scope in scopes.iter_mut() {
|
|
for import in &mut scope.imports {
|
|
import.scope = packages.get(import.package.as_str()).copied();
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Semantics {
|
|
/// Every scope; index 0 is always the file scope.
|
|
pub fn scopes(&self) -> &[Scope] {
|
|
&self.scopes
|
|
}
|
|
|
|
/// Every declaration, in the order they were bound.
|
|
pub fn symbols(&self) -> &[Symbol] {
|
|
&self.symbols
|
|
}
|
|
|
|
/// Every use, in source order.
|
|
pub fn references(&self) -> &[Reference] {
|
|
&self.references
|
|
}
|
|
|
|
/// The file scope.
|
|
pub fn file_scope(&self) -> ScopeId {
|
|
ScopeId(0)
|
|
}
|
|
|
|
/// One scope by id.
|
|
pub fn scope(&self, id: ScopeId) -> Option<&Scope> {
|
|
self.scopes.get(id.0 as usize)
|
|
}
|
|
|
|
/// One symbol by id.
|
|
pub fn symbol(&self, id: SymbolId) -> Option<&Symbol> {
|
|
self.symbols.get(id.0 as usize)
|
|
}
|
|
|
|
/// Every declaration that spells `name`, in declaration order — the same
|
|
/// symbols, in the same order, that filtering [`Semantics::symbols`] by
|
|
/// name yields, without walking the ones that cannot match.
|
|
pub fn symbols_named(&self, name: &str) -> impl Iterator<Item = SymbolId> + '_ {
|
|
// Two binary searches over the name-sorted side table: the first name
|
|
// that is not less than the one asked for, then the first one past it.
|
|
let spelling = |id: &SymbolId| self.symbol(*id).map_or("", |symbol| symbol.name.as_str());
|
|
let start = self.by_name.partition_point(|id| spelling(id) < name);
|
|
let rest = self.by_name.get(start..).unwrap_or(&[]);
|
|
let end = rest.partition_point(|id| spelling(id) == name);
|
|
rest.get(..end).unwrap_or(&[]).iter().copied()
|
|
}
|
|
|
|
/// The declaration whose *name* covers `offset` — a cursor sitting on a
|
|
/// declared name, not anywhere in its declaration.
|
|
pub fn symbol_at(&self, offset: u32) -> Option<SymbolId> {
|
|
position_at(&self.symbol_positions, offset)
|
|
}
|
|
|
|
/// The use whose name covers `offset`.
|
|
pub fn reference_at(&self, offset: u32) -> Option<&Reference> {
|
|
self.reference_id_at(offset).and_then(|id| self.reference(id))
|
|
}
|
|
|
|
/// The id of the use whose name covers `offset` — the key the workspace
|
|
/// index's overlay uses.
|
|
pub fn reference_id_at(&self, offset: u32) -> Option<ReferenceId> {
|
|
position_at(&self.reference_positions, offset)
|
|
}
|
|
|
|
/// One use by id.
|
|
pub fn reference(&self, id: ReferenceId) -> Option<&Reference> {
|
|
self.references.get(id.0 as usize)
|
|
}
|
|
|
|
/// Go-to-definition: the declaration named at `offset`, whether the
|
|
/// cursor sits on a use or on the declaration itself.
|
|
pub fn definition_of(&self, offset: u32) -> Option<&Symbol> {
|
|
if let Some(r) = self.reference_at(offset) {
|
|
if let Some(id) = r.resolved() {
|
|
return self.symbol(id);
|
|
}
|
|
}
|
|
self.symbol_at(offset).and_then(|id| self.symbol(id))
|
|
}
|
|
|
|
/// Find-all-references: every *use* of a symbol, in source order. The
|
|
/// declaration itself is not one of them — it is `symbol.name_span`, and
|
|
/// an LSP that wants `includeDeclaration` adds it.
|
|
pub fn references_of(&self, id: SymbolId) -> Vec<&Reference> {
|
|
match self.uses.get(&id) {
|
|
Some(indices) => indices.iter().filter_map(|&i| self.references.get(i)).collect(),
|
|
None => Vec::new(),
|
|
}
|
|
}
|
|
|
|
/// The outline of the file: file-scope declarations, each with the
|
|
/// declarations it contains, in source order. Scopes no declaration owns
|
|
/// (an unnamed `begin`) contribute their symbols to the enclosing level.
|
|
pub fn document_symbols(&self) -> Vec<DocumentSymbol> {
|
|
self.outline_of(ScopeId(0))
|
|
}
|
|
|
|
fn outline_of(&self, scope: ScopeId) -> Vec<DocumentSymbol> {
|
|
let Some(s) = self.scopes.get(scope.0 as usize) else {
|
|
return Vec::new();
|
|
};
|
|
let mut out: Vec<DocumentSymbol> = s
|
|
.symbols
|
|
.iter()
|
|
.map(|&id| {
|
|
let children = match self.symbol(id).and_then(|sym| sym.child_scope) {
|
|
Some(child) => self.outline_of(child),
|
|
None => Vec::new(),
|
|
};
|
|
DocumentSymbol { symbol: id, children }
|
|
})
|
|
.collect();
|
|
for &child in &s.children {
|
|
let owned = self.scopes.get(child.0 as usize).is_some_and(|c| c.owner.is_some());
|
|
if !owned {
|
|
out.extend(self.outline_of(child));
|
|
}
|
|
}
|
|
out.sort_by_key(|d| self.symbol(d.symbol).map_or(0, |s| s.name_span.start));
|
|
out
|
|
}
|
|
|
|
/// How many uses resolved to a declaration in this file, out of how many
|
|
/// were recorded. The corpus test reports the ratio as an honest baseline.
|
|
pub fn resolution_counts(&self) -> (usize, usize) {
|
|
(self.references.iter().filter(|r| r.resolved().is_some()).count(), self.references.len())
|
|
}
|
|
|
|
/// The span the file covers, as the parser saw it.
|
|
pub fn file_span(&self) -> TextRange {
|
|
self.scopes.first().map_or(TextRange::empty(0), |s| s.span)
|
|
}
|
|
}
|
|
|
|
/// The source span covering `offset` in a non-overlapping, start-sorted table.
|
|
fn position_at<Id: Copy>(positions: &[(TextRange, Id)], offset: u32) -> Option<Id> {
|
|
let after = positions.partition_point(|(span, _)| span.start <= offset);
|
|
let (span, id) = positions.get(after.checked_sub(1)?)?;
|
|
span.contains(offset).then_some(*id)
|
|
}
|