641 lines
30 KiB
Rust
641 lines
30 KiB
Rust
//! What a built [`WorkspaceIndex`] answers, by map reads alone: files and
|
||
//! ids, the unit and member tables, the inherited-member listing, the edges,
|
||
//! `` `define``s, reference postings, the two spelling censuses and
|
||
//! `workspace/symbol` — plus the two ways to build one,
|
||
//! [`WorkspaceIndex::build`] and the file-at-a-time [`IndexBuilder`] it is a
|
||
//! loop over. Nothing here changes an index once `finish` has run; that is
|
||
//! `update`.
|
||
|
||
use std::collections::HashSet;
|
||
use std::path::{Path, PathBuf};
|
||
|
||
use vlog_parser::defines::{Define, DefineTable};
|
||
|
||
use crate::model::{Surface, SymbolKind};
|
||
|
||
use super::external::{fold_path, last_segment, member_chain, own_members};
|
||
use super::hierarchy;
|
||
use super::record::{FileFacts, ReferenceFact};
|
||
use super::{
|
||
reexport, Def, DefinitionKey, FileId, IndexCounts, IndexTableSizes, InheritanceEdge,
|
||
InstantiationEdge, Reexport, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
|
||
};
|
||
|
||
impl WorkspaceIndex {
|
||
/// Scan a whole workspace. The caller does the I/O and hands over
|
||
/// `(path, source)` pairs; tokenizing and parsing happen here, with
|
||
/// `parse_source_tolerant`, so a file that does not parse still
|
||
/// contributes every declaration that *did* parse.
|
||
///
|
||
/// Pure: the same inputs always give the same index, whatever order they
|
||
/// arrive in. A workspace where **one** file changed does not need this at
|
||
/// all — see [`WorkspaceIndex::update_file`], which produces exactly the
|
||
/// index this would have.
|
||
///
|
||
/// This is exactly [`index_order`] followed by an [`IndexBuilder`] loop,
|
||
/// and stays the API every caller that does not care to watch the build
|
||
/// should use. The [`index_order`] here saves parsing a duplicate path
|
||
/// twice; it is not what makes the result deterministic — the builder
|
||
/// sorts for itself.
|
||
pub fn build<'a>(files: impl IntoIterator<Item = (PathBuf, &'a str)>) -> WorkspaceIndex {
|
||
let mut builder = IndexBuilder::new();
|
||
for (path, src) in index_order(files) {
|
||
builder.add_file(path, src);
|
||
}
|
||
builder.finish()
|
||
}
|
||
|
||
/// Every file the index covers, by [`FileId`].
|
||
pub fn files(&self) -> &[PathBuf] {
|
||
&self.files
|
||
}
|
||
|
||
/// The path of one file.
|
||
pub fn path(&self, file: FileId) -> Option<&Path> {
|
||
self.files.get(file.0 as usize).map(PathBuf::as_path)
|
||
}
|
||
|
||
/// The id of an indexed path.
|
||
pub fn file_id(&self, path: &Path) -> Option<FileId> {
|
||
self.files
|
||
.binary_search_by(|held| held.as_path().cmp(path))
|
||
.ok()
|
||
.map(|at| FileId(at as u32))
|
||
}
|
||
|
||
/// Every file-scope declaration of `name` — module, package or typedef —
|
||
/// in disambiguation order (by file path, then by position in the file).
|
||
/// More than one means the workspace really does declare the name twice.
|
||
pub fn units(&self, name: &str) -> &[Def] {
|
||
self.units.get(name).map_or(&[], Vec::as_slice)
|
||
}
|
||
|
||
/// Every declaration of `member` `unit` exports on its **connection**
|
||
/// surface. This is what makes `p::x` and `import p::*` reach into
|
||
/// another file, and what makes a `.port` connection reach into the
|
||
/// instantiated module.
|
||
///
|
||
/// The connection surface is the whole surface of a package, a class and
|
||
/// a struct; for a module it is its ports and parameters, and what a
|
||
/// hierarchical path may name besides is
|
||
/// [`WorkspaceIndex::member_in`]'s business ([`Surface`]).
|
||
pub fn member(&self, unit: &str, member: &str) -> &[Def] {
|
||
self.members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice)
|
||
}
|
||
|
||
/// [`WorkspaceIndex::member`] in a named surface: the same answer for
|
||
/// [`Surface::Connection`], and for [`Surface::Hierarchical`] the
|
||
/// connection records first and a module's nets, variables and instances
|
||
/// after them.
|
||
pub fn member_in(&self, unit: &str, member: &str, surface: Surface) -> &[Def] {
|
||
hierarchy::member(self, unit, member, surface)
|
||
}
|
||
|
||
/// Every member `unit` exports on its connection surface, sorted by name
|
||
/// — the completion list behind `p::` and behind an instantiation's
|
||
/// connection list.
|
||
pub fn members_of(&self, unit: &str) -> impl Iterator<Item = (&str, &[Def])> {
|
||
self.members
|
||
.get(unit)
|
||
.into_iter()
|
||
.flat_map(|m| m.iter().map(|(name, defs)| (name.as_str(), defs.as_slice())))
|
||
}
|
||
|
||
/// Every member of `unit` a hierarchical path may name and a connection
|
||
/// list may not, sorted by name — the second half of a hierarchical
|
||
/// listing, never a listing on its own.
|
||
pub(super) fn hierarchical_members_of(
|
||
&self,
|
||
unit: &str,
|
||
) -> impl Iterator<Item = (&str, &[Def])> {
|
||
self.hier_members
|
||
.get(unit)
|
||
.into_iter()
|
||
.flat_map(|m| m.iter().map(|(name, defs)| (name.as_str(), defs.as_slice())))
|
||
}
|
||
|
||
/// [`WorkspaceIndex::member`] on the hierarchical-only half alone.
|
||
pub(super) fn hierarchical_member(&self, unit: &str, member: &str) -> &[Def] {
|
||
self.hier_members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice)
|
||
}
|
||
|
||
/// Every unit that declares `name` on its **hierarchical** surface, with
|
||
/// the declaration — the census `workspace_symbols` deliberately does not
|
||
/// hold.
|
||
///
|
||
/// A module's internal net is not a workspace symbol: `workspace/symbol`
|
||
/// answers what a user can name from outside, and a design with 20 000
|
||
/// modules has hundreds of thousands of internal signals. But a rename's
|
||
/// fan-out has to find the *declaring file* of a name a hierarchical tail
|
||
/// resolves to, and that is exactly this question — asked once per
|
||
/// rename, over a map, reading nothing. See
|
||
/// `docs/features/hierarchical-tail/README.md`.
|
||
pub fn hierarchical_declarations<'a>(
|
||
&'a self,
|
||
name: &'a str,
|
||
) -> impl Iterator<Item = (&'a str, &'a Def)> + 'a {
|
||
self.hier_members.iter().flat_map(move |(unit, members)| {
|
||
members.get(name).into_iter().flatten().map(move |def| (unit.as_str(), def))
|
||
})
|
||
}
|
||
|
||
/// Every member `path::` can name, **inherited ones included**, sorted by
|
||
/// name with one declaration each — the completion list behind `pkg::`,
|
||
/// `handle.` and `vif.` when the type is another file's.
|
||
///
|
||
/// `path` is a [`crate::MemberSite::Unit`] spelling: a unit name, or a
|
||
/// unit followed by the member names already selected from it
|
||
/// (`pkt_t::hdr`), which are folded through
|
||
/// [`WorkspaceIndex::member_unit`] exactly as `follow_one` folds them
|
||
/// before its own lookup. A hop that cannot be taken honestly answers an
|
||
/// empty list, never a guess.
|
||
///
|
||
/// **The same walk one member lookup takes.** The units searched are
|
||
/// `unit` and then its `extends` hops ([`own_members`]), then the packages
|
||
/// `unit` **re-exports** from ([`reexport::members`]) — exactly
|
||
/// `member_chain`'s order — and a name found in more than one of them is
|
||
/// listed once from the nearest. So a subclass's override, and a package's
|
||
/// own declaration of a name it also re-exports, are what is listed *and*
|
||
/// what a lookup would find. Map reads only: no file is opened.
|
||
pub fn members_of_chain(&self, path: &str) -> Vec<(&str, &Def)> {
|
||
self.members_of_chain_in(path, Surface::Connection)
|
||
}
|
||
|
||
/// [`WorkspaceIndex::members_of_chain`] in a named surface — the list
|
||
/// behind `u_x.` in an expression, where the module's nets, variables and
|
||
/// instances are what the user is reaching for and what the tail
|
||
/// resolution will find. A connection list's `.` is the other surface and
|
||
/// its own function (`completion::connection_members`).
|
||
pub fn members_of_chain_in(&self, path: &str, surface: Surface) -> Vec<(&str, &Def)> {
|
||
let Some(unit) = fold_path(self, path, surface) else {
|
||
return Vec::new();
|
||
};
|
||
let mut out: Vec<(&str, &Def)> = Vec::new();
|
||
let mut seen: HashSet<&str> = HashSet::new();
|
||
for (name, def) in
|
||
own_members(self, &unit, surface).into_iter().chain(reexport::members(self, &unit))
|
||
{
|
||
if seen.insert(name) {
|
||
out.push((name, def));
|
||
}
|
||
}
|
||
out.sort_by_key(|(name, _)| *name);
|
||
out
|
||
}
|
||
|
||
/// What one package re-exports, in file order then source order — the
|
||
/// edges `reexport`'s two walks follow. Empty for every unit that
|
||
/// re-exports nothing, which is all but a handful in any workspace.
|
||
pub(super) fn reexports(&self, unit: &str) -> &[Reexport] {
|
||
self.reexports.get(unit).map_or(&[], Vec::as_slice)
|
||
}
|
||
|
||
/// The packages `unit` re-exports names from, each named once.
|
||
///
|
||
/// The public half of [`WorkspaceIndex::reexports`], and the one question
|
||
/// a caller assembling a *file set* has to ask: a refactoring that judges
|
||
/// which of a file's imports are used must hold every file that can
|
||
/// supply a name through `import p::*`, and `p` re-exporting from `q`
|
||
/// makes `q`'s file one of them. Empty for every unit that re-exports
|
||
/// nothing, which is all but a handful in any workspace. See
|
||
/// `docs/features/organize-imports/README.md`.
|
||
pub fn reexported_packages(&self, unit: &str) -> Vec<&str> {
|
||
let mut out: Vec<&str> = Vec::new();
|
||
for edge in self.reexports(unit) {
|
||
if !out.contains(&edge.package.as_str()) {
|
||
out.push(edge.package.as_str());
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
/// The **declared type** of one member of one unit, as the next unit name
|
||
/// to look in — the hop that walks a chain `pkt_t::hdr::addr` across
|
||
/// files, and the one a `MemberSite::Unit` path is folded by.
|
||
///
|
||
/// `None` whenever the hop cannot be taken honestly: no such member,
|
||
/// several equally plausible ones, a member declared without a type this
|
||
/// crate records, or a type name the **workspace** declares more than
|
||
/// once — two declarations are two answers, and picking one is the guess
|
||
/// `TypeHere` exists to refuse (a struct `hdr_t` in one file and an
|
||
/// unrelated class `hdr_t` in another must not answer for each other). A
|
||
/// class declared inside a package declares no file-scope unit at all —
|
||
/// the dominant UVM shape — and is unaffected.
|
||
pub fn member_unit(&self, unit: &str, member: &str) -> Option<String> {
|
||
self.member_unit_in(unit, member, Surface::Connection)
|
||
}
|
||
|
||
/// [`WorkspaceIndex::member_unit`] in a named surface: the hop
|
||
/// `u_a.u_b.sig` takes, where `u_b` is an instance inside `a` and only
|
||
/// the hierarchical surface holds it.
|
||
pub fn member_unit_in(&self, unit: &str, member: &str, surface: Surface) -> Option<String> {
|
||
let [def] = member_chain(self, unit, member, surface) else {
|
||
return None;
|
||
};
|
||
let next = last_segment(def.type_name.as_deref()?);
|
||
(self.units(next).len() < 2).then(|| next.to_string())
|
||
}
|
||
|
||
/// Every place the workspace instantiates `name`, in disambiguation order
|
||
/// — by file path, then in the order the sites are written.
|
||
///
|
||
/// This is the table `callHierarchy/incomingCalls` and the code lens read
|
||
/// instead of re-reading and re-parsing every in-scope file; see
|
||
/// [`InstantiationEdge`] for the census it records.
|
||
pub fn instantiations_of(&self, name: &str) -> &[InstantiationEdge] {
|
||
self.instantiations.get(name).map_or(&[], Vec::as_slice)
|
||
}
|
||
|
||
/// Every class extending `name`, in the same order.
|
||
pub fn subclasses_of(&self, name: &str) -> &[InheritanceEdge] {
|
||
self.subclasses.get(name).map_or(&[], Vec::as_slice)
|
||
}
|
||
|
||
/// What the class `name` extends, **as written** (`base`, `pkg::base`) —
|
||
/// the reverse of [`WorkspaceIndex::subclasses_of`], and the one hop an
|
||
/// inherited-member lookup needs.
|
||
///
|
||
/// One base per class name: a workspace declaring the name twice takes the
|
||
/// first in disambiguation order (by file path, then by walk order), the
|
||
/// same policy every other duplicate-name table here applies. `None` for a
|
||
/// class that extends nothing, and for a name the workspace does not
|
||
/// declare — which is what ends the chase in
|
||
/// [`resolve_external`](super::resolve_external).
|
||
pub fn base_of(&self, name: &str) -> Option<&str> {
|
||
self.bases.get(name).map(String::as_str)
|
||
}
|
||
|
||
/// Every instantiated module name the workspace names, with its sites.
|
||
pub fn instantiations(&self) -> impl Iterator<Item = (&str, &[InstantiationEdge])> {
|
||
self.instantiations.iter().map(|(name, edges)| (name.as_str(), edges.as_slice()))
|
||
}
|
||
|
||
/// Every extended class name the workspace names, with its subclasses.
|
||
pub fn subclasses(&self) -> impl Iterator<Item = (&str, &[InheritanceEdge])> {
|
||
self.subclasses.iter().map(|(name, edges)| (name.as_str(), edges.as_slice()))
|
||
}
|
||
|
||
/// What one file contributes to this index, by path.
|
||
///
|
||
/// The unmerged record — everything the file's parse found. Public so a
|
||
/// caller that persists those records can store the one an incremental
|
||
/// update just produced without parsing the file a second time
|
||
/// (`docs/features/index-persistence/README.md`).
|
||
pub fn facts_for(&self, path: &Path) -> Option<&FileFacts> {
|
||
let at = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)).ok()?;
|
||
self.facts.get(at)
|
||
}
|
||
|
||
/// The `` `define`` table of one file.
|
||
pub fn defines(&self, file: FileId) -> Option<&DefineTable> {
|
||
self.facts.get(file.0 as usize).map(|facts| &facts.defines)
|
||
}
|
||
|
||
/// Every definition of a macro name anywhere in the workspace, in file
|
||
/// order. **No resolution order is implied**: which one a given use sees
|
||
/// depends on the `` `include`` graph and on `` `ifdef``, neither of which
|
||
/// this index models. A hover showing all of them is honest; picking one
|
||
/// silently would not be.
|
||
pub fn find_define(&self, name: &str) -> Vec<(FileId, &Define)> {
|
||
self.macro_definitions
|
||
.get(name)
|
||
.into_iter()
|
||
.flatten()
|
||
.filter_map(|&(file, entry)| {
|
||
let define = self.facts.get(file.0 as usize)?.defines.entries().get(entry)?;
|
||
Some((file, define))
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// Every indexed use of `def`, excluding its declaration.
|
||
pub fn references_to(&self, def: &Def) -> &[ReferenceSite] {
|
||
self.reference_sites.get(&DefinitionKey::of(def)).map_or(&[], Vec::as_slice)
|
||
}
|
||
|
||
/// Whether at least one use could name `def` or another declaration equally.
|
||
pub fn references_are_ambiguous(&self, def: &Def) -> bool {
|
||
self.ambiguous_references.contains(&DefinitionKey::of(def))
|
||
}
|
||
|
||
/// Every file holding a use spelled `name` that this index had to look
|
||
/// **outside that file** to answer — whether or not it found anything.
|
||
///
|
||
/// [`WorkspaceIndex::references_to`] is keyed by the declaration a use
|
||
/// landed on, so a use that landed on nothing is in no posting at all.
|
||
/// That is the right shape for "who refers to this declaration" and the
|
||
/// wrong shape for "which files would notice if this name suddenly
|
||
/// started meaning something" — the question a rename has to ask about
|
||
/// the name it is renaming *to*, because an `import p::*` of a package
|
||
/// that does not exist yet changes meaning the moment a package `p`
|
||
/// appears. Answered from the per-file records, which keep every external
|
||
/// reference by its spelled name; a resolved one is here too, since a use
|
||
/// that already means something can equally start meaning something else.
|
||
///
|
||
/// A linear walk over the records, in [`FileId`] order and deduplicated:
|
||
/// no source is read and nothing is parsed. See
|
||
/// `docs/features/refactor-rename/README.md` for the rename's use of it
|
||
/// and the measurement.
|
||
pub fn files_spelling(&self, name: &str) -> impl Iterator<Item = FileId> + '_ {
|
||
let name = name.to_string();
|
||
self.facts.iter().enumerate().filter_map(move |(id, facts)| {
|
||
let spelled = facts.references.iter().any(|reference| match reference {
|
||
// A fact with **no paths at all** is not one of these: it is
|
||
// an inherited-member miss, answered only through the base
|
||
// class this file already names, and it is recorded (since
|
||
// round 2, for its index posting) rather than dropped. What
|
||
// `rename`'s fan-out reads here is unchanged by that: the set
|
||
// is still every use whose *paths* the workspace was asked
|
||
// about. See the class-member-access README's Handshakes for
|
||
// the question this leaves open for `rename`.
|
||
ReferenceFact::External { name: spelled, paths, .. } => {
|
||
!paths.is_empty() && *spelled == name
|
||
}
|
||
// A local fact resolved inside its own file, so that file
|
||
// declares the name and every caller already has it.
|
||
ReferenceFact::Local { .. } => false,
|
||
});
|
||
spelled.then_some(FileId(id as u32))
|
||
})
|
||
}
|
||
|
||
/// Every file whose token stream writes the word `name` down anywhere.
|
||
///
|
||
/// The *textual* census, not the resolved one:
|
||
/// [`WorkspaceIndex::files_spelling`] answers from the reference table and
|
||
/// therefore misses every use the index does not resolve — a hierarchical
|
||
/// path whose head is not a local instance (`tb.dut.sig`), a `bind`
|
||
/// connection, a name inside a region that did not parse. This answers
|
||
/// from [`FileFacts::words`], which is read off the tokens, so all of them
|
||
/// are in it. What it cannot do is tell one scope's `count` from
|
||
/// another's: a word is a word. That is the trade the semantic lint rules
|
||
/// take deliberately — see `docs/features/semantic-lints-on/README.md`.
|
||
///
|
||
/// A linear walk over the records, in [`FileId`] order, binary-searching
|
||
/// each file's sorted word list: no source is read and nothing is parsed.
|
||
/// A merged `word → files` map would answer in one lookup instead of
|
||
/// `files × log(words)` comparisons, and was measured against this and
|
||
/// rejected — see the README's "why there is no inverted index".
|
||
pub fn files_mentioning<'a>(&'a self, name: &'a str) -> impl Iterator<Item = FileId> + 'a {
|
||
self.facts
|
||
.iter()
|
||
.enumerate()
|
||
.filter(move |(_, facts)| {
|
||
facts.words.binary_search_by(|w| w.as_str().cmp(name)).is_ok()
|
||
})
|
||
.map(|(id, _)| FileId(id as u32))
|
||
}
|
||
|
||
/// Every file that writes the word `name` inside a macro invocation, a
|
||
/// directive line or an attribute — text lucisv never looked into.
|
||
///
|
||
/// The twin of [`WorkspaceIndex::files_mentioning`], over
|
||
/// [`FileFacts::macro_words`] instead of the union census and by the same
|
||
/// binary search per record. The narrower question, and the one a
|
||
/// refactoring asks: a name here has no reference, no declaration and no
|
||
/// edge, so nothing can edit it and nothing else in the index knows it is
|
||
/// there. A rename that never read the file can still *name* it —
|
||
/// `docs/features/macro-word-census/README.md`.
|
||
///
|
||
/// The answer is a superset of the files a macro *argument* names it in:
|
||
/// a directive line (`` `ifdef sig ``) and an attribute count too, and the
|
||
/// macro's own name is a word. Erring towards saying so is deliberate —
|
||
/// the alternative is silence about text the rename really did leave
|
||
/// behind.
|
||
pub fn files_naming_in_macros<'a>(
|
||
&'a self,
|
||
name: &'a str,
|
||
) -> impl Iterator<Item = FileId> + 'a {
|
||
self.facts
|
||
.iter()
|
||
.enumerate()
|
||
.filter(move |(_, facts)| {
|
||
facts.macro_words.binary_search_by(|w| w.as_str().cmp(name)).is_ok()
|
||
})
|
||
.map(|(id, _)| FileId(id as u32))
|
||
}
|
||
|
||
/// Whether any file **other than** `except` writes the word `name` down.
|
||
///
|
||
/// The question a cross-file lint guard actually asks, answered without
|
||
/// building the whole list: a file's own mention of its own signal is not
|
||
/// evidence that something else uses it.
|
||
pub fn mentioned_outside(&self, name: &str, except: Option<FileId>) -> bool {
|
||
self.files_mentioning(name).any(|file| Some(file) != except)
|
||
}
|
||
|
||
/// Every indexed name containing `query`, case-insensitively — LSP's
|
||
/// `workspace/symbol`. An empty query matches everything; the result is
|
||
/// sorted by name and is not truncated, so a caller with a result limit
|
||
/// applies its own.
|
||
pub fn workspace_symbols(&self, query: &str) -> Vec<WorkspaceSymbol<'_>> {
|
||
let mut out = Vec::new();
|
||
for (name, defs) in &self.units {
|
||
if contains_ignore_ascii_case(name, query) {
|
||
out.extend(defs.iter().map(|def| WorkspaceSymbol { name, container: None, def }));
|
||
}
|
||
}
|
||
for (unit, members) in &self.members {
|
||
for (name, defs) in members {
|
||
if contains_ignore_ascii_case(name, query) {
|
||
out.extend(defs.iter().map(|def| WorkspaceSymbol {
|
||
name,
|
||
container: Some(unit),
|
||
def,
|
||
}));
|
||
}
|
||
}
|
||
}
|
||
out.sort_by(|a, b| {
|
||
(a.name, a.container, a.def.file, a.def.name_span.start).cmp(&(
|
||
b.name,
|
||
b.container,
|
||
b.def.file,
|
||
b.def.name_span.start,
|
||
))
|
||
});
|
||
out
|
||
}
|
||
|
||
/// Every file-scope declaration of one kind, under its name, in name
|
||
/// order.
|
||
///
|
||
/// The cheap half of [`WorkspaceIndex::workspace_symbols`] for a caller
|
||
/// that wants units and never members: it walks the unit table alone and
|
||
/// sorts nothing, where `workspace_symbols("")` walks every member of every
|
||
/// unit and sorts the lot. On opentitan that is 1 544 modules out of
|
||
/// hundreds of thousands of declarations, and the difference is 15 ms per
|
||
/// call (`docs/features/vscode-hierarchy-sidebar/README.md`).
|
||
pub fn units_of(&self, kind: SymbolKind) -> impl Iterator<Item = (&str, &Def)> {
|
||
self.units
|
||
.iter()
|
||
.flat_map(|(name, defs)| defs.iter().map(move |def| (name.as_str(), def)))
|
||
.filter(move |(_, def)| def.kind == kind)
|
||
}
|
||
|
||
/// Every file-scope declaration an instantiation may name — a `module` or
|
||
/// an `interface` — under its name, in name order.
|
||
///
|
||
/// [`WorkspaceIndex::units_of`] with the one filter that is two kinds. An
|
||
/// interface instance is an instantiation edge exactly as a module instance
|
||
/// is, so the design hierarchy, the code lens and the instantiate ghost all
|
||
/// read this rather than spelling the pair for themselves.
|
||
pub fn instantiable_units(&self) -> impl Iterator<Item = (&str, &Def)> {
|
||
self.units
|
||
.iter()
|
||
.flat_map(|(name, defs)| defs.iter().map(move |def| (name.as_str(), def)))
|
||
.filter(|(_, def)| def.kind.is_instantiable())
|
||
}
|
||
|
||
/// How many unit names and member names are indexed.
|
||
pub fn counts(&self) -> IndexCounts {
|
||
IndexCounts {
|
||
files: self.files.len(),
|
||
modules: self.units_of_kind(SymbolKind::Module),
|
||
interfaces: self.units_of_kind(SymbolKind::Interface),
|
||
packages: self.units_of_kind(SymbolKind::Package),
|
||
typedefs: self.units_of_kind(SymbolKind::Typedef),
|
||
classes: self.units_of_kind(SymbolKind::Class)
|
||
+ self
|
||
.members
|
||
.values()
|
||
.flat_map(|m| m.values())
|
||
.flatten()
|
||
.filter(|d| d.kind == SymbolKind::Class)
|
||
.count(),
|
||
members: self.members.values().flat_map(|m| m.values()).map(Vec::len).sum(),
|
||
hierarchical_members: self
|
||
.hier_members
|
||
.values()
|
||
.flat_map(|m| m.values())
|
||
.map(Vec::len)
|
||
.sum(),
|
||
defines: self.facts.iter().map(|f| f.defines.entries().len()).sum(),
|
||
instantiations: self.instantiations.values().map(Vec::len).sum(),
|
||
inheritances: self.subclasses.values().map(Vec::len).sum(),
|
||
}
|
||
}
|
||
|
||
/// How many entries each table holds — [`IndexCounts`] asked by table
|
||
/// rather than by declaration kind.
|
||
pub fn table_sizes(&self) -> IndexTableSizes {
|
||
IndexTableSizes {
|
||
unit_names: self.units.len(),
|
||
unit_defs: self.units.values().map(Vec::len).sum(),
|
||
members: self.members.values().flat_map(|m| m.values()).map(Vec::len).sum(),
|
||
hier_members: self.hier_members.values().flat_map(|m| m.values()).map(Vec::len).sum(),
|
||
reference_keys: self.reference_sites.len(),
|
||
reference_sites: self.reference_sites.values().map(Vec::len).sum(),
|
||
words: self.facts.iter().map(|facts| facts.words().len()).sum(),
|
||
word_bytes: self
|
||
.facts
|
||
.iter()
|
||
.flat_map(|facts| facts.words())
|
||
.map(|word| word.len())
|
||
.sum(),
|
||
}
|
||
}
|
||
|
||
fn units_of_kind(&self, kind: SymbolKind) -> usize {
|
||
self.units.values().flatten().filter(|d| d.kind == kind).count()
|
||
}
|
||
}
|
||
|
||
/// The file list an index will be built from, in the order it is built in:
|
||
/// sorted by path, one entry per path (a path handed over twice is one file,
|
||
/// and the first copy wins).
|
||
///
|
||
/// Exposed because a caller that wants to *watch* a build — the server's
|
||
/// indexing progress bar — has to know the work list, and its length, before
|
||
/// the first file is parsed. Getting that ordering from here rather than
|
||
/// re-deriving it is what keeps a watched build and a plain
|
||
/// [`WorkspaceIndex::build`] the same index in the same order.
|
||
///
|
||
/// Generic in what rides beside the path — a borrowed `&str` for a caller that
|
||
/// holds the texts, an owned `String` for one that is handing them over — so a
|
||
/// scan that owns its work list gets the same ordering from the same function
|
||
/// rather than sorting for itself.
|
||
pub fn index_order<T>(files: impl IntoIterator<Item = (PathBuf, T)>) -> Vec<(PathBuf, T)> {
|
||
let mut sources: Vec<(PathBuf, T)> = files.into_iter().collect();
|
||
sources.sort_by(|a, b| a.0.cmp(&b.0));
|
||
// A path handed over twice is one file; the first copy wins.
|
||
sources.dedup_by(|a, b| a.0 == b.0);
|
||
sources
|
||
}
|
||
|
||
/// A [`WorkspaceIndex`] under construction, one file at a time.
|
||
///
|
||
/// The same work [`WorkspaceIndex::build`] does — that function is a loop over
|
||
/// this one — split so a caller can do something between two files, which in
|
||
/// practice means reporting progress. A file can be added here and nothing
|
||
/// else; replacing or dropping one is [`WorkspaceIndex::update_file`] /
|
||
/// [`WorkspaceIndex::remove_file`], on the finished index.
|
||
///
|
||
/// **The order files are added in cannot change the result.** `add_file`
|
||
/// parses its file and keeps what it declares to itself; `finish` sorts those
|
||
/// per-file records by path — [`index_order`]'s rule, applied where no caller
|
||
/// can bypass it — and only then hands out [`FileId`]s and merges the
|
||
/// declarations. So the file ids, the disambiguation order of a name declared
|
||
/// twice, and every member table are the path order, whoever calls this and in
|
||
/// whatever sequence. (Before 2026-08-27 the ordering was a doc comment asking
|
||
/// callers to feed it [`index_order`]'s list, and a caller who did not silently
|
||
/// got a different index.)
|
||
#[derive(Debug, Clone, Default)]
|
||
pub struct IndexBuilder {
|
||
/// One record per `add_file` call, in call order. Sorted by `finish`.
|
||
files: Vec<FileFacts>,
|
||
}
|
||
|
||
impl IndexBuilder {
|
||
/// An empty index to add files to.
|
||
pub fn new() -> IndexBuilder {
|
||
IndexBuilder::default()
|
||
}
|
||
|
||
/// Parse one file and record what it declares.
|
||
///
|
||
/// The parse happens here, not in `finish`, so a caller reporting progress
|
||
/// between calls is reporting work that has really been done.
|
||
pub fn add_file(&mut self, path: PathBuf, src: &str) {
|
||
self.add_facts(FileFacts::of(path, src));
|
||
}
|
||
|
||
/// Add one file whose facts are already known — restored from a cache
|
||
/// rather than read from the file's text.
|
||
///
|
||
/// Exactly [`IndexBuilder::add_file`] with the parse already done: the
|
||
/// record is what that parse produces, so an index built from records and
|
||
/// an index built from text are the same index. Whether the record really
|
||
/// describes the file is the caller's business, and the caller answers it
|
||
/// by keying its store on the file's content
|
||
/// (`docs/features/index-persistence/README.md`).
|
||
pub fn add_facts(&mut self, facts: FileFacts) {
|
||
self.files.push(facts);
|
||
}
|
||
|
||
/// The finished index: the files sorted by path, then merged.
|
||
///
|
||
/// `sort_by` is stable and `dedup_by` keeps the first of a run, so a path
|
||
/// added twice is one file and the first copy wins — exactly what
|
||
/// [`index_order`] does to the list it is handed.
|
||
pub fn finish(mut self) -> WorkspaceIndex {
|
||
self.files.sort_by(|a, b| a.path.cmp(&b.path));
|
||
self.files.dedup_by(|a, b| a.path == b.path);
|
||
let mut index = WorkspaceIndex {
|
||
files: self.files.iter().map(|facts| facts.path.clone()).collect(),
|
||
facts: self.files,
|
||
..WorkspaceIndex::default()
|
||
};
|
||
index.merge(None);
|
||
index
|
||
}
|
||
}
|
||
|
||
fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
|
||
if needle.is_empty() {
|
||
return true;
|
||
}
|
||
let needle = needle.as_bytes();
|
||
haystack.as_bytes().windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle))
|
||
}
|