workspace-index (vlog_semantic): cross-file resolution -- the
owner's `import pkg::*;`-anywhere requirement delivered.
WorkspaceIndex maps modules/packages/file-scope typedefs, package
exports, module ports/params and per-file define tables; built
tolerantly (broken files still contribute), deterministic by
construction (FileIds assigned after path sort). resolve_external
answers ExternalCandidates in a two-layer overlay keyed by
ReferenceId -- Semantics stays a pure single-file fact; local
declarations outrank imports. Corpus: 87% of external candidates
answered (external rate 19.6% -> 2.6% on clean files), ambiguity
kept honest (OpenTitan prim_generic/prim_xilinx), 0.7s build,
workspace_symbols substring search.
name-spans (vlog_parser): the approved vlog-semantic handshake --
the parser records every declared name's span at parse time (28
fields across 21 node kinds; Name/ImportPath bundles where parallel
Vecs could desync; ImportPath splits p::x for the index). Content-
pinned by the exhaustive walker on every source, mutation-tested
three ways, zero behavior change (corpus md5 exact, QA byte-compared
formatter output against a HEAD worktree). scan.rs is now one
consumer away from deletion (DataType span, handshake item 2).
TODO §6 foundations complete: spans, error recovery, define table,
single-file semantics, workspace index. Next: vfmt_server.
Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{workspace-index,name-spans}/README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
211 lines
7.5 KiB
Rust
211 lines
7.5 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;
|
|
mod model;
|
|
mod resolve;
|
|
mod scan;
|
|
mod workspace;
|
|
|
|
pub use model::{
|
|
DocumentSymbol, Import, Reference, ReferenceId, Resolution, Scope, ScopeId, ScopeKind, Symbol,
|
|
SymbolId, SymbolKind,
|
|
};
|
|
pub use workspace::{
|
|
resolve_external, Def, Definition, ExternalResolutions, ExternalTarget, FileId, IndexCounts,
|
|
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>>,
|
|
}
|
|
|
|
/// 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);
|
|
|
|
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 {
|
|
references.push(Reference {
|
|
name: p.name.clone(),
|
|
name_span: p.name_span,
|
|
scope: p.scope,
|
|
resolution: resolve::resolve(&scopes, &symbols, p),
|
|
});
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
Semantics { scopes, symbols, references, uses }
|
|
}
|
|
|
|
/// 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)
|
|
}
|
|
|
|
/// 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> {
|
|
self.symbols.iter().position(|s| s.name_span.contains(offset)).map(|i| SymbolId(i as u32))
|
|
}
|
|
|
|
/// The use whose name covers `offset`.
|
|
pub fn reference_at(&self, offset: u32) -> Option<&Reference> {
|
|
self.references.iter().find(|r| r.name_span.contains(offset))
|
|
}
|
|
|
|
/// 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> {
|
|
self.references
|
|
.iter()
|
|
.position(|r| r.name_span.contains(offset))
|
|
.map(|i| ReferenceId(i as u32))
|
|
}
|
|
|
|
/// 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)
|
|
}
|
|
}
|