Files
lucisv/crates/vlog_semantic/src/workspace/mod.rs
T
lucioandClaude Fable 5 b57ae35be4 Decomposition, lane D: vlog_semantic's bind.rs and workspace.rs, vlog_refactor's ports.rs and rename.rs become modules, a pure move
TODO section 28, lane D (the file-size rule in CLAUDE.md).
bind.rs (1 718 production lines) becomes bind/{mod, item, decl, class,
cover, stmt, sva, expr}.rs; workspace.rs (1 111) becomes workspace/
{mod, index, update, record, external}.rs with facts.rs and
FACTS_FORMAT untouched; ports.rs (1 391) becomes ports/{mod, find, add,
remove, propagate, list}.rs, one file per refactoring; rename.rs (760)
becomes rename/{mod, scope, warnings, tests}.rs. No function split, no
file over 600 production lines (largest add.rs at 432), every public
path unchanged (crate-root doc pages identical; only private-module
pages relocated). Carved by a range manifest that had to tile the
original byte for byte. Proof: per-binary test counts identical
(vlog_semantic 345 / 17, vlog_refactor 206 / 5, workspace 3 215 / 48),
corpus --stdout byte-identical, and the lucisv check finding lists
byte-identical between this build and the base over the corpus and the
opentitan hw tree - done by the dev and redone from scratch by QA.

docs/features/decomposition-semantic/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 21:55:55 -07:00

341 lines
15 KiB
Rust

