Files
lucisv/crates/vlog_semantic/src/lib.rs
T
lucioandClaude Fable 5 651e58bfb3 The design-hierarchy sidebar: codex's feature, integrated
An instance-oriented hierarchy view in the Activity Bar —
lucisv/moduleHierarchy snapshots (schema 2: uri table, flat ranges,
derived ids; 11.6 MB -> 2.3 MB on opentitan) plus
lucisv/moduleHierarchyChanged invalidation, gated on the extension's
initializationOptions. Format 5 carries decl spans, instance
occurrences and client positions for file-scope declarations
(+1.7-1.9 % store), so a snapshot reads no files at all: handler
145-167 -> 17-20 ms settled, a save with the sidebar open 366 ->
141 ms. complete is !scanning && !must_wait, pinned. Owner UI rounds:
no hover preview, all levels collapsed by default with stable ids
across refreshes, and search over a resident flat model (freeze
diagnosed: materialized expanded tree x undebounced double
fuzzyScore x whole-tree clone per keystroke) — prebuilt lowercased
index, bitmask prefilter, top-K counting, 200-row cap with an honest
remainder, single-digit ms over a 120k-entry fixture.
LineIndex::utf16_position unifies the index's and the wire's position
math under a cross-crate agreement test.

Implementation: codex. Integration fixes + owner items: Opus dev.
QA: lead (measurement pass) + Sonnet (SHIP, independent oracles).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 03:39:06 -07:00

266 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 {
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);
}
}
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)
}