Files
lucisv/crates/vlog_semantic/src/lib.rs
T
lucioandClaude Fable 5 54b0ca3896 Add class-semantics and lexer-cleanup (round 20)
class-semantics: classes are first-class in vlog_semantic -- class
scopes and symbols, member/method/prototype binding, this.x
(nearest-class-only), super.x, cls::x with lexical unit heads,
out-of-body cls::method bound into the class's scope with the extern
prototype as the definition (rule 10), and the honest
InheritedCandidate{base, paths} shape: a member miss in an extending
class records what the unknown base might supply (import paths
included) and is never chased, not even in-file -- the future
inheritance round's worklist, measured at 1303 candidates. Unit-name
misses stay ExternalCandidate (QA-found, lead-ruled: bases supply
members, not package names; +170 recovered navigations, pinned).
Workspace index gains classes as units (246) and their members
(11399). scan.rs migrated to parser name-spans: 26 call sites down
to the 2 documented consumers. 114044 spans, 0 unplaced, 0 panics;
UVM code now has hover/definition/references/outline.

lexer-cleanup: the three filed gaps -- @(* ) lexes via a
starts_attribute backoff (an attribute cannot begin with `)`; real
attributes pinned, no misfire on legal expressions), a leading BOM
is accepted as a named losslessness exception (mid-file BOM errors
clearly; 20k-case position fuzz clean), and non-ASCII lex errors now
decode the full character AND surface through vfmt check's error
slot (exit 2, matching format, text-rule findings still reported --
the silent-pass hole closed). The macro space-before-paren item is
parked with a QA-hardened analysis: the reading depends on a
definition vfmt cannot see, any fixed answer is provably wrong for
one population, and today's behavior fails safe.

827 workspace tests. Dev: 2 Fable agents; QA: 2 Opus agents; reviews
in docs/features/{class-semantics,lexer-cleanup}/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-20 00:56:32 -07:00

214 lines
7.7 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);
// 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);
}
}
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)
}
}