//! The workspace index: the second layer of name resolution, the one that
//! finishes what [`analyze`](crate::analyze) deliberately leaves open.
//!
//! `analyze` is single-file by design, so a name only another file can supply
//! comes back as [`Resolution::ExternalCandidate`] carrying the import paths
//! that could finish it. [`WorkspaceIndex`] scans every file in the workspace
//! once and records what each one *declares*; [`resolve_external`] walks one
//! file's external candidates against that index and produces an **overlay**
//! keyed by reference id. The overlay is a separate value: `Semantics` is
//! never mutated, so a file's analysis stays valid when the workspace around
//! it changes, and a server can recompute either layer alone.
//!
//! See `docs/features/workspace-index/README.md` for the resolution order,
//! the duplicate-name policy and the corpus numbers.
//!
//! This file is the index's vocabulary: the records it hands out ([`Def`],
//! [`DeclLines`], the edges) and the [`WorkspaceIndex`] tables themselves.
//! `index` answers questions of a built index, `update` changes one after it
//! is built, `record` reads off what one file contributes ([`FileFacts`]), and
//! `external` is the overlay — [`resolve_external`] — and the member and
//! inheritance walks it shares with `index`.
mod external;
mod index;
mod record;
mod update;
pub use external::{resolve_external, Definition, ExternalResolutions, ExternalTarget};
pub use index::{index_order, IndexBuilder};
pub use record::FileFacts;
pub(crate) use record::{Decl, ReferenceFact, SiteFact};
use std::collections::{BTreeMap, HashSet};
use std::path::PathBuf;
use vlog_parser::span::TextRange;
use vlog_parser::LineIndex;
use crate::model::SymbolKind;
/// Index of a file in a [`WorkspaceIndex`], assigned in sorted path order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FileId(pub u32);
/// A declaration the index can point an editor at.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Def {
/// The file the declaration is written in.
pub file: FileId,
/// Byte range of the declared name inside that file.
pub name_span: TextRange,
/// Byte range of the complete construct that declares the name.
pub decl_span: TextRange,
/// What kind of declaration it is, for an icon and for hover text.
pub kind: SymbolKind,
/// Where the declaration is *completed* when not at `name_span` — a
/// non-ANSI port's body `input wire clk;`. A cross-file hover shows these
/// lines; `None` for every declaration complete where it is named.
pub detail_span: Option<TextRange>,
/// Which lines those spans fall on, read while the file was indexed.
pub lines: DeclLines,
/// The declared type **as written**, on the same terms as
/// [`crate::Symbol::type_name`] — which is where it is copied from. This
/// is what lets a member access chain across files: the type of
/// `pkt_t::hdr` is what `item.hdr.addr`'s last link is looked up in, and
/// only the index knows it when `pkt_t` is another file's. `None` for a
/// built-in type, an unpacked declarator, and every declaration written
/// without a type.
pub type_name: Option<String>,
}
/// Where a declaration sits in its file, counted in **lines**, computed when
/// that file is indexed.
///
/// The index keeps no file text, so before this every `file:line` a server
/// printed for an indexed declaration cost a read of the declaring file and a
/// whole [`LineIndex`] over it — the thing a cross-file hover into a closed
/// file was mostly spending its time on. A line is four bytes per declaration,
/// a few tens of KB for a workspace of 20 000 modules, and it is the whole of
/// what a heading needs.
///
/// **One value per declaration, so it extends by gaining a field.** Members
/// are [`Decl`]s exactly as units are, so a module's ports already carry their
/// own lines here; a column, or a rendered preview, is another field written
/// beside these two — plus the [`crate::FACTS_FORMAT`] bump any change to a
/// record owes — and not a second table to keep in step with this one.
/// [`DeclPositions`] is the first of those added fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DeclLines {
/// 1-based line the declared name is on.
pub name: u32,
/// 1-based line the `detail_span` starts on, `None` exactly when there is
/// no detail span.
pub detail: Option<u32>,
/// The same two spans as a *client* counts positions — `Some` for a
/// file-scope declaration, `None` for a member. See [`DeclPositions`].
pub positions: Option<DeclPositions>,
}
impl DeclLines {
/// The lines a declaration's spans fall on, read off its file's line
/// index. 1-based, so `name` is what `LineIndex::line_col` reports and
/// what a `file:line` prints.
fn of(lines: &LineIndex, name_span: TextRange, detail_span: Option<TextRange>) -> DeclLines {
DeclLines {
name: lines.line_col(name_span.start).0,
detail: detail_span.map(|span| lines.line_col(span.start).0),
positions: None,
}
}
}
/// One position as a language-server client counts one: a **0-based** line and
/// **UTF-16 code units** into it — not [`LineIndex`]'s 1-based bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord)]
pub struct Utf16Pos {
/// 0-based line.
pub line: u32,
/// UTF-16 code units from the start of that line's content.
pub character: u32,
}
/// A byte [`TextRange`] as a client sees it, both ends converted once when the
/// file was scanned.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord)]
pub struct Utf16Range {
pub start: Utf16Pos,
pub end: Utf16Pos,
}
impl Utf16Range {
/// A span's two ends, converted through the file's own line index.
pub(crate) fn of(src: &str, lines: &LineIndex, span: TextRange) -> Utf16Range {
Utf16Range { start: pos(src, lines, span.start), end: pos(src, lines, span.end) }
}
}
fn pos(src: &str, lines: &LineIndex, offset: u32) -> Utf16Pos {
let (line, character) = lines.utf16_position(src, offset);
Utf16Pos { line, character }
}
/// Where a **file-scope** declaration sits in its file, in the units a client
/// speaks — so pointing an editor at a module declared in a file nobody has
/// open costs no read of that file at all.
///
/// **Why only file-scope declarations carry this.** A member — a port, a
/// parameter, a class field — is a [`Decl`] exactly as a unit is, and there are
/// two orders of magnitude more of them: on opentitan, 1 544 modules against
/// hundreds of thousands of members, so giving every declaration eight more
/// numbers would have roughly doubled the persistent store to serve a caller
/// that does not exist. The units and the members are written in two separate
/// groups of a record, so "units carry positions, members do not" costs a
/// member no field at all — and the day a member wants them, it is the same
/// eight fields in the other group plus the [`crate::FACTS_FORMAT`] bump.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DeclPositions {
/// The declared name's own range — an editor's selection range.
pub name: Utf16Range,
/// The whole declaring construct's range.
pub decl: Utf16Range,
}
/// Stable identity of one indexed declaration inside the current index.
///
/// A [`FileId`] may move when a file is added or removed, so this key survives
/// only as long as the [`WorkspaceIndex`] that produced it. That is exactly the
/// lifetime of every merged table in the index; callers never persist it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DefinitionKey {
pub file: FileId,
pub name_start: u32,
pub name_end: u32,
}
impl DefinitionKey {
/// The key of an indexed definition.
pub fn of(def: &Def) -> DefinitionKey {
DefinitionKey {
file: def.file,
name_start: def.name_span.start,
name_end: def.name_span.end,
}
}
}
/// One indexed use of a declaration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReferenceSite {
/// The file the use is written in.
pub file: FileId,
/// Byte range of the referenced name inside that file.
pub name_span: TextRange,
}
/// One hit of [`WorkspaceIndex::workspace_symbols`].
#[derive(Debug, Clone)]
pub struct WorkspaceSymbol<'a> {
/// The declared name, as written.
pub name: &'a str,
/// The unit the name is declared in, for a package/module member.
pub container: Option<&'a str>,
/// Where it is declared.
pub def: &'a Def,
}
/// One end of an edge: a declaration another file's edge points at or hangs
/// off. The instantiating module of an instantiation edge, the extending class
/// of an inheritance edge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeclSite {
/// The declared name, as written.
pub name: String,
/// Byte range of that name in its file.
pub name_span: TextRange,
/// Byte range of the whole declaration — `module … endmodule`, `class …
/// endclass` — which is what a hierarchy item's `range` is.
pub span: TextRange,
}
/// One place the workspace instantiates a module.
///
/// The census this records is `callHierarchy/incomingCalls`'s, unchanged: one
/// edge per `Instantiation` node however many instances it declares, textual
/// rather than elaborated (a `generate for` body is one site, both arms of an
/// `` `ifdef`` are sites), matched by the name as written. An instantiation at
/// **file scope** is not an edge: it has no enclosing module to be the caller,
/// which is the rule `hierarchy::callers_in` has always applied.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstantiationEdge {
/// The file the instantiation is written in.
pub file: FileId,
/// The module it is written inside — the caller.
pub owner: DeclSite,
/// Byte range of the instantiated module's name at the site.
pub site_span: TextRange,
/// The individual instances the statement declares, in source order.
///
/// The edge itself deliberately remains one-per-statement: call hierarchy
/// and code lenses have always treated `sub u1 (), u2 ();` as one written
/// call site. Instance-oriented clients can flatten this list without
/// changing that census.
pub instances: Vec<InstanceOccurrence>,
}
/// One named instance inside an [`InstantiationEdge`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstanceOccurrence {
/// Instance name as written (`u_fifo`).
pub name: String,
/// Byte range of the instance name.
pub name_span: TextRange,
/// Byte range of the whole instance, including dimensions and connections.
pub span: TextRange,
/// `name_span` as a client counts positions, converted when the file was
/// scanned — the same reason [`DeclPositions`] exists, for the other half
/// of what a design-hierarchy row points at.
pub name_positions: Utf16Range,
/// `span` likewise.
pub positions: Utf16Range,
}
/// One class that extends another.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InheritanceEdge {
/// The file the extending class is declared in.
pub file: FileId,
/// The extending class.
pub subclass: DeclSite,
}
/// What every file in the workspace declares: the units other files can name,
/// their exported members, their `` `define`` tables, and the edges between
/// them — who instantiates which module, and who extends which class.
///
/// The index keeps every file's contribution **unmerged** beside the merged
/// tables ([`FileFacts`]), which is what lets one file be replaced without
/// re-reading the workspace ([`WorkspaceIndex::update_file`]). The price is
/// memory: the same names and spans the tables hold, held once more per file.
#[derive(Debug, Clone, Default)]
pub struct WorkspaceIndex {
/// Indexed by [`FileId`], sorted by path. The paths of `facts`, kept flat
/// so [`WorkspaceIndex::files`] can hand out a slice.
files: Vec<PathBuf>,
/// What each file contributes, parallel to `files` and in the same order.
/// A [`FileId`] is an index into both.
facts: Vec<FileFacts>,
/// File-scope name → every declaration of it, in disambiguation order.
units: BTreeMap<String, Vec<Def>>,
/// Unit name → member name → every declaration of it.
members: BTreeMap<String, BTreeMap<String, Vec<Def>>>,
/// Instantiated module name → every site, in file order then walk order.
instantiations: BTreeMap<String, Vec<InstantiationEdge>>,
/// Base class name → every class extending it, in file order then walk
/// order.
subclasses: BTreeMap<String, Vec<InheritanceEdge>>,
/// The same census read the other way: class name → the base it extends,
/// as written. Built in [`WorkspaceIndex::merge`] from the very edges that
/// fill `subclasses`, so the two cannot disagree and no [`FileFacts`]
/// field was added for it. See [`WorkspaceIndex::base_of`].
bases: BTreeMap<String, String>,
/// Macro name → `(file, entry-in-that-file)` for each definition.
macro_definitions: BTreeMap<String, Vec<(FileId, usize)>>,
/// Declaration → every unambiguous use, in file then source order.
reference_sites: BTreeMap<DefinitionKey, Vec<ReferenceSite>>,
/// Declarations touched by at least one ambiguous external reference.
/// Find-references refuses those rather than assigning the use to one of
/// several equally plausible declarations.
ambiguous_references: HashSet<DefinitionKey>,
}
/// The headline numbers of a built index.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct IndexCounts {
/// Files scanned, whether they parsed or not.
pub files: usize,
/// Module declarations indexed, duplicates counted separately. Interfaces
/// are **not** in this number — they have their own, so a caller reporting
/// "1 544 modules" still means 1 544 modules.
pub modules: usize,
/// Interface declarations indexed, duplicates counted separately.
pub interfaces: usize,
/// Package declarations indexed, duplicates counted separately.
pub packages: usize,
/// File-scope typedefs; a typedef inside a module or package is not one.
pub typedefs: usize,
/// Class declarations reachable in the index — file-scope units plus
/// classes registered as members of a package or an enclosing class.
pub classes: usize,
/// Package, class and module member declarations, duplicates counted
/// separately.
pub members: usize,
/// `` `define``/`` `undef`` directives recorded across all files.
pub defines: usize,
/// Instantiation sites recorded — one per written statement, inside a
/// module.
pub instantiations: usize,
/// `extends` edges recorded, one per class that names a base.
pub inheritances: usize,
}