TODO §49 (docs/features/hierarchical-tail). Closes topo §2.9-23 and
comment-slots finding 2. The first dev was cut off by an outage with the
library half complete; a second finished the tests, README and gates.
`Surface { Connection, Hierarchical }` on `Resolution::ExternalCandidate`
and `MemberSite::Unit`, set by `resolve.rs::head_surface` for an instance
head. `workspace/hierarchy.rs`: `surface_of` (the export rule, re-ruled)
and the two surface-taking reads; the index keeps two disjoint tables —
`members` (connection: ports, parameters; byte-identical to before for
every existing reader) and `hier_members` (nets, variables, instances) —
and a hierarchical read consults the connection table first, so a port
has one record. `FACTS_FORMAT` 18 → 19. `assign w = u_x.sig;` in another
file now resolves to `sub`'s `wire sig`; rename edits both files (nested
`u_a.u_b.sig` included); the §2.9-20 warning is retired for a resolved
tail; a generate-scoped net is still refused honestly. Completion after
`u_x.` in an expression lists the hierarchical surface; a connection
list's does not.
Census: single-file numbers unmoved; 12 939 connection + 5 239
hierarchical-only members; 335 corpus references newly resolve, 514 over
opentitan `hw/` (20 sampled by QA, all genuine). 0 of 860 corpus files
differ. Also: §50/§51 planned, §55 (state.rs size) filed.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
354 lines
15 KiB
Rust
354 lines
15 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;
|
|
pub mod words;
|
|
mod workspace;
|
|
|
|
pub use facts::{record_path, FACTS_FORMAT};
|
|
pub use model::{
|
|
DocumentSymbol, Duplicate, Import, MemberSite, Reference, ReferenceId, Resolution, Scope,
|
|
ScopeId, ScopeKind, Surface, 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 name a scope bound twice, in source order. Recorded by the
|
|
/// binder and judged by nobody here — see [`Duplicate`].
|
|
duplicates: Vec<Duplicate>,
|
|
/// 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();
|
|
match &file.fragment {
|
|
Some(fragment) => binder.bind_fragment(fragment, file_scope, file.span),
|
|
None => 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, duplicates, .. } = 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,
|
|
duplicates,
|
|
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
|
|
}
|
|
|
|
/// Every name a scope bound a second time, in source order.
|
|
///
|
|
/// Additive, and read by one caller: the `duplicate-declaration` lint.
|
|
/// Nothing else in the crate consults it, and no existing answer changed
|
|
/// when it was added — a redeclaration is still a reference to the first
|
|
/// declaration everywhere it was one before.
|
|
pub fn duplicates(&self) -> &[Duplicate] {
|
|
&self.duplicates
|
|
}
|
|
|
|
/// 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())
|
|
}
|
|
|
|
/// Where `head.mids….` puts the cursor: the site the next `.name` would
|
|
/// be looked up in, with nothing looked up yet.
|
|
///
|
|
/// **The prefix of the walk that resolves `head.mids….name`**, and the
|
|
/// same code — `resolve::member_of` is this function plus one lookup in
|
|
/// what it returns. That is the whole point of it: a completion list
|
|
/// after a `.` must offer exactly the names hover and go-to-definition
|
|
/// would resolve there, and the only way to promise that is to ask the
|
|
/// same question of the same walk.
|
|
///
|
|
/// `head` is the first identifier of the spine, `mids` the names between
|
|
/// it and the cursor (`item.hdr.` is `head = "item"`, `mids = ["hdr"]`).
|
|
/// `this` and `super` are accepted as heads and mean the enclosing class
|
|
/// and its base. `None` means this crate has nothing to say — an
|
|
/// unresolvable head, a type it cannot look members up in, a chain it
|
|
/// cannot finish — and a caller must answer nothing rather than guess.
|
|
pub fn member_site(&self, from: ScopeId, head: &str, mids: &[String]) -> Option<MemberSite> {
|
|
resolve::member_site(&self.scopes, &self.symbols, from, head, mids)
|
|
}
|
|
|
|
/// Where `path::` puts the cursor — the package or class the `::` reaches
|
|
/// into, as a scope this file holds or as a workspace unit name.
|
|
///
|
|
/// The prefix of the walk that resolves `path::name`, on the same terms
|
|
/// [`Semantics::member_site`] is the prefix of the other one. `None` when
|
|
/// a `pkg::cls` path names a segment this file's own container does not
|
|
/// hold — this file has answered, and the answer is nothing.
|
|
pub fn unit_site(&self, from: ScopeId, path: &str) -> Option<MemberSite> {
|
|
resolve::unit_site(&self.scopes, &self.symbols, from, path)
|
|
}
|
|
|
|
/// The scope the module or interface `name` opens, when **this file**
|
|
/// declares one — the scope a `.port` connection to it is resolved in.
|
|
///
|
|
/// Literally the call `resolve`'s [`Target::Port`] arm makes
|
|
/// (`owning_scope(..., is_instantiable)`), so a completion list of a
|
|
/// connection's legal names and the resolution of one of them look in one
|
|
/// scope, found one way. `None` when this file does not declare the
|
|
/// module — which is exactly when `Target::Port` hands the question to the
|
|
/// workspace's member table instead.
|
|
pub fn instantiable_scope(&self, name: &str) -> Option<ScopeId> {
|
|
resolve::owning_scope(&self.scopes, &self.symbols, name, resolve::is_instantiable)
|
|
}
|
|
|
|
/// Every scope a member of `scope` may be declared in, nearest first, and
|
|
/// the base class the `extends` chain left this file at — `None` when it
|
|
/// ended here.
|
|
///
|
|
/// The walk a member *lookup* takes, with the lookup left out, so that
|
|
/// listing a class's members and resolving one of them cannot disagree
|
|
/// about which classes are on the chain. For a non-class scope this is
|
|
/// the scope itself and nothing more.
|
|
pub fn member_scopes(&self, scope: ScopeId) -> (Vec<ScopeId>, Option<String>) {
|
|
resolve::extends_chain(&self.scopes, &self.symbols, scope)
|
|
}
|
|
|
|
/// 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)
|
|
}
|