Incremental indexing + the edge tables: one file changed, one file merged

Owner-requested round. WorkspaceIndex::update_file/remove_file replace
one file's contribution without reading or parsing anything else;
Server::reindex_one takes the fast path for a didSave of one held file
or a one-file watcher event (33 ms vs 1.5 s on the corpus, 45x), with
everything else — settings, scope, filelist, multi-file events —
keeping the full rebuild, pinned by a trigger-table test. FileIds stay
sorted positions by deliberate deviation: renumbering through the one
merge both finish and update_file end in makes build(W) byte-identical
to build(W minus F).update_file(F) — fingerprint equality, attacked by
QA across long interleaved sequences, disambiguation flips, define
shadowing and the ghost hunt (the affected-keys union reads old and
new records both). The per-file FileFacts the index retains are the
documented memory cost (~1.4 MB on the corpus).

The two oldest filed Handshakes land: instantiation and inheritance
edge tables, built by the byte-for-byte moved census walks, turn
codeLens counts (92 ms to 0.26 ms), incomingCalls and typeHierarchy
subtypes into lookups — census policies pinned unchanged at both the
consumers and now the source. Counts are as of the index, not of
unsaved keystrokes: the freshness delta is documented and pinned from
both sides. Saves no longer raise a progress bar; generation and lens
refresh still ride. Round 18's three inherited scope obligations are
pinned permanent.

36 tests added (dev 27 + QA 9). Left open, filed: wholesale republish,
Candidates re-derivation cost, incremental removal vs include
re-resolution.

docs/features/incremental-index/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-27 14:35:27 -07:00
1 parent 7266b13702
commit 5e4aa7bd6f
26 files changed
+3132 -383

No files matched your search

+17 -4
View File
@@ -491,7 +491,9 @@ later:
typedef names → (file, span) across all workspace files, so header
imports (`import pkg::*;`) and instantiations resolve to definitions
in other files. Start as a full-scan-on-startup index (Verilog
codebases are small); incrementality comes with salsa later.
codebases are small); ~~incrementality comes with salsa later~~ — one file
at a time since 2026-08-27, without salsa
(`docs/features/incremental-index/README.md`).
→ `vlog_semantic::WorkspaceIndex::build(files) `+
`resolve_external(&Semantics, &WorkspaceIndex) -> ExternalResolutions`,
a two-layer design: the index is a full scan (860 corpus files in 0.7 s),
@@ -558,6 +560,12 @@ later:
- [ ] **Salsa-style incrementality — defer.** ruff's `ruff_db` uses salsa;
don't take that dependency until hover/definition across files exists.
Per-file recompute is fine at Verilog file sizes.
**Partly answered without salsa, 2026-08-27**
(`docs/features/incremental-index/README.md`): `WorkspaceIndex::update_file`
replaces one file's contribution and provably gives the index a whole build
would have, so a save costs 33 ms instead of 1.5 s over the corpus. No query
graph and no dependency tracking — the salsa question is still open, and is
still deferred.
- [x] **Release prep.** `LICENSE` (MIT), `CHANGELOG.md` (v0.2.0), version
bumped to 0.2.0 across the workspace and the extension, `tools/release.sh`
(release binaries + `.vsix` + `SHA256SUMS` into a gitignored `dist/`) and
@@ -848,7 +856,10 @@ and are not gaps.
the progress bar comes down, gated on
`workspace.codeLens.refreshSupport`. One request recorded there: an
instantiation-edge table in `WorkspaceIndex` would make both this and
`callHierarchy/incomingCalls` a lookup instead of a workspace walk.
`callHierarchy/incomingCalls` a lookup instead of a workspace walk —
**delivered 2026-08-27, `docs/features/incremental-index/README.md`**:
`instantiations_of` is the table, the walk is gone, and a whole file's
lenses went 92 ms → 0.26 ms over the corpus.
- [x] **On-type formatting** — conspicuous absence for a
formatter-first server; candidate trigger: newline (indent the new
line per block nesting), `;` (reformat the finished statement).
@@ -896,10 +907,12 @@ and are not gaps.
bare name of a parameterized `base #(8)`. A base the workspace does
not index (every UVM chain top) yields no item rather than a guess.
`subtypes` is `hierarchy::callers_of_each`'s census in another key —
one `sources()` pass, substring prefilter, deterministic sort — at
~~one `sources()` pass, substring prefilter, deterministic sort — at
55 ms over the 860-file corpus, 53 ms of it file I/O; the
inheritance-edge table that would make it a lookup is filed beside the
instantiation-edge table §9c's code-lens item already recorded. Two
instantiation-edge table §9c's code-lens item already recorded.~~
**Both tables shipped 2026-08-27** (`docs/features/incremental-index/README.md`):
`subclasses_of` makes `subtypes` a lookup, 55 ms → 0.71 ms. Two
gaps recorded there: `lsp-types` 0.97 has no `typeHierarchyProvider`
field, so the capability is inserted into the serialized `initialize`
result by hand, and `vlog_parser` rejects `interface class`, so
+152 -25
View File
@@ -20,8 +20,8 @@
//! See `docs/features/completion-core/README.md`.
use std::cmp::Ordering;
use std::collections::HashSet;
use std::path::PathBuf;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use vlog_parser::defines::DefineKind;
use vlog_parser::token::TokenKind;
@@ -55,6 +55,14 @@ pub struct Candidates {
units: Vec<Candidate>,
macros: Vec<Macro>,
words: Vec<String>,
/// How many in-scope files contain each word. What makes it possible to
/// take one file's words back without re-lexing every other file
/// ([`Candidates::update_file`]): a word is dropped from `words` exactly
/// when the last file holding it stops holding it.
word_files: HashMap<String, usize>,
/// Each file's distinct words, so the count above can be decremented for
/// the version of the file being replaced.
per_file: HashMap<PathBuf, Vec<String>>,
}
impl Candidates {
@@ -64,7 +72,70 @@ impl Candidates {
/// the index, so the files are read once and the only extra work is one
/// lex per file — see the measurements in the feature README.
pub fn build(index: &WorkspaceIndex, sources: &[(PathBuf, String)]) -> Candidates {
Candidates { units: units_of(index), macros: macros_of(index), words: words_of(sources) }
let mut out = Candidates {
units: units_of(index),
macros: macros_of(index),
..Candidates::default()
};
for (path, text) in sources {
let words = words_in(text);
for word in &words {
*out.word_files.entry(word.clone()).or_default() += 1;
}
if !words.is_empty() {
out.per_file.insert(path.clone(), words);
}
}
out.words = out.word_files.keys().cloned().collect();
sort_by_name(&mut out.words, |w| w.as_str());
out
}
/// Replace one file's contribution — the incremental form of
/// [`Candidates::build`], for a rescan that only one file triggered
/// (`docs/features/incremental-index/README.md`).
///
/// The two index-derived tables are re-derived from the index, which has
/// already been updated and is the only thing they read. The word table is
/// patched: this file's old words are given back and its new ones taken,
/// so nothing else is re-lexed. The result is what a whole
/// [`Candidates::build`] over the same files would have produced.
pub fn update_file(&mut self, index: &WorkspaceIndex, path: &Path, text: &str) {
self.units = units_of(index);
self.macros = macros_of(index);
self.set_words(path, words_in(text));
}
/// Drop one file's contribution entirely.
pub fn remove_file(&mut self, index: &WorkspaceIndex, path: &Path) {
self.units = units_of(index);
self.macros = macros_of(index);
self.set_words(path, Vec::new());
}
/// Make `words` this file's words, adjusting the workspace-wide table.
fn set_words(&mut self, path: &Path, words: Vec<String>) {
for word in self.per_file.remove(path).unwrap_or_default() {
let Some(count) = self.word_files.get_mut(&word) else { continue };
*count -= 1;
if *count == 0 {
self.word_files.remove(&word);
if let Ok(at) = self.words.binary_search_by(|held| word_cmp(held, &word)) {
self.words.remove(at);
}
}
}
for word in &words {
let count = self.word_files.entry(word.clone()).or_default();
*count += 1;
if *count == 1 {
let at = self.words.partition_point(|held| word_cmp(held, word) == Ordering::Less);
self.words.insert(at, word.clone());
}
}
if !words.is_empty() {
self.per_file.insert(path.to_path_buf(), words);
}
}
/// Index names starting with `prefix`, case-insensitively.
@@ -132,27 +203,24 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
out
}
/// Every identifier the in-scope files' token streams contain.
fn words_of(sources: &[(PathBuf, String)]) -> Vec<String> {
// Deduplicated as it is collected, not afterwards: a workspace holds two
// orders of magnitude more identifier *tokens* than distinct identifiers
// (900k against 17k over this repo's corpus), and copying every one of
// them only to sort the copies away costs more than the lexing does.
/// Every distinct identifier one file's token stream contains.
///
/// Deduplicated as it is collected, not afterwards: a workspace holds two
/// orders of magnitude more identifier *tokens* than distinct identifiers
/// (900k against 17k over this repo's corpus), and copying every one of them
/// only to sort the copies away costs more than the lexing does.
fn words_in(text: &str) -> Vec<String> {
// A file that does not lex contributes nothing rather than being guessed
// at with a regex — the same all-or-nothing rule the lexer gives every
// other consumer.
let Ok(tokens) = tokenize(text) else { return Vec::new() };
let mut seen: HashSet<String> = HashSet::new();
for (_, text) in sources {
// A file that does not lex contributes nothing rather than being
// guessed at with a regex — the same all-or-nothing rule the lexer
// gives every other consumer.
let Ok(tokens) = tokenize(text) else { continue };
for token in tokens.iter().filter(|t| is_word(t.kind, &t.text)) {
if !seen.contains(token.text.as_str()) {
seen.insert(token.text.clone());
}
for token in tokens.iter().filter(|t| is_word(t.kind, &t.text)) {
if !seen.contains(token.text.as_str()) {
seen.insert(token.text.clone());
}
}
let mut out: Vec<String> = seen.into_iter().collect();
sort_by_name(&mut out, |w| w.as_str());
out
seen.into_iter().collect()
}
/// Whether a token is a word worth offering.
@@ -174,10 +242,13 @@ fn is_word(kind: TokenKind, text: &str) -> bool {
/// Sort by name, case-insensitively first so [`matching`]'s binary search is
/// valid, then exactly so equal names sit next to each other for `dedup`.
fn sort_by_name<T>(items: &mut [T], name: impl for<'b> Fn(&'b T) -> &'b str) {
items.sort_by(|a, b| {
let (a, b) = (name(a), name(b));
lower_cmp(a, b).then_with(|| a.cmp(b))
});
items.sort_by(|a, b| word_cmp(name(a), name(b)));
}
/// The order [`sort_by_name`] puts names in, named so an incremental insert
/// can find the one place a whole sort would have put a word.
fn word_cmp(a: &str, b: &str) -> Ordering {
lower_cmp(a, b).then_with(|| a.cmp(b))
}
/// The entries whose name starts with `prefix`, case-insensitively.
@@ -324,4 +395,60 @@ mod tests {
assert!(names.contains(&"seen"), "{names:?}");
assert!(!names.contains(&"never_seen"), "{names:?}");
}
// ------------------------------------------------------------------
// QA (incremental-index, 2026-08-27): `word_files`'s exact bookkeeping
// ------------------------------------------------------------------
#[test]
fn a_shared_word_dropped_from_one_file_is_still_offered_by_the_other() {
let raw = [
("/rtl/a.sv", "module a;\n logic shared;\nendmodule\n"),
("/rtl/b.sv", "module b;\n logic shared;\nendmodule\n"),
];
let srcs = sources(&raw);
let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
let mut candidates = Candidates::build(&index, &srcs);
assert_eq!(candidates.words("shared").len(), 1, "premise: two files, one word");
let mut current = index.clone();
current.update_file(PathBuf::from("/rtl/a.sv"), "module a;\nendmodule\n");
candidates.update_file(&current, Path::new("/rtl/a.sv"), "module a;\nendmodule\n");
assert_eq!(candidates.words("shared").len(), 1, "b.sv still holds it — not given back");
current.update_file(PathBuf::from("/rtl/b.sv"), "module b;\nendmodule\n");
candidates.update_file(&current, Path::new("/rtl/b.sv"), "module b;\nendmodule\n");
assert!(candidates.words("shared").is_empty(), "and now nothing holds it");
}
#[test]
fn updating_the_same_file_twice_in_a_row_never_double_counts_or_goes_negative() {
// `set_words` decrements the *previous* call's words before counting
// the new ones; the attack is a bug that decrements the same word
// twice (an underflow — `usize` would panic in debug, wrap in
// release) or forgets to re-add a word that survives across the two
// calls.
let raw = [("/rtl/a.sv", "module a;\n logic w1;\nendmodule\n")];
let srcs = sources(&raw);
let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
let mut candidates = Candidates::build(&index, &srcs);
let mut current = index.clone();
let text2 = "module a;\n logic w2;\nendmodule\n";
current.update_file(PathBuf::from("/rtl/a.sv"), text2);
candidates.update_file(&current, Path::new("/rtl/a.sv"), text2);
assert!(candidates.words("w1").is_empty(), "w1 given back");
assert_eq!(candidates.words("w2").len(), 1);
// The same update again, unchanged text.
candidates.update_file(&current, Path::new("/rtl/a.sv"), text2);
assert!(candidates.words("w1").is_empty(), "still gone, not somehow negative-then-absent");
assert_eq!(candidates.words("w2").len(), 1, "still exactly one, not doubled");
// `remove_file`, twice in a row.
candidates.remove_file(&current, Path::new("/rtl/a.sv"));
assert!(candidates.words("w2").is_empty());
candidates.remove_file(&current, Path::new("/rtl/a.sv"));
assert!(candidates.words("w2").is_empty(), "removing an already-removed file is a no-op");
}
}
+92 -60
View File
@@ -24,8 +24,10 @@ use vlog_parser::ast::Item;
use vlog_parser::{parse_source_tolerant, LineIndex, TextRange};
use vlog_semantic::SymbolKind as SemanticKind;
use vlog_semantic::instantiations::{self, Decl};
use vlog_semantic::{DeclSite, InstantiationEdge};
use crate::convert::Positions;
use crate::instantiations::{self, Decl, Site};
use crate::state::Workspace;
use crate::uri::{path_to_uri, uri_to_path};
@@ -69,41 +71,49 @@ pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyIn
/// Who instantiates each of `names`, answered one list per name in the order
/// asked.
///
/// Every in-scope file is walked, because the workspace index records what a
/// file *declares* and not what it instantiates — there is no edge table to
/// consult. A file whose text contains none of the names is skipped before it
/// is parsed, which is what keeps the walk affordable: an instantiation of
/// `fifo` has to write `fifo`.
/// **A lookup in the workspace index's instantiation-edge table** since
/// 2026-08-27, where it used to be a re-read and re-parse of every in-scope
/// file. The census is unchanged — the table is built by the same
/// [`instantiations::sites`] walk this function used to run, at index time
/// (`docs/features/incremental-index/README.md`) — and so is the answer's
/// shape and order. What changed is the cost: only the files that really do
/// instantiate one of the names are read, to turn the recorded byte spans into
/// the protocol's line/character ranges.
///
/// The **batch** is the primitive rather than the single name because
/// [`Workspace::sources`] re-reads every in-scope file: one question per name
/// would re-read the whole workspace once per name, and `lens.rs` asks about
/// every module declared in a buffer at once. A file is parsed once for the
/// whole batch.
/// The **batch** stays the primitive: `lens.rs` asks about every module
/// declared in a buffer at once, and one file that instantiates three of them
/// is read once for the batch rather than once per name.
///
/// An empty name is answered with nothing rather than searched for: nothing
/// this server hands out is nameless, and the prefilter matches every file for
/// one, which would parse the whole workspace to find nothing.
/// An empty name is answered with nothing rather than looked up: nothing this
/// server hands out is nameless, and a nameless question has no answer.
pub fn callers_of_each(ws: &Workspace, names: &[&str]) -> Vec<Vec<CallHierarchyIncomingCall>> {
let index = ws.index();
let mut answers: Vec<Vec<CallHierarchyIncomingCall>> =
names.iter().map(|_| Vec::new()).collect();
for (path, text) in ws.sources() {
let wanted: Vec<usize> = names
.iter()
.enumerate()
.filter(|(_, name)| !name.is_empty() && text.contains(**name))
.map(|(index, _)| index)
.collect();
if wanted.is_empty() {
continue;
}
let Some(uri) = path_to_uri(&path) else { continue };
let (tree, _) = parse_source_tolerant(&text);
let sites = instantiations::sites(&tree.items);
// Every file holding an edge for any of the names, once, in path order.
let mut files: Vec<vlog_semantic::FileId> = names
.iter()
.filter(|name| !name.is_empty())
.flat_map(|name| index.instantiations_of(name).iter().map(|edge| edge.file))
.collect();
files.sort();
files.dedup();
for file in files {
let Some(path) = index.path(file) else { continue };
let Some(uri) = path_to_uri(path) else { continue };
// The spans were recorded against the text the index was built from;
// this is the text now. The two differ only for a buffer edited since
// the last rebuild, which is the same staleness `item_in_file` has
// always carried.
let Some(text) = ws.text_of(path) else { continue };
let line_index = LineIndex::new(&text);
let positions = Positions::new(&text, &line_index);
for index in wanted {
answers[index].extend(callers_in(&uri, &positions, &sites, names[index]));
for (at, name) in names.iter().enumerate() {
if name.is_empty() {
continue;
}
let edges = index.instantiations_of(name).iter().filter(|edge| edge.file == file);
answers[at].extend(callers_in(&uri, &positions, edges));
}
}
for answer in &mut answers {
@@ -152,31 +162,29 @@ pub fn outgoing(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyOu
.collect()
}
/// Every module in one already-parsed file that instantiates `name`, with its
/// sites.
/// One file's edges for one module, as incoming calls: one call per
/// instantiating module, with every site inside it.
///
/// Sites are grouped by the declaration they sit in rather than by adjacency,
/// because a module written inside another can put its own sites between two
/// of the outer module's.
fn callers_in<'a>(
uri: &Uri,
positions: &Positions,
sites: &[Site<'a>],
name: &str,
edges: impl Iterator<Item = &'a InstantiationEdge>,
) -> Vec<CallHierarchyIncomingCall> {
let mut callers: Vec<(Decl<'a>, Vec<TextRange>)> = Vec::new();
for site in sites {
if site.inst.module != name {
continue;
}
// An instantiation at file scope has no calling module to report.
let Some(owner) = site.owner else { continue };
match callers.iter_mut().find(|(decl, _)| decl.span == owner.span) {
Some((_, spans)) => spans.push(site.inst.module_span),
None => callers.push((owner, vec![site.inst.module_span])),
let mut callers: Vec<(&DeclSite, Vec<TextRange>)> = Vec::new();
for edge in edges {
match callers.iter_mut().find(|(owner, _)| owner.span == edge.owner.span) {
Some((_, spans)) => spans.push(edge.site_span),
None => callers.push((&edge.owner, vec![edge.site_span])),
}
}
callers
.into_iter()
.filter_map(|(decl, spans)| {
.filter_map(|(owner, spans)| {
Some(CallHierarchyIncomingCall {
from: item(uri.clone(), positions, decl)?,
from: item_of(uri.clone(), positions, &owner.name, owner.name_span, owner.span)?,
from_ranges: spans.into_iter().map(|span| positions.range(span)).collect(),
})
})
@@ -186,20 +194,28 @@ fn callers_in<'a>(
/// The hierarchy item for one module declaration, positioned against the text
/// it was parsed from.
fn item(uri: Uri, positions: &Positions, decl: Decl) -> Option<CallHierarchyItem> {
let name_span = decl.module.name_span;
item_of(uri, positions, &decl.module.name, decl.module.name_span, decl.span)
}
/// [`item`] from the parts, for a caller reading them out of the index's edge
/// table rather than off a parse tree.
fn item_of(
uri: Uri,
positions: &Positions,
name: &str,
name_span: TextRange,
span: TextRange,
) -> Option<CallHierarchyItem> {
if name_span.is_empty() {
return None;
}
// The protocol requires `selectionRange` inside `range`; a declaration the
// parser could not close is the case where that may not hold, and there
// the name alone is the honest extent.
let full = if decl.span.start <= name_span.start && name_span.end <= decl.span.end {
decl.span
} else {
name_span
};
let full =
if span.start <= name_span.start && name_span.end <= span.end { span } else { name_span };
Some(CallHierarchyItem {
name: decl.module.name.clone(),
name: name.to_string(),
kind: SymbolKind::MODULE,
tags: None,
detail: None,
@@ -536,9 +552,15 @@ endmodule
}
#[test]
fn an_unsaved_instantiation_is_a_caller_before_it_is_saved() {
// The sources a walk reads are the open buffers overlaid on disk, so a
// just-typed instantiation counts.
fn an_edited_buffers_instantiation_counts_from_the_moment_the_index_sees_it() {
// Superseded this round (incremental-index, 2026-08-27):
// `an_unsaved_instantiation_is_a_caller_before_it_is_saved` pinned the
// census reading `Workspace::sources()` on every request, so a
// keystroke in *another* buffer moved the count before anything
// rebuilt. The census is the index's edge table now, and an index is
// only ever as of its last build or update — which does fold every
// open buffer in, so a save (or any other rescan trigger) makes the
// edit count. The rule the test pins is the new one, from both sides.
let (tree, mut ws, uri) = three("unsaved");
let root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone();
assert_eq!(incoming(&ws, &root).len(), 2, "premise");
@@ -546,7 +568,14 @@ endmodule
let fresh = tree.path.join("other.sv");
let other_uri = path_to_uri(&fresh).expect("uri");
ws.set_document(other_uri, "module other;\nendmodule\n".to_string());
assert_eq!(incoming(&ws, &root).len(), 1, "the buffer removed its instantiation");
assert_eq!(
incoming(&ws, &root).len(),
2,
"the buffer alone does not move the census — the index has not seen it"
);
// What a save does, and what the incremental path does with it.
assert!(ws.update_one(&fresh), "the file is in scope, so one file is enough");
assert_eq!(incoming(&ws, &root).len(), 1, "the edit removed its instantiation");
}
// ------------------------------------------------------------------
@@ -935,10 +964,13 @@ endmodule
#[test]
#[ignore]
fn qa_perf_worst_case_common_word_module_name() {
// A single-letter module name is a substring of nearly every file's
// text, so the prefilter admits nearly everything — the worst case
// the prefilter can face. Measures whether that worst case is still
// sane, not a specific number.
// A single-letter module name used to be the worst case there was: it
// is a substring of nearly every file, so the prefilter over
// `Workspace::sources()` admitted nearly everything. There is no
// prefilter and no walk since 2026-08-27 — the census is a lookup in
// the index's edge table, and a name nothing instantiates is an empty
// slice — so this probe is kept for what it now measures: that the
// shape which used to be the worst case is not a case at all.
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
+55 -21
View File
@@ -84,9 +84,9 @@ fn include_on_line(line: &str, base: u32) -> Option<Include> {
/// Where `` `include``s are looked for, and which file includes which.
///
/// Rebuilt whole on every index rebuild, from the same source list: includes
/// are a handful of lines per file, so there is nothing here worth updating
/// incrementally.
/// Rebuilt whole on every index rebuild, from the same source list — and
/// patched one file at a time when only one file's text moved
/// ([`IncludeGraph::update_file`]).
#[derive(Debug, Default, Clone)]
pub struct IncludeGraph {
/// The `+incdir+` directories of the configured filelist, in filelist
@@ -104,24 +104,11 @@ pub struct IncludeGraph {
impl IncludeGraph {
/// Scan every in-scope file for its `` `include``s and resolve them.
pub fn build(sources: &[(PathBuf, String)], incdirs: Vec<PathBuf>) -> IncludeGraph {
let mut graph = IncludeGraph {
incdirs,
edges: HashMap::new(),
known: sources.iter().map(|(path, _)| path.clone()).collect(),
folded: HashMap::new(),
};
// Built before the edges: `resolve` consults it, and an edge resolved
// against a half-filled table would be keyed inconsistently.
for (path, _) in sources {
let Some(key) = path.to_str().map(str::to_lowercase) else { continue };
graph
.folded
.entry(key)
// A second file with the same folded spelling makes the
// spelling ambiguous, and an ambiguous one decides nothing.
.and_modify(|found| *found = None)
.or_insert_with(|| Some(path.clone()));
}
let mut graph = IncludeGraph { incdirs, ..IncludeGraph::default() };
// Learned before the edges: `resolve` consults both tables, and an edge
// resolved against a half-filled one would be keyed inconsistently.
let paths: Vec<PathBuf> = sources.iter().map(|(path, _)| path.clone()).collect();
graph.relearn(&paths);
for (path, text) in sources {
let targets: Vec<PathBuf> = scan(text)
.iter()
@@ -134,6 +121,53 @@ impl IncludeGraph {
graph
}
/// Re-scan one file's `` `include``s, the rest of the graph left standing.
///
/// `known` is the index's file list as it stands *after* the update, which
/// is what the known-file and folded-spelling tables are: cheap to rebuild
/// from a list already in memory, and wrong to leave stale when a file has
/// come or gone.
///
/// One honest limit, and the reason the incremental path in `state.rs`
/// takes it only for a file that already existed: an edge of a *different*
/// file is not re-resolved. So a file appearing or vanishing does not
/// change whether some other file's `` `include "x.svh"`` resolves until
/// the next whole rebuild. For the case this is used in — one file's text
/// changed, the file set did not — there is nothing stale at all.
pub fn update_file(&mut self, path: &Path, text: &str, known: &[PathBuf]) {
self.relearn(known);
let targets: Vec<PathBuf> =
scan(text).iter().filter_map(|include| self.resolve(Some(path), include)).collect();
match targets.is_empty() {
true => self.edges.remove(path),
false => self.edges.insert(path.to_path_buf(), targets),
};
}
/// Drop one file from the graph: its own edges, and its place among the
/// known files.
pub fn remove_file(&mut self, path: &Path, known: &[PathBuf]) {
self.relearn(known);
self.edges.remove(path);
}
/// Re-derive the known-file set and the folded-spelling table from the
/// index's file list. The same two loops [`IncludeGraph::build`] runs, over
/// paths rather than over `(path, text)` pairs.
fn relearn(&mut self, known: &[PathBuf]) {
self.known = known.iter().cloned().collect();
self.folded.clear();
for path in known {
let Some(key) = path.to_str().map(str::to_lowercase) else { continue };
self.folded
.entry(key)
// A second file with the same folded spelling makes the
// spelling ambiguous, and an ambiguous one decides nothing.
.and_modify(|found| *found = None)
.or_insert_with(|| Some(path.clone()));
}
}
/// The `+incdir+` directories an include is looked for in, in filelist
/// order — the search rungs past the including file's own directory.
pub fn incdirs(&self) -> &[PathBuf] {
+1 -1
View File
@@ -25,9 +25,9 @@ use lsp_types::{InlayHint, InlayHintKind, InlayHintLabel, Range, Uri};
use vlog_parser::ast::{Connections, Expr, Instance, Instantiation};
use vlog_parser::TextRange;
use vlog_refactor::InstantiationPlan;
use vlog_semantic::instantiations;
use crate::convert::Positions;
use crate::instantiations;
use crate::state::Workspace;
/// The ghost labels for one range of a buffer.
+75 -11
View File
@@ -25,8 +25,10 @@
use lsp_types::{CodeLens, Command, Location, Uri};
use serde_json::Value;
use vlog_semantic::instantiations;
use crate::hierarchy;
use crate::state::Workspace;
use crate::{hierarchy, instantiations};
/// Show every instantiation of a module: `[module-name]`.
pub const SHOW_INSTANTIATIONS: &str = "lucisv.showInstantiations";
@@ -639,17 +641,73 @@ endmodule
// the performance claim, measured
// ------------------------------------------------------------------
/// What a whole file's lenses cost over the real corpus, and — the point
/// of the batch — that asking about three modules at once costs about what
/// asking about one does, not three times as much.
/// The number the round's Handshake was filed for, measured: what a whole
/// file's lenses cost before the edge table (a walk of every in-scope
/// file, re-read and re-parsed) and what they cost after (a lookup).
///
/// `#[ignore]`d like the other measurement probes in this crate — it prints
/// a number rather than asserting one, and the assertion that must hold is
/// `code_lenses_for_a_whole_file_cost_a_fraction_of_a_workspace_walk`
/// above. Run with `cargo test -p lucisv_server -- --ignored --nocapture`.
#[test]
#[ignore]
fn qa_perf_lens_lookup_against_the_walk_it_replaced() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let file = corpus.join("common_cells/src/cdc_fifo_gray.sv");
let Ok(text) = fs::read_to_string(&file) else {
eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping");
return;
};
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text);
let _ = code_lenses(&ws, &uri);
let mut lenses = std::time::Duration::ZERO;
let mut walk = std::time::Duration::ZERO;
for _ in 0..3 {
let started = std::time::Instant::now();
let _ = code_lenses(&ws, &uri).expect("open");
lenses = lenses.max(started.elapsed());
// What `callers_of_each` used to begin with, every request.
let started = std::time::Instant::now();
let _ = ws.sources();
walk = walk.max(started.elapsed());
}
eprintln!(
"codeLens over {} files: {lenses:?} for the whole file; one workspace walk \
(what the old census re-read on every request) is {walk:?}",
ws.index().files().len()
);
}
/// What a whole file's lenses cost over the real corpus, against what one
/// workspace walk costs.
///
/// **Superseded this round (incremental-index, 2026-08-27):**
/// `code_lenses_for_a_whole_file_cost_about_one_workspace_walk` asserted
/// `whole_file < one_name * 2` — that asking about three modules cost about
/// what asking about one did, because both were *one walk* of the whole
/// workspace. There is no walk any more: the count is a lookup in the
/// index's instantiation-edge table, and the only I/O left is reading the
/// handful of files that really do instantiate one of the three. Both sides
/// of that ratio are now microseconds dominated by a file read each, so the
/// ratio pins noise. The property worth pinning is the stronger one this
/// round bought: **a whole file's lenses cost a small fraction of one
/// workspace walk**, measured here rather than asserted.
///
/// Skipped when `corpus/` is not checked out (`tools/corpus_fetch.sh`),
/// like the other corpus tests. The budget is deliberately loose: a debug
/// build on a loaded machine is the worst case this ever runs in, and this
/// exists to catch an order-of-magnitude regression — a lens handler that
/// re-read the workspace once per declaration would fail the ratio.
/// went back to re-reading the workspace would fail it by two.
#[test]
fn code_lenses_for_a_whole_file_cost_about_one_workspace_walk() {
fn code_lenses_for_a_whole_file_cost_a_fraction_of_a_workspace_walk() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
@@ -667,10 +725,13 @@ endmodule
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text);
// Warm, then the worst of three, for the whole file and for one name.
// Warm, then the worst of three, for the whole file and for one name;
// and the best of three for the walk it used to be, so the comparison
// is stacked against the claim rather than for it.
let _ = code_lenses(&ws, &uri);
let mut whole_file = std::time::Duration::ZERO;
let mut one_name = std::time::Duration::ZERO;
let mut walk = std::time::Duration::MAX;
let mut count = 0;
for _ in 0..3 {
let started = std::time::Instant::now();
@@ -680,18 +741,21 @@ endmodule
let started = std::time::Instant::now();
let _ = sites_of(&ws, "cdc_fifo_gray");
one_name = one_name.max(started.elapsed());
let started = std::time::Instant::now();
let _ = ws.sources();
walk = walk.min(started.elapsed());
}
eprintln!(
"corpus: {} files, {count} lenses for cdc_fifo_gray.sv in {whole_file:?} \
(one name alone: {one_name:?})",
(one name alone: {one_name:?}; one workspace walk: {walk:?})",
ws.index().files().len(),
);
assert!(count >= 3, "the file declares three modules: {count}");
assert!(whole_file < std::time::Duration::from_millis(1500), "lenses cost {whole_file:?}");
assert!(
whole_file < one_name * 2,
"the batch is one walk, not one per module: {count} names cost {whole_file:?} \
against {one_name:?} for one"
whole_file * 10 < walk,
"the lens is a lookup, not a walk: {count} names cost {whole_file:?} against \
{walk:?} for one walk of the workspace"
);
}
}
-1
View File
@@ -20,7 +20,6 @@ mod hover;
mod includes;
mod inlay;
mod inline;
mod instantiations;
mod lens;
mod linked;
mod lint;
+290 -40
View File
@@ -1090,7 +1090,15 @@ impl Server {
// others are a change to `lucisv.exclude`/`lucisv.filelist`
// below, and a watched file changing on disk. The
// staleness window that is left is in the feature README.
self.reindex();
//
// A save names exactly one file, which is the case the
// index can replace in place — so this is where the
// incremental path earns its keep, and the whole rebuild is
// the fallback for a file the index does not already hold.
let one = crate::uri::uri_to_path(&p.text_document.uri);
if !one.is_some_and(|path| self.reindex_one(path.as_path())) {
self.reindex();
}
}
}
// Something changed on disk that no buffer told us about — a `git
@@ -1101,7 +1109,13 @@ impl Server {
if let Ok(p) = extract::<DidChangeWatchedFilesParams>(notification) {
let filelist = self.workspace.filelist_path();
if watch::touches_scope(&p.changes, filelist.as_deref()) {
self.reindex();
// One file named is the incremental case; a checkout
// filling the list, or the filelist itself moving, is
// the whole rebuild.
let one = watch::one_scope_file(&p.changes, filelist.as_deref());
if !one.is_some_and(|path| self.reindex_one(path.as_path())) {
self.reindex();
}
}
}
}
@@ -1336,6 +1350,42 @@ impl Server {
}
}
/// [`Server::reindex`] for a trigger that named exactly **one** file, when
/// that file is one the index already holds. Reports whether it ran; a
/// `false` means the caller owes a whole rebuild.
///
/// Everything a rebuild does *after* the scan happens here too, for the
/// same reasons: the code-lens refresh (the file that moved may have
/// changed an instantiation count in any buffer), the diagnostics
/// generation bump (every open buffer's diagnostics are computed against
/// the index), and a republish of every open buffer. The republish stays
/// wholesale rather than narrowing to the buffers that could have moved:
/// a lint reads the index, so any buffer's diagnostics may have changed,
/// and narrowing it correctly needs a dependency graph this server does not
/// have. Worth doing later; wrong to guess at now.
///
/// Three things a whole rebuild does that this deliberately does not:
///
/// * **no progress bar.** The bar exists because a whole scan takes
/// perceptible seconds on a large workspace; one file is one parse, and a
/// bar that appears and vanishes inside a frame is noise, not progress.
/// * **no per-file log line.** Same reason, and the log's purpose — "which
/// files is this scan reading?" — is a question about a scan.
/// * **no scope warnings.** They come from *resolving* the scope, and the
/// scope was not re-resolved: nothing about which files exist changed, so
/// repeating a filelist's complaints would be repeating stale news.
fn reindex_one(&mut self, path: &Path) -> bool {
if !self.workspace.update_one(path) {
return false;
}
self.refresh_code_lenses();
self.generation += 1;
for uri in self.workspace.open_uris() {
self.publish(&uri);
}
true
}
/// Rescan the workspace and republish every open buffer against the new
/// index. Every caller changed what the index should contain — a save, a
/// new `lucisv.exclude`/`lucisv.filelist`, a watched file changing on disk,
@@ -2169,10 +2219,206 @@ mod tests {
}
#[test]
fn a_save_puts_a_bar_up_and_takes_it_down_again() {
fn a_whole_rescan_puts_a_bar_up_and_takes_it_down_again() {
// Superseded this round (incremental-index, 2026-08-27):
// `a_save_puts_a_bar_up_and_takes_it_down_again` pinned the bar on a
// save, and a save of a file the index already holds is now one parse
// on the incremental path — see
// `a_one_file_save_costs_no_bar_and_no_log_line` below. The bar's own
// rule is unchanged and is pinned here on a trigger that really does
// rescan: two files changing at once.
let tree = Tree::new("progresssave");
tree.package("rtl/a.sv", "a");
tree.package("rtl/b.sv", "b");
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
let _ = session.drain();
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
// One create, one begin, one report per file, one end — the rescan's
// own token, not the startup one.
assert_eq!(
session.progress(),
vec![
("create", "lucisv-index-1".to_string()),
("begin", "lucisv-index-1".to_string()),
("report", "lucisv-index-1".to_string()),
("report", "lucisv-index-1".to_string()),
("end", "lucisv-index-1".to_string()),
]
);
}
#[test]
fn the_fast_path_is_taken_for_one_held_file_and_for_nothing_else() {
// The trigger table, all four rows in one place. The bar is the tell:
// a whole rescan puts one up, the incremental path never does.
let tree = Tree::new("fastpathtable");
tree.package("rtl/a.sv", "a");
tree.package("rtl/b.sv", "b");
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
let uri = session
.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
let _ = session.drain();
// 1. A save naming one file the index holds — incremental.
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
assert!(session.progress().is_empty(), "one held file on a save is incremental");
// 2. One watched file — incremental too, same rule.
session.watched(&[tree.path.join("rtl/a.sv")]);
assert!(session.progress().is_empty(), "and one watched file is the same case");
// 3. Two files in one watcher event — the whole rescan.
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
assert!(!session.progress().is_empty(), "two files is a rescan");
// 4. A settings change that moves which files exist — the whole
// rescan, whatever it names.
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "exclude": ["rtl/b.sv"], "index": { "scope": "workspace" } } } }),
);
assert!(!session.progress().is_empty(), "a settings change is a rescan");
// 5. A save naming a file the index does not hold — the whole rescan,
// which is how a new file gets in at all.
let fresh = tree.path.join("rtl/c.sv");
tree.package("rtl/c.sv", "c");
let fresh_uri = crate::uri::path_to_uri(&fresh).expect("uri");
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": fresh_uri } }),
);
assert!(!session.progress().is_empty(), "a file the index does not hold is a rescan");
assert_eq!(indexed(&session, "c"), 1, "and the new file is in the index after it");
}
/// QA (incremental-index, 2026-08-27): the fast-path discipline under a
/// burst. `process_batch` handles one message at a time
/// (`for message in batch`), so two `didSave`s that arrive in the same
/// burst are not coalesced into one rescan — each is its own notification,
/// each independently names one held file, and each takes the incremental
/// path on its own. Not a rebuild, and not a dropped update either.
#[test]
fn two_saves_of_different_held_files_in_one_batch_are_two_incremental_updates() {
let tree = Tree::new("batchtwosaves");
tree.write("a.sv", "module a;\nendmodule\n");
tree.write("sub.sv", "module sub;\nendmodule\n");
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
let uri_a = session.open(&tree.path.join("a.sv"), "module a;\nendmodule\n");
let uri_sub = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let _ = session.drain();
let before = session.server.generation;
let a_with_sub = "module a;\n sub u1 ();\nendmodule\n";
let sub_v2 = "module sub;\n logic marker;\nendmodule\n";
let save = |uri: &Uri, text: &str| {
Message::Notification(Notification::new(
DidSaveTextDocument::METHOD.to_string(),
serde_json::json!({ "textDocument": { "uri": uri }, "text": text }),
))
};
session.batch(vec![save(&uri_a, a_with_sub), save(&uri_sub, sub_v2)]);
assert!(session.progress().is_empty(), "neither save alone is a whole rescan");
// Each save bumps the generation twice — once in `set_document` for
// the buffer's own new text (every text change does that, save or
// not), once in `reindex_one` for the fast-path update — so two saves
// is four, not two and not one shared bump for the whole batch.
assert_eq!(
session.server.generation,
before + 4,
"two independent fast-path updates, not one bump shared by the batch"
);
assert_eq!(
session.server.workspace.index().instantiations_of("sub").len(),
1,
"a.sv's edit reached the index"
);
assert_eq!(
session.server.workspace.candidates().words("marker").len(),
1,
"sub.sv's own edit reached the index too, not just a.sv's"
);
}
#[test]
fn a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses() {
// Everything the fast path keeps: a pulling client's cached
// diagnostics are stale from here, and every lens a client is holding
// may now read a different count.
let tree = lens_tree("fastpathafter");
let abilities = ClientAbilities { code_lens_refresh: true, ..Default::default() };
let mut session = Session::with(vec![tree.path.clone()], abilities);
let uri = session.open(
&tree.path.join("top.sv"),
"module top;\n sub u_a ();\n sub u_b ();\nendmodule\n",
);
let _ = session.drain();
let before = session.server.generation;
let one_site = "module top;\n sub u_a ();\nendmodule\n";
std::fs::write(tree.path.join("top.sv"), one_site).expect("write");
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri }, "text": one_site }),
);
assert!(session.server.generation > before, "the generation moved");
let refreshes = session
.sent()
.iter()
.filter(|request| request.method == CodeLensRefresh::METHOD)
.count();
assert_eq!(refreshes, 1, "one refresh, as a whole rescan sends");
}
#[test]
fn a_one_file_save_answers_from_the_file_it_saved() {
// The point of the whole path: one file's edit really does reach the
// index, and the rest of the workspace really is left alone.
let tree = lens_tree("fastpathanswer");
let mut session = Session::new(vec![tree.path.clone()], false);
let two_sites = "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n";
let uri = session.open(&tree.path.join("top.sv"), two_sites);
let _ = session.drain();
assert_eq!(
session.server.workspace.index().instantiations_of("sub").len(),
2,
"premise: top.sv instantiates `sub` twice"
);
let emptied = "module top;\nendmodule\n";
std::fs::write(tree.path.join("top.sv"), emptied).expect("write");
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri }, "text": emptied }),
);
assert!(
session.server.workspace.index().instantiations_of("sub").is_empty(),
"the saved file's edges are gone"
);
assert_eq!(
session.server.workspace.index().units("sub").len(),
1,
"and sub.sv, which nothing named, is untouched"
);
}
#[test]
fn a_one_file_save_costs_no_bar_and_no_log_line() {
// The fast path's whole visible protocol delta: a save that names one
// file the index already holds does its work inside a frame, so there
// is no bar to put up and no scan to narrate. What it does still do —
// the generation bump and the code-lens refresh — is pinned by
// `a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses`.
let tree = Tree::new("progressonefile");
tree.package("rtl/a.sv", "a");
let abilities = ClientAbilities { work_done_progress: true, ..Default::default() };
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
let _ = session.drain();
@@ -2180,17 +2426,8 @@ mod tests {
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
// One create, one begin, one report per file, one end — the save's own
// token, not the startup one.
assert_eq!(
session.progress(),
vec![
("create", "lucisv-index-1".to_string()),
("begin", "lucisv-index-1".to_string()),
("report", "lucisv-index-1".to_string()),
("end", "lucisv-index-1".to_string()),
]
);
assert!(session.progress().is_empty(), "one file is not a scan to report");
assert!(session.logged().is_empty(), "and not a scan to narrate either");
}
#[test]
@@ -2281,14 +2518,14 @@ mod tests {
// user already pays on every keystroke.
let tree = Tree::new("progressorder");
tree.package("rtl/a.sv", "a");
tree.package("rtl/b.sv", "b");
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
let _ = session.drain();
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
// Two files at once, so this is a whole rescan and there is a bar to
// order the republish against (incremental-index, 2026-08-27).
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
let order: Vec<String> = session
.drain()
.into_iter()
@@ -2299,7 +2536,7 @@ mod tests {
_ => progress_step(message).map(|(step, _)| step.to_string()),
})
.collect();
assert_eq!(order, vec!["create", "begin", "report", "end", "publish"]);
assert_eq!(order, vec!["create", "begin", "report", "report", "end", "publish"]);
}
/// A tree with one file the default cap would keep and one it would not.
@@ -2534,13 +2771,13 @@ mod tests {
tree.package("rtl/m_open.sv", "m_open");
tree.package("rtl/z_last.sv", "z_last");
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
let uri = session.open(&tree.path.join("rtl/m_open.sv"), "package m_open;\nendpackage\n");
session.open(&tree.path.join("rtl/m_open.sv"), "package m_open;\nendpackage\n");
let _ = session.drain();
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
// A whole rescan, since that is what has a bar to name files on: a
// save of one held file takes the incremental path now
// (incremental-index, 2026-08-27).
session.watched(&[tree.path.join("rtl/a_first.sv"), tree.path.join("rtl/z_last.sv")]);
let named: Vec<Option<String>> =
session.reported().into_iter().map(|(message, _)| message).collect();
assert_eq!(
@@ -2577,20 +2814,28 @@ mod tests {
#[test]
fn every_rescan_path_gets_its_own_bar_and_its_own_token() {
// The three non-startup callers of `reindex`: a save, a watched file,
// and a changed scope. One begin/end pair each, and no token twice.
// The three non-startup callers of the *whole* `reindex`: a save of a
// file the index does not hold, a watcher event naming more than one
// file, and a changed scope. One begin/end pair each, and no token
// twice. (Superseded this round: the first two used to be a plain save
// and a one-file watcher event, both of which take the incremental
// path now and put no bar up at all.)
let tree = Tree::new("progresspaths");
tree.package("rtl/a.sv", "a");
tree.package("rtl/b.sv", "b");
tree.write("files.f", "rtl/a.sv\n");
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
let _ = session.drain();
let fresh = tree.path.join("rtl/c.sv");
tree.package("rtl/c.sv", "c");
let fresh_uri = crate::uri::path_to_uri(&fresh).expect("uri");
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
serde_json::json!({ "textDocument": { "uri": fresh_uri } }),
);
session.watched(&[tree.path.join("rtl/a.sv")]);
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "filelist": "files.f" } } }),
@@ -2636,9 +2881,11 @@ mod tests {
let result = session.result(ExecuteCommand::METHOD, params);
assert!(result.is_null(), "the edit was pushed, not returned");
// Force a rescan while the edit is outstanding, so a progress create
// sits between the push and its answer.
session.watched(&[tree.path.join("sub.sv")]);
// Force a *whole* rescan while the edit is outstanding, so a progress
// create sits between the push and its answer. Two files, because one
// takes the incremental path and puts no bar up
// (incremental-index, 2026-08-27).
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.sv")]);
let sent = session.sent();
let edit = sent
.iter()
@@ -2679,7 +2926,8 @@ mod tests {
let result = session.result(ExecuteCommand::METHOD, params);
assert!(result.is_null(), "the edit was pushed, not returned");
session.watched(&[tree.path.join("sub.sv")]);
// Two files, so the rescan is the whole one that puts a bar up.
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.sv")]);
let sent = session.sent();
let edit = sent
.iter()
@@ -3702,12 +3950,13 @@ mod tests {
..Default::default()
};
let mut session = Session::with(vec![tree.path.clone()], abilities);
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let _ = session.drain();
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
// Two files at once, so this is a whole rescan and there is a bar for
// the refresh to ride after (incremental-index, 2026-08-27); the
// one-file path's own refresh is pinned in
// `a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses`.
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.sv")]);
let order: Vec<String> = session
.drain()
.into_iter()
@@ -6185,7 +6434,8 @@ mod tests {
let result = session.result(ExecuteCommand::METHOD, params);
assert!(result.is_null(), "the edit was pushed, not returned");
session.watched(&[tree.path.join("sub.sv")]);
// Two files, so the rescan is the whole one that puts a bar up.
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.sv")]);
let sent = session.sent();
let of = |method: &str| -> RequestId {
+386
View File
@@ -422,6 +422,89 @@ impl Workspace {
scope.warnings
}
/// Rebuild the index for **one** file, leaving every other file's
/// contribution exactly as it is. Reports whether it could.
///
/// `false` means the caller must fall back to [`Workspace::rebuild_index`]:
/// the file is not one this index already holds, which is the one case the
/// cheap path cannot settle. A file appearing changes which *other* files
/// exist as far as the include graph is concerned (a `` `include`` that had
/// nothing to resolve to now has something), and answering that takes a
/// walk — so the rule is simply "a file the index already holds".
///
/// The four pieces of state a rebuild produces, and what happens to each:
///
/// * **the workspace index** — [`WorkspaceIndex::update_file`] /
/// [`WorkspaceIndex::remove_file`], which promise the index a whole
/// rebuild over the same file set would have produced;
/// * **the completion tables** — the two index-derived ones re-derived, the
/// word table patched by this file's words alone;
/// * **the include graph** — this file's edges re-scanned, the known-file
/// and folded-spelling tables re-learned from the index's list;
/// * **every open buffer's overlay** — refreshed, exactly as a rebuild
/// refreshes it, because any of them may resolve into the file that moved.
///
/// The text is chosen by `collect_sources`'s rules, for one path: an open
/// buffer beats disk and is never capped; a walked file over
/// `lucisv.index.maxFileSize`, one that has been deleted, and one that
/// cannot be read are all "this file is not in the index any more".
pub fn update_one(&mut self, path: &Path) -> bool {
if !self.index.files().iter().any(|held| held == path) {
return false;
}
match self.current_text(path) {
Some(text) => {
self.index.update_file(path.to_path_buf(), &text);
self.candidates.update_file(&self.index, path, &text);
self.includes.update_file(path, &text, self.index.files());
}
None => {
self.index.remove_file(path);
self.candidates.remove_file(&self.index, path);
self.includes.remove_file(path, self.index.files());
}
}
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
true
}
/// [`Workspace::update_one`], then a whole rebuild over the same
/// workspace, asserting the two produced the same thing — the paranoid
/// form, for tests.
///
/// It is the incremental path's whole claim, checked rather than argued:
/// the index's fingerprint (ids, disambiguation order, member tables,
/// edges, define counts) and the completion word table, which is the one
/// piece of derived state that is patched rather than re-derived. The
/// workspace is left holding the *rebuilt* index, which is the same index,
/// so a test may keep using it.
#[cfg(test)]
pub fn update_one_checked(&mut self, path: &Path) -> bool {
if !self.update_one(path) {
return false;
}
let index = self.index.fingerprint();
let words = self.candidates.words("").to_vec();
self.rebuild_index();
assert_eq!(index, self.index.fingerprint(), "incremental index != rebuilt index");
assert_eq!(words, self.candidates.words(""), "incremental words != rebuilt words");
true
}
/// The text one in-scope file contributes right now, by `collect_sources`'s
/// rules — `None` when it contributes nothing at all.
fn current_text(&self, path: &Path) -> Option<String> {
if let Some(doc) = self.docs.values().find(|doc| doc.path.as_deref() == Some(path)) {
return Some(doc.text.clone());
}
if oversize(path, self.client.max_file_size).is_some() {
return None;
}
fs::read_to_string(path).ok()
}
/// The work list with the open buffers' own files at the front of it, each
/// group still in path order (`sort_by_key` is stable).
///
@@ -1820,4 +1903,307 @@ mod tests {
assert_eq!(ws.index().files(), plain.index().files(), "same files, same ids");
assert_eq!(ws.index().counts(), plain.index().counts(), "and the same index");
}
// ------------------------------------------------------------------
// The incremental path (incremental-index, 2026-08-27)
// ------------------------------------------------------------------
#[test]
fn only_a_file_the_index_already_holds_takes_the_incremental_path() {
// The whole gate, from both sides. A file the index holds is one the
// update can replace; anything else is a rebuild's business, because a
// file appearing changes what *other* files' includes resolve to.
let tree = Tree::new("incrgate");
tree.package("rtl/a.sv", "a_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(ws.update_one_checked(&tree.path.join("rtl/a.sv")), "a file the index holds");
assert!(!ws.update_one(&tree.path.join("rtl/new.sv")), "a file it does not");
assert!(!ws.update_one(&tree.path.join("rtl/a.txt")), "and a path it never would");
// A file that appears is exactly the "not held" case, and stays so
// until something rebuilds.
tree.package("rtl/new.sv", "new_pkg");
assert!(!ws.update_one(&tree.path.join("rtl/new.sv")), "still not held");
ws.rebuild_index();
assert!(ws.update_one_checked(&tree.path.join("rtl/new.sv")), "held now");
}
#[test]
fn one_files_edit_reaches_every_table_the_index_answers_from() {
// The four pieces of derived state a rebuild produces, checked one by
// one after an update that moves all four: a declaration, an
// instantiation edge, an inheritance edge, a completion word and an
// `` `include`` edge.
let tree = Tree::new("incrtables");
tree.write("rtl/defs.svh", "`define W 8\n");
tree.write("rtl/sub.sv", "module sub;\nendmodule\nclass base;\nendclass\n");
tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule top;\n sub u1 ();\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let top = tree.path.join("rtl/top.sv");
assert_eq!(ws.index().instantiations_of("sub").len(), 1, "premise: one site");
assert_eq!(
ws.includes().reachable(vec![top.clone()]).len(),
2,
"premise: top.sv reaches defs.svh"
);
assert_eq!(ws.candidates().words("u1").len(), 1, "premise: the instance name is a word");
fs::write(
&top,
"module top;\n logic renamed_wire;\nendmodule\nclass leaf extends base;\nendclass\n",
)
.expect("write");
assert!(ws.update_one_checked(&top));
assert!(ws.index().instantiations_of("sub").is_empty(), "the site went");
assert_eq!(ws.index().subclasses_of("base").len(), 1, "and an inheritance edge came");
assert!(ws.candidates().words("u1").is_empty(), "the old word was given back");
assert_eq!(ws.candidates().words("renamed_wire").len(), 1, "the new one taken");
assert_eq!(ws.includes().reachable(vec![top]).len(), 1, "the include edge went too");
}
#[test]
fn a_file_the_cap_or_the_disk_takes_away_leaves_the_index() {
let tree = Tree::new("incrremove");
tree.package("rtl/keep.sv", "keep_pkg");
tree.package("rtl/gone.sv", "gone_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["keep_pkg", "gone_pkg"]).len(), 2, "premise");
// Deleted on disk: the update is a removal.
let gone = tree.path.join("rtl/gone.sv");
fs::remove_file(&gone).expect("remove");
assert!(ws.update_one_checked(&gone), "a held file, even a vanished one");
assert_eq!(indexed(&ws, &["keep_pkg", "gone_pkg"]), ["keep_pkg"]);
// And a file that grew past the cap is the same answer for the same
// reason: it is not a file this server reads any more.
let mut ws = Workspace::default();
let tree = Tree::new("incrcap");
tree.package("rtl/keep.sv", "keep_pkg");
fat_package(&tree, "rtl/netlist.sv", "netlist_pkg", 4096);
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["keep_pkg", "netlist_pkg"]).len(), 2, "premise: under no cap");
ws.set_client_settings(wide(capping(1024)));
assert!(ws.update_one_checked(&tree.path.join("rtl/netlist.sv")));
assert_eq!(indexed(&ws, &["keep_pkg", "netlist_pkg"]), ["keep_pkg"], "the cap took it");
}
#[test]
fn an_open_buffer_beats_disk_on_the_incremental_path_too() {
let tree = Tree::new("incrbuffer");
tree.package("rtl/a.sv", "a_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let path = tree.path.join("rtl/a.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(
uri,
"package buffered_pkg;\n localparam K = 1;\nendpackage\n".to_string(),
);
assert!(ws.update_one_checked(&path));
assert_eq!(
indexed(&ws, &["a_pkg", "buffered_pkg"]),
["buffered_pkg"],
"the buffer's text, not the file's"
);
}
#[test]
fn the_incremental_update_agrees_with_a_whole_rebuild_over_the_real_corpus() {
// The paranoid sweep: take real files out of a real workspace, put a
// mutated version back through the incremental path, and check the
// result against a whole rebuild every time. `update_one_checked` is
// what does the checking; this test is the corpus it does it over.
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
// Copied into a scratch tree, because the sweep rewrites files. Every
// fifth file: `update_one_checked` rebuilds the whole workspace to
// check itself, so the sweep costs a full rebuild per mutation and a
// third of the corpus is still hundreds of real files.
let tree = Tree::new("incrcorpus");
let mut copied = 0;
let mut sample: Vec<PathBuf> = Vec::new();
for (n, source) in walk_sources(&corpus).into_iter().step_by(5).enumerate() {
let Ok(text) = fs::read_to_string(&source) else { continue };
let rel = format!("f{n:04}.sv");
tree.write(&rel, &text);
copied += 1;
if n % 31 == 0 {
sample.push(tree.path.join(&rel));
}
}
assert!(copied > 100, "premise: the corpus was really copied ({copied} files)");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(sample.len() > 5, "a sample worth sweeping: {}", sample.len());
for path in &sample {
let text = fs::read_to_string(path).expect("the copy is on disk");
// Four shapes of edit, each checked against a whole rebuild.
assert!(ws.update_one_checked(path), "unchanged");
fs::write(
path,
format!("{text}\nmodule qa_added_module;\n qa_added_sub u1 ();\nendmodule\n"),
)
.expect("write");
assert!(ws.update_one_checked(path), "a declaration and an edge added");
fs::write(path, "class qa_leaf extends qa_base;\nendclass\n").expect("write");
assert!(ws.update_one_checked(path), "replaced wholesale");
fs::write(path, "").expect("write");
assert!(ws.update_one_checked(path), "emptied");
fs::remove_file(path).expect("remove");
assert!(ws.update_one_checked(path), "removed");
}
eprintln!("paranoid sweep: {copied} files, {} of them mutated five ways", sample.len());
}
/// Every source file under `dir`, for the corpus sweep above.
fn walk_sources(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
let mut stack = vec![dir.to_path_buf()];
while let Some(next) = stack.pop() {
let Ok(entries) = fs::read_dir(&next) else { continue };
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
stack.push(path);
} else if matches!(
path.extension().and_then(|e| e.to_str()),
Some("sv" | "v" | "svh")
) {
out.push(path);
}
}
}
out.sort();
out
}
/// What one file's rescan costs on the incremental path, against the whole
/// rebuild it replaces, over the real corpus.
///
/// `#[ignore]`d like the crate's other measurement probes: it prints
/// numbers rather than asserting one. The numbers themselves are in
/// `docs/features/incremental-index/README.md`.
#[test]
#[ignore]
fn qa_perf_one_file_against_the_whole_rebuild() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus]);
let files = ws.index().files().len();
let one = ws.index().files().last().cloned().expect("a file");
let mut whole = std::time::Duration::MAX;
let mut single = std::time::Duration::MAX;
for _ in 0..3 {
let started = std::time::Instant::now();
ws.rebuild_index();
whole = whole.min(started.elapsed());
let started = std::time::Instant::now();
assert!(ws.update_one(&one));
single = single.min(started.elapsed());
}
eprintln!(
"reindex over {files} files: whole rebuild {whole:?}, one file {single:?} \
({:.0}x)",
whole.as_secs_f64() / single.as_secs_f64().max(f64::MIN_POSITIVE)
);
}
// ------------------------------------------------------------------
// Inherited obligations (index-scope Review, 2026-08-27)
// ------------------------------------------------------------------
#[test]
fn lowering_the_scope_depth_narrows_the_index_on_the_next_rescan() {
// The scope grows only along the *open* axis — a `didClose` never
// narrows it. A settings change is the other axis and moves both ways,
// because it is a deliberate statement about how much of this machine's
// time to spend. Verified by hand by the previous round's QA; pinned
// here.
let tree = two_folder_tree("depthdown");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 1, ..Default::default() });
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert!(scoped(&ws).contains(&"defs_pkg".to_string()), "premise: depth 1 reaches beside");
assert!(
ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() }),
"lowering the depth asks for a rescan"
);
ws.rebuild_index();
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg"], "narrowed, not kept");
}
#[test]
fn a_filelist_appearing_mid_session_flips_the_ladder_to_rung_one() {
// Not just "asks for a rescan" — that the index really becomes the
// filelist's files, from a folder scope that was covering something
// else entirely.
let tree = two_folder_tree("filelistmid");
tree.write("files.f", "elsewhere/far.sv\n");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg"],
"premise: the folder rung"
);
assert!(ws.set_client_settings(using_filelist("files.f")), "a rescan is owed");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "far_pkg"],
"rung 1 defines the scope exactly — plus the open buffer, which overlays every rung"
);
}
#[test]
fn a_buffer_opened_outside_every_root_rides_the_folder_rung_like_a_rootless_one() {
// `raised()`'s floor is the deepest root *containing* the directory, and
// there is none here — so the climb stops at `/`, exactly as it does
// with no root at all. Verified by hand by the previous round's QA;
// pinned here, on the directories rather than by walking one.
let inside = Tree::new("outsideroot_in");
inside.package("rtl/a.sv", "a_pkg");
let outside = Tree::new("outsideroot_out");
outside.package("other/b.sv", "b_pkg");
let mut ws = Workspace::default();
ws.open_roots(vec![inside.path.clone()]);
open(&mut ws, &outside, "other/b.sv");
assert_eq!(
ws.scope_dirs(),
vec![outside.path.join("other")],
"at depth 0 it is the buffer's own directory and nothing else"
);
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["a_pkg", "b_pkg"]),
["b_pkg"],
"the root's own tree is not in it"
);
ws.set_client_settings(ClientSettings { index_scope_depth: 99, ..Default::default() });
assert_eq!(
ws.scope_dirs(),
vec![PathBuf::from("/")],
"and with nothing to clamp against the climb stops at the filesystem root"
);
}
}
+104 -82
View File
@@ -21,24 +21,15 @@
//! See `docs/features/type-hierarchy/README.md`.
use lsp_types::{Range, SymbolKind, TypeHierarchyItem, Uri};
use vlog_parser::ast::{ClassDecl, Item, ItemKind};
use vlog_parser::ast::Item;
use vlog_parser::{parse_source_tolerant, LineIndex, TextRange};
use vlog_semantic::classes::{self, Decl};
use vlog_semantic::{Definition, SymbolKind as SemanticKind};
use crate::convert::Positions;
use crate::state::{Document, Workspace};
use crate::uri::{path_to_uri, uri_to_path};
/// One class declaration: the node, and the extent of the whole
/// `class ... endclass` it was written as.
#[derive(Clone, Copy)]
struct Decl<'a> {
class: &'a ClassDecl,
/// Code extent of the declaration, attributes included — what a type
/// hierarchy item's `range` is.
span: TextRange,
}
/// The class the cursor names, as the root of a type hierarchy — its own
/// declaration, or any use of its name.
///
@@ -53,8 +44,9 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<TypeHierarc
let doc = ws.document(uri)?;
// The cursor on a declaration written in this buffer answers from the
// buffer, unsaved edits and all — no index lookup can beat that.
if let Some(decl) =
declarations(&doc.tree.items).into_iter().find(|decl| touches(decl.class.name_span, offset))
if let Some(decl) = classes::declarations(&doc.tree.items)
.into_iter()
.find(|decl| touches(decl.class.name_span, offset))
{
let positions = doc.positions();
return Some(vec![item(uri.clone(), &positions, decl)?]);
@@ -94,37 +86,38 @@ pub fn supertypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec<TypeHierarchy
/// Who extends this class, across the workspace.
///
/// Every in-scope file is walked, because the workspace index records what a
/// file *declares* and not what it extends — there is no edge table to consult,
/// exactly as there is none for instantiations
/// (`docs/features/hierarchy/README.md`). A file whose text does not contain
/// the name is skipped before it is parsed, which is what keeps the walk
/// affordable: `extends base` has to write `base`.
/// **A lookup in the workspace index's inheritance-edge table** since
/// 2026-08-27, where it used to be a re-read and re-parse of every in-scope
/// file. The edges are recorded by the same [`classes::declarations`] walk this
/// function used to run, at index time
/// (`docs/features/incremental-index/README.md`), so the answer and its order
/// are unchanged; only the files that really do extend the class are read now,
/// and only to turn the recorded byte spans into line/character ranges.
///
/// An empty name is answered with nothing rather than searched for: nothing
/// this server hands out is nameless, and the prefilter matches every file for
/// one, which would parse the whole workspace to find nothing.
/// An empty name is answered with nothing rather than looked up: nothing this
/// server hands out is nameless, and a nameless question has no answer.
pub fn subtypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec<TypeHierarchyItem> {
if item.name.is_empty() {
return Vec::new();
}
let index = ws.index();
let mut found: Vec<TypeHierarchyItem> = Vec::new();
for (path, text) in ws.sources() {
if !text.contains(&item.name) {
continue;
}
let Some(uri) = path_to_uri(&path) else { continue };
let (tree, _) = parse_source_tolerant(&text);
let edges = index.subclasses_of(&item.name);
let mut at = 0;
while at < edges.len() {
// The edges arrive in file order, so one file's are consecutive: read
// its text once and build every item it holds.
let file = edges[at].file;
let group = &edges[at..][..edges[at..].iter().take_while(|e| e.file == file).count()];
at += group.len();
let Some(path) = index.path(file) else { continue };
let Some(uri) = path_to_uri(path) else { continue };
let Some(text) = ws.text_of(path) else { continue };
let line_index = LineIndex::new(&text);
let positions = Positions::new(&text, &line_index);
for decl in declarations(&tree.items) {
if extends_name(decl.class) != Some(item.name.as_str()) {
continue;
}
if let Some(built) = self::item(uri.clone(), &positions, decl) {
found.push(built);
}
}
found.extend(group.iter().map(|edge| &edge.subclass).filter_map(|subclass| {
item_of(uri.clone(), &positions, &subclass.name, subclass.name_span, subclass.span)
}));
}
found.sort_by(|a, b| {
(a.uri.as_str(), key(a.selection_range)).cmp(&(b.uri.as_str(), key(b.selection_range)))
@@ -132,16 +125,6 @@ pub fn subtypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec<TypeHierarchyIt
found
}
/// The base class of one class declaration, as written — `None` when the
/// header has no `extends`.
///
/// The name is the bare base: `extends base #(8)` stores `base`, because the
/// parser keeps the parameter overrides on their own field, so a parameterized
/// base needs no unwrapping here.
fn extends_name(class: &ClassDecl) -> Option<&str> {
class.extends.as_ref().map(|extends| extends.name.as_str())
}
/// The base classes of the class an item names, in the file it names.
fn bases_of(
ws: &Workspace,
@@ -200,20 +183,28 @@ fn classes_at(ws: &Workspace, doc: &Document, uri: &Uri, offset: u32) -> Vec<Typ
/// The hierarchy item for one class declaration, positioned against the text it
/// was parsed from.
fn item(uri: Uri, positions: &Positions, decl: Decl) -> Option<TypeHierarchyItem> {
let name_span = decl.class.name_span;
item_of(uri, positions, &decl.class.name, decl.class.name_span, decl.span)
}
/// [`item`] from the parts, for a caller reading them out of the index's
/// inheritance-edge table rather than off a parse tree.
fn item_of(
uri: Uri,
positions: &Positions,
name: &str,
name_span: TextRange,
span: TextRange,
) -> Option<TypeHierarchyItem> {
if name_span.is_empty() {
return None;
}
// The protocol requires `selectionRange` inside `range`; a declaration the
// parser could not close is the case where that may not hold, and there the
// name alone is the honest extent.
let full = if decl.span.start <= name_span.start && name_span.end <= decl.span.end {
decl.span
} else {
name_span
};
let full =
if span.start <= name_span.start && name_span.end <= span.end { span } else { name_span };
Some(TypeHierarchyItem {
name: decl.class.name.clone(),
name: name.to_string(),
// `interface class` is a different construct (IEEE 1800 §8.26) that
// `vlog_parser` does not model at all, so there is nothing here that
// could carry `SymbolKind::INTERFACE`.
@@ -250,34 +241,11 @@ fn item_in_file(
item(uri, &Positions::new(&text, &line_index), decl)
}
/// Every class declaration in `items`, wherever a class may be written: at file
/// scope, inside a `package`, inside a `module`, and nested inside another
/// class.
fn declarations(items: &[Item]) -> Vec<Decl<'_>> {
let mut out = Vec::new();
collect(items, &mut out);
out
}
fn collect<'a>(items: &'a [Item], out: &mut Vec<Decl<'a>>) {
for item in items {
match &item.kind {
ItemKind::Class(class) => {
out.push(Decl { class, span: item.span });
collect(&class.items, out);
}
ItemKind::Package { items, .. } => collect(items, out),
ItemKind::Module(module) => collect(&module.items, out),
_ => {}
}
}
}
/// The declaration of `name` in a parsed file: the one whose name sits at `at`,
/// else the first of that name.
fn find_class<'a>(items: &'a [Item], name: &str, at: Option<TextRange>) -> Option<Decl<'a>> {
let decls: Vec<Decl> =
declarations(items).into_iter().filter(|d| d.class.name == name).collect();
classes::declarations(items).into_iter().filter(|d| d.class.name == name).collect();
if let Some(at) = at {
if let Some(exact) = decls.iter().find(|d| d.class.name_span == at) {
return Some(*exact);
@@ -727,9 +695,14 @@ endclass
}
#[test]
fn an_unsaved_extends_is_a_subtype_before_it_is_saved() {
// The sources a walk reads are the open buffers overlaid on disk, so a
// just-typed `extends` counts.
fn an_edited_buffers_extends_counts_from_the_moment_the_index_sees_it() {
// Superseded this round (incremental-index, 2026-08-27):
// `an_unsaved_extends_is_a_subtype_before_it_is_saved` pinned the walk
// over `Workspace::sources()`, so a keystroke in another buffer moved
// the answer before anything rebuilt. Subtypes are the index's
// inheritance-edge table now — as of its last build or update, both of
// which fold every open buffer in. Same rule as the call hierarchy's
// census, pinned from both sides.
let (tree, mut ws, uri) = two("unsaved");
let root = prepare(&ws, &uri, at(CHILD, "extends base") + 8).expect("base")[0].clone();
assert_eq!(subtypes(&ws, &root).len(), 1, "premise");
@@ -737,7 +710,13 @@ endclass
let fresh = tree.path.join("child.sv");
let child_uri = path_to_uri(&fresh).expect("uri");
ws.set_document(child_uri, "class child;\nendclass\n".to_string());
assert!(subtypes(&ws, &root).is_empty(), "the buffer took the `extends` away");
assert_eq!(
subtypes(&ws, &root).len(),
1,
"the buffer alone does not move the answer — the index has not seen it"
);
assert!(ws.update_one(&fresh), "the file is in scope, so one file is enough");
assert!(subtypes(&ws, &root).is_empty(), "the edit took the `extends` away");
}
// ------------------------------------------------------------------
@@ -1088,6 +1067,49 @@ endclass
// the corpus, smoke-tested
// ------------------------------------------------------------------
/// What `subtypes` costs after the inheritance-edge table, against the
/// workspace walk it replaced. `#[ignore]`d: it prints a number rather
/// than asserting one — the budget is asserted in
/// `the_corpus_uvm_classes_answer_all_three_requests`.
#[test]
#[ignore]
fn qa_perf_subtypes_lookup_against_the_walk_it_replaced() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let lib = corpus.join("ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv");
let Ok(text) = fs::read_to_string(&lib) else {
eprintln!("core_ibex_test_lib.sv is not in this corpus — skipping");
return;
};
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&lib).expect("uri");
ws.set_document(uri.clone(), text.clone());
let offset = at(&text, "class core_ibex_debug_intr_basic_test") + 6;
let child = prepare(&ws, &uri, offset).expect("the class")[0].clone();
let base = supertypes(&ws, &child).first().cloned().expect("core_ibex_base_test");
let mut lookup = std::time::Duration::ZERO;
let mut walk = std::time::Duration::ZERO;
for _ in 0..3 {
let started = std::time::Instant::now();
let found = subtypes(&ws, &base);
lookup = lookup.max(started.elapsed());
assert!(!found.is_empty());
let started = std::time::Instant::now();
let _ = ws.sources();
walk = walk.max(started.elapsed());
}
eprintln!(
"typeHierarchy/subtypes over {} files: {lookup:?}; one workspace walk (what it \
used to begin with) is {walk:?}",
ws.index().files().len()
);
}
/// Every class of a real UVM-shaped corpus file, through all three
/// requests, plus one known `extends` chain. Skipped when `corpus/` is not
/// checked out (`tools/corpus_fetch.sh`), like the other corpus tests.
@@ -1113,7 +1135,7 @@ endclass
// every item the protocol's containment rule.
let doc = ws.document(&uri).expect("the open buffer");
let names: Vec<String> =
declarations(&doc.tree.items).iter().map(|d| d.class.name.clone()).collect();
classes::declarations(&doc.tree.items).iter().map(|d| d.class.name.clone()).collect();
assert!(names.len() > 20, "the file really is class-heavy: {}", names.len());
let mut with_a_base = 0;
for name in &names {
+24 -1
View File
@@ -8,7 +8,7 @@
//! module asks it to say what it sees. See
//! `docs/features/file-watching/README.md`.
use std::path::Path;
use std::path::{Path, PathBuf};
use lsp_types::notification::{DidChangeWatchedFiles, Notification as _};
use lsp_types::{
@@ -112,6 +112,29 @@ pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool {
.any(|path| watched(&path, filelist))
}
/// The one file an event named, when it named exactly one and that one is not
/// the filelist.
///
/// The gate on the incremental rescan path (`server.rs`'s `reindex_one`): a
/// checkout fills this list, and a list of one is the case a single file's
/// contribution can be replaced in place. The filelist is excluded because a
/// change to it moves the whole scope, which is a rebuild by definition. An
/// event naming the same path twice — a client is free to send `Changed` and
/// `Created` for one file — is still one file.
pub fn one_scope_file(changes: &[FileEvent], filelist: Option<&Path>) -> Option<PathBuf> {
let mut named: Vec<PathBuf> = changes
.iter()
.filter_map(|change| uri_to_path(&change.uri))
.filter(|path| watched(path, filelist))
.collect();
named.sort();
named.dedup();
match named.as_slice() {
[only] if Some(only.as_path()) != filelist => Some(only.clone()),
_ => None,
}
}
/// Whether one path is something the index reads: a source file, or the
/// filelist that decides which source files there are.
///
+85 -12
View File
@@ -3223,12 +3223,14 @@ fn indexing_reports_its_progress_over_the_wire() {
})
.collect();
// Three rescans, and the shape of them is the folder scope on the wire
// (index-scope, 2026-08-27). The startup build has **no file to scan** —
// the default scope is the open buffers' folders and no buffer is open
// yet — so its bar carries no report; the `didOpen` widens the scope to
// `m.sv`'s folder and rebuilds, reporting the one file; the save rebuilds
// again. Each on its own token, create/begin/…/end in order.
// **Two** rescans, and the shape of them is the folder scope on the wire
// (index-scope, 2026-08-27) plus the incremental save path
// (incremental-index, 2026-08-27). The startup build has **no file to
// scan** — the default scope is the open buffers' folders and no buffer is
// open yet — so its bar carries no report; the `didOpen` widens the scope
// to `m.sv`'s folder and rebuilds, reporting the one file. The **save
// puts no bar up at all**: it names one file the index already holds, so
// it is one parse on the incremental path rather than a scan to report.
assert_eq!(
steps,
vec![
@@ -3239,10 +3241,6 @@ fn indexing_reports_its_progress_over_the_wire() {
("begin".to_string(), "lucisv-index-1".to_string()),
("report".to_string(), "lucisv-index-1".to_string()),
("end".to_string(), "lucisv-index-1".to_string()),
("create".to_string(), "lucisv-index-2".to_string()),
("begin".to_string(), "lucisv-index-2".to_string()),
("report".to_string(), "lucisv-index-2".to_string()),
("end".to_string(), "lucisv-index-2".to_string()),
],
"{messages:#?}"
);
@@ -3262,13 +3260,14 @@ fn indexing_reports_its_progress_over_the_wire() {
assert!(begin["params"]["value"].get("percentage").is_none(), "no fake numbers: {begin:#?}");
// The startup bar ends at nothing indexed — honestly, since the folder
// scope had no folder yet — and the two rebuilds after it name the file.
// scope had no folder yet — and the `didOpen` rebuild after it names the
// file. The save has no bar to end.
let ends: Vec<&serde_json::Value> = messages
.iter()
.filter(|m| m["params"]["value"]["kind"] == "end")
.map(|m| &m["params"]["value"]["message"])
.collect();
assert_eq!(ends, ["0 files indexed", "1 file indexed", "1 file indexed"], "{messages:#?}");
assert_eq!(ends, ["0 files indexed", "1 file indexed"], "{messages:#?}");
// The create is a request the client may answer or error; leaving it
// unanswered here is exactly what a client that does not care does, and
@@ -4301,3 +4300,77 @@ fn the_folder_scope_widens_when_a_file_in_another_folder_is_opened() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_save_of_one_file_updates_the_index_over_the_wire() {
// The incremental path against the real binary: a save rewrites one file,
// the answer that file supplies changes, and a second file nobody touched
// still answers exactly what it did before.
let dir = temp_dir("incremental");
std::fs::write(dir.join("sub.sv"), "module sub;\nendmodule\n").expect("write");
std::fs::write(dir.join("other.sv"), "module other;\nendmodule\n").expect("write");
let top = dir.join("top.sv");
let before = "module top;\n sub u1 ();\nendmodule\n";
std::fs::write(&top, before).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", top.display());
// After the save `top.sv` instantiates `other` instead of `sub`. Both
// definition requests are asked twice, once each side of the save.
let after = "module top;\n other u1 ();\nendmodule\n";
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(before).expect("json")
)),
// Where `sub` is instantiated, before: line 1, character 2.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":3}}}}}}"#
)),
// And what the untouched second file's own declaration answers, out
// of the index rather than out of a buffer — the file has none.
frame(
r#"{"jsonrpc":"2.0","id":3,"method":"workspace/symbol","params":{"query":"sub"}}"#,
),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}},"text":{}}}}}"#,
serde_json::to_string(after).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":3}}}}}}"#
)),
frame(
r#"{"jsonrpc":"2.0","id":5,"method":"workspace/symbol","params":{"query":"sub"}}"#,
),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
let answer = |id: i64| -> serde_json::Value {
messages
.iter()
.find(|m| m["id"] == id)
.unwrap_or_else(|| panic!("no answer to {id} in {messages:#?}"))["result"]
.clone()
};
// `textDocument/definition` answers a list of locations.
let target =
|id: i64| -> String { answer(id)[0]["uri"].as_str().unwrap_or_default().to_string() };
assert!(target(2).ends_with("sub.sv"), "premise: {:#?}", answer(2));
assert!(target(4).ends_with("other.sv"), "the save moved the answer to `other.sv`");
assert_eq!(answer(3), answer(5), "the file nobody touched answers exactly what it did");
assert!(
answer(3).as_array().is_some_and(|hits| hits.iter().any(|hit| hit["name"] == "sub")),
"premise: it answers at all — {:#?}",
answer(3)
);
let _ = std::fs::remove_dir_all(&dir);
}
+123
View File
@@ -0,0 +1,123 @@
//! Finding class declarations in a parse tree — one walk, two readers.
//!
//! `type_hierarchy.rs` wants every class in a file so it can build a hierarchy
//! item for the one the cursor names; the workspace index wants the same walk
//! so it can record who extends whom as it builds
//! (`docs/features/incremental-index/README.md`). One walk here, so the census
//! the index holds and the declaration the hierarchy shows can never disagree.
//!
//! **Lifted from `lucisv_server::type_hierarchy` on 2026-08-27**, unchanged by
//! the move.
use vlog_parser::ast::{ClassDecl, Item, ItemKind};
use vlog_parser::TextRange;
/// One class declaration: the node, and the extent of the whole
/// `class ... endclass` it was written as.
#[derive(Clone, Copy)]
pub struct Decl<'a> {
/// The declaration node, for its name and its `extends` clause.
pub class: &'a ClassDecl,
/// Code extent of the declaration, attributes included — what a type
/// hierarchy item's `range` is.
pub span: TextRange,
}
/// Every class declaration in `items`, wherever a class may be written: at file
/// scope, inside a `package`, inside a `module`, and nested inside another
/// class.
pub fn declarations(items: &[Item]) -> Vec<Decl<'_>> {
let mut out = Vec::new();
collect(items, &mut out);
out
}
/// The base class one declaration names, as written — `None` when the header
/// has no `extends`.
///
/// The name is the bare base: `extends base #(8)` reads `base`, because the
/// parser keeps the parameter overrides on their own field, so a parameterized
/// base needs no unwrapping here.
pub fn extends_name(class: &ClassDecl) -> Option<&str> {
class.extends.as_ref().map(|extends| extends.name.as_str())
}
fn collect<'a>(items: &'a [Item], out: &mut Vec<Decl<'a>>) {
for item in items {
match &item.kind {
ItemKind::Class(class) => {
out.push(Decl { class, span: item.span });
collect(&class.items, out);
}
ItemKind::Package { items, .. } => collect(items, out),
ItemKind::Module(module) => collect(&module.items, out),
_ => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
/// Every class name a file declares, in walk order, with its base.
fn declared(text: &str) -> Vec<(String, String)> {
let (tree, _) = parse_source_tolerant(text);
declarations(&tree.items)
.iter()
.map(|decl| {
(decl.class.name.clone(), extends_name(decl.class).unwrap_or("-").to_string())
})
.collect()
}
#[test]
fn a_class_is_found_wherever_it_may_be_written() {
let text = "\
class top extends base;
class nested extends top;
endclass
endclass
package p;
class in_pkg extends top;
endclass
endpackage
module m;
class in_mod;
endclass
endmodule
";
assert_eq!(
declared(text),
[
("top".to_string(), "base".to_string()),
("nested".to_string(), "top".to_string()),
("in_pkg".to_string(), "top".to_string()),
("in_mod".to_string(), "-".to_string()),
]
);
}
#[test]
fn a_parameterized_base_names_the_bare_class() {
assert_eq!(
declared("class d extends b #(8);\nendclass\n"),
[("d".to_string(), "b".to_string())]
);
}
#[test]
fn a_declarations_extent_contains_its_own_name() {
let text = "class first;\nendclass\n\nclass second;\nendclass\n";
let (tree, _) = parse_source_tolerant(text);
let decls = declarations(&tree.items);
assert_eq!(decls.len(), 2);
for decl in &decls {
assert!(decl.span.start <= decl.class.name_span.start);
assert!(decl.class.name_span.end <= decl.span.end);
}
}
}
@@ -11,6 +11,13 @@
//! Gate primitives are not instantiations here: `and (q, a, b)` is an
//! [`ItemKind::GateInstantiation`], names no module, and is nobody's edge in
//! the hierarchy.
//!
//! **Lifted from `lucisv_server` on 2026-08-27** so the workspace index can
//! record instantiation edges as it builds
//! (`docs/features/incremental-index/README.md`). The walk is the census —
//! what counts as one instantiation site — and a second copy of it in the
//! index would have been free to drift from the one the call hierarchy uses.
//! The code is unchanged by the move.
use vlog_parser::ast::{GenBlock, GenElse, Instantiation, Item, ItemKind, Module};
use vlog_parser::TextRange;
@@ -19,6 +26,7 @@ use vlog_parser::TextRange;
/// `module ... endmodule` it was written as.
#[derive(Clone, Copy)]
pub struct Decl<'a> {
/// The declaration node, for its name and its own items.
pub module: &'a Module,
/// Code extent of the declaration, attributes included — what a call
/// hierarchy item's `range` is.
@@ -27,6 +35,7 @@ pub struct Decl<'a> {
/// One module instantiation, and the module whose body it sits in.
pub struct Site<'a> {
/// The instantiation node: the module it names, and its connections.
pub inst: &'a Instantiation,
/// The innermost module the instantiation is written inside. `None` for
/// one written at file scope — illegal SystemVerilog, and reachable
+5 -2
View File
@@ -17,6 +17,8 @@
//! the simplifications taken.
mod bind;
pub mod classes;
pub mod instantiations;
mod model;
mod resolve;
mod scan;
@@ -27,8 +29,9 @@ pub use model::{
SymbolId, SymbolKind,
};
pub use workspace::{
index_order, resolve_external, Def, Definition, ExternalResolutions, ExternalTarget, FileId,
IndexBuilder, IndexCounts, WorkspaceIndex, WorkspaceSymbol,
index_order, resolve_external, DeclSite, Def, Definition, ExternalResolutions, ExternalTarget,
FileId, IndexBuilder, IndexCounts, InheritanceEdge, InstantiationEdge, WorkspaceIndex,
WorkspaceSymbol,
};
use std::collections::HashMap;
+392 -36
View File
@@ -13,15 +13,16 @@
//! See `docs/features/workspace-index/README.md` for the resolution order,
//! the duplicate-name policy and the corpus numbers.
use std::collections::{BTreeMap, HashMap};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use vlog_parser::ast::SourceFile;
use vlog_parser::defines::{collect_defines, Define, DefineTable};
use vlog_parser::span::TextRange;
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize};
use crate::model::{ReferenceId, Resolution, Symbol, SymbolKind};
use crate::{analyze, Semantics};
use crate::{analyze, classes, instantiations, Semantics};
/// Index of a file in a [`WorkspaceIndex`], assigned in sorted path order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
@@ -49,18 +50,72 @@ pub struct WorkspaceSymbol<'a> {
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,
}
/// 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, and their `` `define`` tables.
/// 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.
/// 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>>>,
/// Indexed by [`FileId`], parallel to `files`.
defines: Vec<DefineTable>,
/// 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>>,
}
impl WorkspaceIndex {
@@ -70,8 +125,9 @@ impl WorkspaceIndex {
/// contributes every declaration that *did* parse.
///
/// Pure: the same inputs always give the same index, whatever order they
/// arrive in. Re-scanning a changed workspace means calling this again —
/// there is no incremental update (TODO.md §6 defers that to salsa).
/// 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
@@ -119,9 +175,34 @@ impl WorkspaceIndex {
.flat_map(|m| m.iter().map(|(name, defs)| (name.as_str(), defs.as_slice())))
}
/// 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)
}
/// 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()))
}
/// The `` `define`` table of one file.
pub fn defines(&self, file: FileId) -> Option<&DefineTable> {
self.defines.get(file.0 as usize)
self.facts.get(file.0 as usize).map(|facts| &facts.defines)
}
/// Every definition of a macro name anywhere in the workspace, in file
@@ -131,9 +212,9 @@ impl WorkspaceIndex {
/// silently would not be.
pub fn find_define(&self, name: &str) -> Vec<(FileId, &Define)> {
let mut out = Vec::new();
for (i, table) in self.defines.iter().enumerate() {
for (i, facts) in self.facts.iter().enumerate() {
let file = FileId(i as u32);
out.extend(table.all(name).into_iter().map(|d| (file, d)));
out.extend(facts.defines.all(name).into_iter().map(|d| (file, d)));
}
out
}
@@ -187,13 +268,226 @@ impl WorkspaceIndex {
.filter(|d| d.kind == SymbolKind::Class)
.count(),
members: self.members.values().flat_map(|m| m.values()).map(Vec::len).sum(),
defines: self.defines.iter().map(|t| t.entries().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(),
}
}
fn units_of_kind(&self, kind: SymbolKind) -> usize {
self.units.values().flatten().filter(|d| d.kind == kind).count()
}
// ------------------------------------------------------------------
// incremental update
// ------------------------------------------------------------------
/// Replace one file's contribution to the index — or add the file, when
/// the index does not hold it yet.
///
/// **The result is the index a full [`WorkspaceIndex::build`] over the same
/// file set would have produced, byte for byte**: same [`FileId`]s, same
/// disambiguation order, same member tables, same edges. That is the whole
/// contract, and it is what makes an incremental server safe. It holds by
/// construction rather than by care — the merge below is `finish`'s own
/// loop, over the same path-sorted records, restricted to the names this
/// file could have moved.
///
/// A [`FileId`] is a position in the path-sorted file list and nothing
/// else, so **adding a file renumbers the ones after it**. That is
/// deliberate: an id that meant a different thing depending on how the
/// index was arrived at would make "the same index" unprovable, and the
/// renumbering costs one merge pass over records already in memory — no
/// file is read and no file is re-parsed. Ids do not survive an add or a
/// remove; nothing in this workspace holds one across an update (the
/// server refreshes every overlay after it, exactly as it does after a
/// rebuild).
pub fn update_file(&mut self, path: PathBuf, src: &str) {
let facts = facts_of(path.clone(), src);
match self.facts.binary_search_by(|held| held.path.cmp(&path)) {
// The common case — a saved file the index already holds. Only the
// names this file declared before or declares now can have moved,
// and the file list has not, so ids are untouched.
Ok(at) => {
let mut affected = Affected::of(&self.facts[at]);
affected.add(&facts);
self.facts[at] = facts;
self.merge(Some(&affected));
}
// A file the index did not hold: every id from here on shifts, so
// every table is rebuilt from the records. No parse, no read.
Err(at) => {
self.files.insert(at, path);
self.facts.insert(at, facts);
self.merge(None);
}
}
}
/// Drop one file from the index, reporting whether it was there.
///
/// Same contract as [`WorkspaceIndex::update_file`]: what is left is the
/// index a full build over the remaining files would have produced.
pub fn remove_file(&mut self, path: &Path) -> bool {
let Ok(at) = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)) else {
return false;
};
self.files.remove(at);
self.facts.remove(at);
self.merge(None);
true
}
/// Every observable this index answers, rendered as one comparable value.
///
/// The witness for the equivalence [`WorkspaceIndex::update_file`]
/// promises: two indexes are the same index exactly when their
/// fingerprints are equal. Public because the proof is worth writing in
/// more than one crate's tests — `lucisv_server` checks it against the
/// real corpus, this crate against crafted attacks.
pub fn fingerprint(&self) -> String {
let mut out = String::new();
for (id, path) in self.files.iter().enumerate() {
let defines = self.defines(FileId(id as u32)).map_or(0, |t| t.entries().len());
out.push_str(&format!("file {id} {} defines={defines}\n", path.display()));
}
for symbol in self.workspace_symbols("") {
out.push_str(&format!(
"sym {} in {:?} {:?} {}:{}..{}\n",
symbol.name,
symbol.container,
symbol.def.kind,
symbol.def.file.0,
symbol.def.name_span.start,
symbol.def.name_span.end
));
}
for (name, edges) in self.instantiations() {
for edge in edges {
out.push_str(&format!(
"inst {name} {} in {}@{}..{} site {}..{}\n",
edge.file.0,
edge.owner.name,
edge.owner.name_span.start,
edge.owner.span.end,
edge.site_span.start,
edge.site_span.end
));
}
}
for (name, edges) in self.subclasses() {
for edge in edges {
out.push_str(&format!(
"extends {name} {} {}@{}..{}\n",
edge.file.0,
edge.subclass.name,
edge.subclass.name_span.start,
edge.subclass.span.end
));
}
}
out
}
/// Rebuild the merged tables from the per-file records.
///
/// `affected` names the keys that may have moved; `None` means all of
/// them. Either way this is one loop over the path-sorted records pushing
/// in the order it meets them, which is the *only* place any table's order
/// is decided — so a restricted merge and a whole one agree by
/// construction, and both agree with [`IndexBuilder::finish`].
fn merge(&mut self, affected: Option<&Affected>) {
match affected {
None => {
self.units.clear();
self.members.clear();
self.instantiations.clear();
self.subclasses.clear();
}
Some(affected) => {
for name in &affected.units {
self.units.remove(name);
}
for name in &affected.containers {
self.members.remove(name);
}
for name in &affected.modules {
self.instantiations.remove(name);
}
for name in &affected.bases {
self.subclasses.remove(name);
}
}
}
for (id, facts) in self.facts.iter().enumerate() {
let file = FileId(id as u32);
for decl in &facts.units {
if affected.is_some_and(|a| !a.units.contains(&decl.name)) {
continue;
}
self.units.entry(decl.name.clone()).or_default().push(decl.def(file));
}
for (unit, decl) in &facts.members {
if affected.is_some_and(|a| !a.containers.contains(unit)) {
continue;
}
self.members
.entry(unit.clone())
.or_default()
.entry(decl.name.clone())
.or_default()
.push(decl.def(file));
}
for (module, edge) in &facts.instantiations {
if affected.is_some_and(|a| !a.modules.contains(module)) {
continue;
}
self.instantiations.entry(module.clone()).or_default().push(InstantiationEdge {
file,
owner: edge.owner.clone(),
site_span: edge.site_span,
});
}
for (base, subclass) in &facts.subclasses {
if affected.is_some_and(|a| !a.bases.contains(base)) {
continue;
}
self.subclasses
.entry(base.clone())
.or_default()
.push(InheritanceEdge { file, subclass: subclass.clone() });
}
}
}
}
/// The table keys one file's records can move, so a merge after replacing that
/// file can leave every other key alone.
#[derive(Debug, Default)]
struct Affected {
units: HashSet<String>,
/// Keys of the `members` table — the *unit* a member is exported by, not
/// the member itself. A whole unit's sub-table is the smallest thing worth
/// rebuilding: one file adding a member to a package cannot move any other
/// package.
containers: HashSet<String>,
modules: HashSet<String>,
bases: HashSet<String>,
}
impl Affected {
fn of(facts: &FileFacts) -> Affected {
let mut out = Affected::default();
out.add(facts);
out
}
fn add(&mut self, facts: &FileFacts) {
self.units.extend(facts.units.iter().map(|decl| decl.name.clone()));
self.containers.extend(facts.members.iter().map(|(unit, _)| unit.clone()));
self.modules.extend(facts.instantiations.iter().map(|(module, _)| module.clone()));
self.bases.extend(facts.subclasses.iter().map(|(base, _)| base.clone()));
}
}
/// One declaration as a single file contributes it, before that file has a
@@ -210,6 +504,18 @@ impl Decl {
fn of(symbol: &Symbol) -> Decl {
Decl { name: symbol.name.clone(), name_span: symbol.name_span, kind: symbol.kind }
}
fn def(&self, file: FileId) -> Def {
Def { file, name_span: self.name_span, kind: self.kind }
}
}
/// One instantiation site as a single file contributes it — an
/// [`InstantiationEdge`] without its [`FileId`].
#[derive(Debug, Clone)]
struct SiteFact {
owner: DeclSite,
site_span: TextRange,
}
/// Everything one file contributes to an index: read while the file is parsed,
@@ -227,13 +533,26 @@ struct FileFacts {
/// Members, each under the name of the unit that exports it, in the order
/// the scope tree yields them.
members: Vec<(String, Decl)>,
/// Instantiation sites, each under the name of the module instantiated, in
/// walk order.
instantiations: Vec<(String, SiteFact)>,
/// Class declarations with a base, each under the base's name, in walk
/// order.
subclasses: Vec<(String, DeclSite)>,
}
/// Parse one file and read off what it declares.
/// Parse one file and read off what it declares and what it points at.
fn facts_of(path: PathBuf, src: &str) -> FileFacts {
let (tree, defines) = parse_and_collect(src);
let sem = analyze(&tree, src);
let mut facts = FileFacts { path, defines, units: Vec::new(), members: Vec::new() };
let mut facts = FileFacts {
path,
defines,
units: Vec::new(),
members: Vec::new(),
instantiations: edges_of(&tree),
subclasses: inheritance_of(&tree),
};
let Some(file_scope) = sem.scope(sem.file_scope()) else {
return facts;
};
@@ -250,6 +569,51 @@ fn facts_of(path: PathBuf, src: &str) -> FileFacts {
facts
}
/// Every instantiation one file writes, under the name of the module it
/// instantiates.
///
/// The walk is [`crate::instantiations::sites`] — the same one the call
/// hierarchy reads a buffer with — so the workspace-wide census and the
/// per-file one cannot disagree. A site written at file scope has no
/// instantiating module and is not an edge.
fn edges_of(tree: &SourceFile) -> Vec<(String, SiteFact)> {
instantiations::sites(&tree.items)
.into_iter()
.filter_map(|site| {
let owner = site.owner?;
Some((
site.inst.module.clone(),
SiteFact {
owner: DeclSite {
name: owner.module.name.clone(),
name_span: owner.module.name_span,
span: owner.span,
},
site_span: site.inst.module_span,
},
))
})
.collect()
}
/// Every class one file declares that extends another, under the base's name.
fn inheritance_of(tree: &SourceFile) -> Vec<(String, DeclSite)> {
classes::declarations(&tree.items)
.into_iter()
.filter_map(|decl| {
let base = classes::extends_name(decl.class)?;
Some((
base.to_string(),
DeclSite {
name: decl.class.name.clone(),
name_span: decl.class.name_span,
span: decl.span,
},
))
})
.collect()
}
/// Read off the names another file may reach *into* this unit for.
fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>) {
let Some(scope) = unit.child_scope.and_then(|c| sem.scope(c)) else {
@@ -296,8 +660,9 @@ pub fn index_order<'a>(
///
/// 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. Nothing here is incremental in the salsa
/// sense: a file can be added, never replaced or removed.
/// 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
@@ -336,26 +701,12 @@ impl IndexBuilder {
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::default();
for (id, facts) in self.files.into_iter().enumerate() {
let file = FileId(id as u32);
index.files.push(facts.path);
index.defines.push(facts.defines);
for decl in facts.units {
index.units.entry(decl.name).or_default().push(Def {
file,
name_span: decl.name_span,
kind: decl.kind,
});
}
for (unit, decl) in facts.members {
index.members.entry(unit).or_default().entry(decl.name).or_default().push(Def {
file,
name_span: decl.name_span,
kind: decl.kind,
});
}
}
let mut index = WorkspaceIndex {
files: self.files.iter().map(|facts| facts.path.clone()).collect(),
facts: self.files,
..WorkspaceIndex::default()
};
index.merge(None);
index
}
}
@@ -379,6 +730,11 @@ pub struct IndexCounts {
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,
}
/// Parse one file and read its `` `define`` table off the same token stream.
+492 -31
View File
@@ -319,38 +319,15 @@ fn the_incremental_builder_is_what_build_is_made_of() {
assert_eq!(built.member("z", "K").len(), 1);
}
/// Everything an index holds, as text: the files in `FileId` order, then every
/// declared name — unit or member — with its declarations in disambiguation
/// order, each naming the **path** of the file it is in rather than its id, and
/// then each file's `` `define`` count. Two indexes with the same fingerprint
/// answer every query the same way; an index whose file ids or whose
/// duplicate-name order moved has a different one.
/// Everything an index holds, as text — [`WorkspaceIndex::fingerprint`].
///
/// Two indexes with the same fingerprint answer every query the same way; an
/// index whose file ids, whose duplicate-name order or whose edges moved has a
/// different one. It lives in the crate rather than here because
/// `lucisv_server` proves the same equivalence against the real corpus, and one
/// witness that both crates use cannot drift.
fn fingerprint(index: &WorkspaceIndex) -> String {
let mut out = String::new();
for (id, path) in index.files().iter().enumerate() {
let defines = index.defines(FileId(id as u32)).map_or(0, |t| t.entries().len());
out.push_str(&format!("file {id} {} ({defines} defines)\n", path.display()));
}
let mut names: Vec<(Option<String>, String)> = index
.workspace_symbols("")
.iter()
.map(|hit| (hit.container.map(str::to_string), hit.name.to_string()))
.collect();
names.sort();
names.dedup();
for (container, name) in names {
let defs = match &container {
Some(unit) => index.member(unit, &name),
None => index.units(&name),
};
out.push_str(&format!("{}::{name}", container.unwrap_or_default()));
for def in defs {
let path = index.path(def.file).map(|p| p.display().to_string()).unwrap_or_default();
out.push_str(&format!(" [{path} {:?} {:?}]", def.name_span, def.kind));
}
out.push('\n');
}
out
index.fingerprint()
}
/// One index built by adding `files` to an `IndexBuilder` in exactly the order
@@ -994,3 +971,487 @@ fn collect(dir: &std::path::Path, out: &mut Vec<PathBuf>) {
}
}
}
// ----------------------------------------------------------------------
// incremental updates (incremental-index, 2026-08-27)
// ----------------------------------------------------------------------
/// The one invariant everything else in this section is an attack on: an index
/// arrived at by updating one file is the index a whole build over the same
/// files would have produced — ids, disambiguation order, member tables, edges
/// and defines alike.
///
/// Asserted by building both and comparing fingerprints, and returning the
/// incremental one so a caller can go on asking it questions.
fn updated(whole: &[(&str, &str)], changed: &str, text: &str) -> WorkspaceIndex {
let without: Vec<(&str, &str)> = whole.iter().copied().filter(|(p, _)| *p != changed).collect();
let mut incremental = index(&without);
incremental.update_file(PathBuf::from(changed), text);
let mut expected: Vec<(&str, &str)> = without;
expected.push((changed, text));
assert_eq!(
incremental.fingerprint(),
index(&expected).fingerprint(),
"updating `{changed}` must give the index a whole build would have"
);
incremental
}
#[test]
fn adding_a_file_gives_the_index_a_whole_build_would_have() {
// The hardest direction: the new file sorts *first*, so every file id after
// it moves and every table that named one has to move with it.
let held = [
("m.sv", "module m;\n sub u1 ();\nendmodule\n"),
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
];
let ws = updated(&held, "a.sv", "module sub;\nendmodule\nclass leaf extends base;\nendclass\n");
assert_eq!(ws.files()[0], PathBuf::from("a.sv"), "the new file took FileId(0)");
assert_eq!(ws.units("z")[0].file, FileId(2), "and z.sv moved from 1 to 2");
assert_eq!(ws.instantiations_of("sub")[0].file, FileId(1), "m.sv's edge moved with it");
assert_eq!(ws.subclasses_of("base").len(), 1);
}
#[test]
fn replacing_a_file_touches_only_what_that_file_said() {
let held = [
("a.sv", "module a;\n sub u1 ();\nendmodule\n"),
("b.sv", "module b;\n sub u2 ();\nendmodule\n"),
("sub.sv", "module sub;\nendmodule\n"),
];
// `a.sv` stops instantiating `sub` and declares a package instead.
let ws = updated(&held, "a.sv", "package a;\n localparam K = 1;\nendpackage\n");
assert_eq!(ws.instantiations_of("sub").len(), 1, "only b.sv's site is left");
assert_eq!(ws.instantiations_of("sub")[0].owner.name, "b");
assert_eq!(ws.member("a", "K").len(), 1, "and the new package's member is there");
assert_eq!(ws.units("a")[0].kind, SymbolKind::Package, "the module is gone, not shadowed");
assert_eq!(ws.files().len(), 3, "no file came or went");
}
#[test]
fn removing_a_file_gives_the_index_a_whole_build_would_have() {
let held =
[("a.sv", "module dup;\n sub u1 ();\nendmodule\n"), ("z.sv", "module dup;\nendmodule\n")];
let mut ws = index(&held);
assert_eq!(ws.units("dup").len(), 2, "premise: the name is declared twice");
assert!(ws.remove_file(Path::new("a.sv")), "the file was there");
assert_eq!(
ws.fingerprint(),
index(&held[1..]).fingerprint(),
"what is left is the index of what is left"
);
assert_eq!(ws.units("dup").len(), 1, "and the removed declaration is gone");
assert_eq!(ws.units("dup")[0].file, FileId(0), "z.sv renumbered down to 0");
assert!(ws.instantiations_of("sub").is_empty(), "its edges went with it");
assert!(!ws.remove_file(Path::new("a.sv")), "and removing it again says so");
}
#[test]
fn removing_a_file_moves_the_disambiguation_winner() {
// The sharpest thing a removal can do to a *derived* answer: the file that
// won a duplicate name is the file that goes.
let held = [
("a_early.sv", "module dup (input a);\nendmodule\n"),
("z_late.sv", "module dup (input b);\nendmodule\n"),
];
let mut ws = index(&held);
assert_eq!(ws.path(ws.units("dup")[0].file), Some(Path::new("a_early.sv")), "premise");
assert!(ws.remove_file(Path::new("a_early.sv")));
assert_eq!(
ws.path(ws.units("dup")[0].file),
Some(Path::new("z_late.sv")),
"the loser became the winner, and the member table with it"
);
assert_eq!(ws.member("dup", "b").len(), 1);
assert!(ws.member("dup", "a").is_empty());
assert_eq!(ws.fingerprint(), index(&held[1..]).fingerprint());
}
#[test]
fn a_file_that_redefines_a_name_another_file_declares_lands_in_path_order() {
// The update inserts into a table that already holds the *other* file's
// declaration, so this is where an insert-at-the-end bug would show.
let held =
[("a_early.sv", "module dup;\nendmodule\n"), ("z_late.sv", "package other;\nendpackage\n")];
let ws = updated(&held, "z_late.sv", "module dup;\nendmodule\n");
let files: Vec<Option<&Path>> = ws.units("dup").iter().map(|d| ws.path(d.file)).collect();
assert_eq!(
files,
[Some(Path::new("a_early.sv")), Some(Path::new("z_late.sv"))],
"path order, not update order"
);
// And the other way round: the *early* file gains the duplicate.
let ws = updated(
&[held[0], ("z_late.sv", "module dup;\nendmodule\n")],
"a_early.sv",
"module dup;\nendmodule\n",
);
let files: Vec<Option<&Path>> = ws.units("dup").iter().map(|d| ws.path(d.file)).collect();
assert_eq!(files, [Some(Path::new("a_early.sv")), Some(Path::new("z_late.sv"))]);
}
#[test]
fn a_rename_is_a_remove_and_an_add_and_lands_where_a_build_would_put_it() {
let held = [
("mid.sv", "module m;\n sub u1 ();\nendmodule\n"),
("sub.sv", "module sub;\nendmodule\n"),
];
let mut ws = index(&held);
assert!(ws.remove_file(Path::new("mid.sv")));
ws.update_file(PathBuf::from("aaa.sv"), "module m;\n sub u1 ();\nendmodule\n");
let renamed = [("aaa.sv", "module m;\n sub u1 ();\nendmodule\n"), held[1]];
assert_eq!(ws.fingerprint(), index(&renamed).fingerprint(), "a rename is the two of them");
assert_eq!(ws.instantiations_of("sub")[0].file, FileId(0), "and the edge followed the file");
}
#[test]
fn an_update_survives_every_degenerate_file_there_is() {
let held = [("a.sv", "module a;\nendmodule\n"), ("b.sv", "module b;\nendmodule\n")];
for (label, text) in [
("empty", ""),
("whitespace", "\n\n \n"),
("not verilog", "@@@ !!! not verilog at all\n"),
("does not lex", "module a;\n string s = \"unterminated\n"),
("comment only", "// nothing here\n"),
] {
let ws = updated(&held, "a.sv", text);
assert_eq!(ws.files().len(), 2, "{label}: the file is still a file");
assert_eq!(ws.units("b").len(), 1, "{label}: and the other file is untouched");
}
// An empty index is not a special case either.
let mut empty = WorkspaceIndex::default();
assert!(!empty.remove_file(Path::new("nothing.sv")));
empty.update_file(PathBuf::from("only.sv"), "module only;\nendmodule\n");
assert_eq!(
empty.fingerprint(),
index(&[("only.sv", "module only;\nendmodule\n")]).fingerprint()
);
}
#[test]
fn a_full_build_and_a_build_minus_one_plus_that_one_are_the_same_index() {
// The round's headline invariant, over a fixture with something of every
// kind in it and with **every** file taken out and put back in turn.
let files = [
("a_early.sv", "module dup (input a);\n sub u1 (), u2 ();\nendmodule\n"),
("cls.sv", "class leaf extends mid;\nendclass\nclass mid extends base;\nendclass\n"),
("defs.svh", "`define W 8\n`define D 4\n"),
(
"pkg.sv",
"package p;\n localparam K = 1;\n class base;\n int x;\n endclass\nendpackage\n",
),
("sub.sv", "module sub;\nendmodule\n"),
("z_late.sv", "module dup (input b);\n sub u3 ();\nendmodule\n"),
];
let whole = index(&files);
for (path, text) in files {
let rebuilt = updated(&files, path, text);
assert_eq!(
rebuilt.fingerprint(),
whole.fingerprint(),
"taking `{path}` out and putting it back must change nothing at all"
);
}
}
// ----------------------------------------------------------------------
// the edge tables (incremental-index, 2026-08-27)
// ----------------------------------------------------------------------
#[test]
fn the_instantiation_table_records_the_census_the_hierarchy_counts() {
// Every policy `lens.rs`'s QA tests pin, stated once here at the source of
// the numbers: one edge per written statement however many instances it
// declares, a `generate for` body counted once, both arms of an `` `ifdef``
// counted, a module that instantiates itself counted, a `bind`'s
// instantiation an ordinary edge, a gate primitive not an edge at all, and
// an instantiation at file scope not an edge because nothing calls it.
let files = [
(
"top.sv",
"\
module top;
sub u1 (), u2 ();
generate
for (genvar i = 0; i < 4; i++) begin : g
sub u3 ();
end
endgenerate
`ifdef FOO
sub u4 ();
`else
sub u5 ();
`endif
top u6 ();
and u7 (q, a, b);
bind top sub u8 ();
endmodule
",
),
("loose.sv", "sub u_loose ();\n"),
];
let ws = index(&files);
let sites = ws.instantiations_of("sub");
assert_eq!(
sites.len(),
5,
"one multi-instance statement, one generate body, both ifdef arms, one bind: {sites:#?}"
);
assert!(sites.iter().all(|edge| edge.owner.name == "top"), "all inside `top`: {sites:#?}");
assert!(sites.iter().all(|edge| edge.file == FileId(1)), "and all in top.sv");
assert_eq!(ws.instantiations_of("top").len(), 1, "a module instantiates itself");
assert!(ws.instantiations_of("and").is_empty(), "a gate primitive names no module");
assert!(
!sites.iter().any(|edge| edge.owner.name == "loose"),
"an instantiation at file scope has no caller and is not an edge"
);
// The spans are the ones a hierarchy item is built from: the site names the
// module, the owner's name span names the caller.
let text = files[0].1;
assert_eq!(&text[sites[0].site_span.as_range()], "sub");
assert_eq!(&text[sites[0].owner.name_span.as_range()], "top");
assert!(sites[0].owner.span.start <= sites[0].owner.name_span.start);
assert!(sites[0].owner.name_span.end <= sites[0].owner.span.end);
}
#[test]
fn the_inheritance_table_records_every_class_that_names_a_base() {
let files = [
("a.sv", "class leaf extends mid;\nendclass\n"),
("b.sv", "package p;\n class mid extends base;\n endclass\n class loner;\n endclass\nendpackage\n"),
("c.sv", "module m;\n class inner extends mid #(8);\n endclass\nendmodule\n"),
];
let ws = index(&files);
let mids: Vec<&str> =
ws.subclasses_of("mid").iter().map(|e| e.subclass.name.as_str()).collect();
assert_eq!(mids, ["leaf", "inner"], "file order; a parameterized base is the bare name");
assert_eq!(ws.subclasses_of("base").len(), 1, "a class inside a package is an edge too");
assert!(ws.subclasses_of("loner").is_empty(), "and a class nothing extends has none");
assert_eq!(ws.counts().inheritances, 3);
assert_eq!(ws.counts().instantiations, 0);
}
#[test]
fn the_edge_tables_are_empty_for_a_workspace_with_no_edges() {
let ws = index(&[("a.sv", "module a;\nendmodule\n")]);
assert!(ws.instantiations_of("a").is_empty());
assert!(ws.subclasses_of("a").is_empty());
assert_eq!(ws.instantiations().count(), 0);
assert_eq!(ws.subclasses().count(), 0);
assert_eq!(WorkspaceIndex::default().instantiations_of("anything").len(), 0);
}
// ----------------------------------------------------------------------
// QA (incremental-index, 2026-08-27): adversarial sequences the dev's own
// tests do not reach — each checked against a fresh build, not just asserted
// on its own terms.
// ----------------------------------------------------------------------
#[test]
fn a_long_interleaved_sequence_matches_a_fresh_build_at_every_step() {
// update A, update B, remove A, re-add A, update B again — the exact
// sequence the round's equivalence claim has to survive, checked after
// *every* step rather than only at the end (a bug that only shows up two
// steps later, e.g. a stale `Affected` set, would pass an end-only check).
let a1 = "module a;\n sub u1 ();\nendmodule\n";
let b1 = "package b;\n localparam K = 1;\nendpackage\n";
let mut incremental = index(&[("a.sv", a1), ("b.sv", b1)]);
let a2 = "module a;\n sub u1 (), u2 ();\nendmodule\nclass leaf extends base;\nendclass\n";
incremental.update_file(PathBuf::from("a.sv"), a2);
assert_eq!(
incremental.fingerprint(),
index(&[("a.sv", a2), ("b.sv", b1)]).fingerprint(),
"step 1: update a"
);
let b2 = "package b;\n localparam K = 2;\n class base;\n endclass\nendpackage\n";
incremental.update_file(PathBuf::from("b.sv"), b2);
assert_eq!(
incremental.fingerprint(),
index(&[("a.sv", a2), ("b.sv", b2)]).fingerprint(),
"step 2: update b"
);
assert!(incremental.remove_file(Path::new("a.sv")), "step 3: remove a");
assert_eq!(
incremental.fingerprint(),
index(&[("b.sv", b2)]).fingerprint(),
"step 3: what a full build over what is left would have"
);
let a3 = "module a;\n sub u3 ();\nendmodule\n";
incremental.update_file(PathBuf::from("a.sv"), a3);
assert_eq!(
incremental.fingerprint(),
index(&[("a.sv", a3), ("b.sv", b2)]).fingerprint(),
"step 4: re-add a"
);
let b3 = "package b;\n localparam K = 3;\nendpackage\n";
incremental.update_file(PathBuf::from("b.sv"), b3);
assert_eq!(
incremental.fingerprint(),
index(&[("a.sv", a3), ("b.sv", b3)]).fingerprint(),
"step 5: update b again"
);
}
#[test]
fn a_name_only_one_file_declared_leaves_no_ghost_when_that_file_stops_declaring_it() {
// The ghost hunt: `Affected` for an update is the old record's names
// *and* the new record's names (checked by reading `WorkspaceIndex::
// update_file`'s `Ok(at)` arm), so a name that only the changed file used
// to declare must come back with nothing at all — not a stale one-entry
// `Vec` from before the update, and not silently dropped from the merge's
// `.remove()` and never refilled either.
let held = [("a.sv", "module solo;\nendmodule\n"), ("b.sv", "package other;\nendpackage\n")];
let mut ws = index(&held);
assert_eq!(ws.units("solo").len(), 1, "premise: only a.sv declares it");
ws.update_file(PathBuf::from("a.sv"), "package a;\nendpackage\n");
assert!(ws.units("solo").is_empty(), "the ghost must not survive");
assert_eq!(
ws.fingerprint(),
index(&[("a.sv", "package a;\nendpackage\n"), held[1]]).fingerprint()
);
}
#[test]
fn adding_a_new_file_that_duplicates_an_existing_name_lands_by_path_order_either_direction() {
// `a_file_that_redefines_a_name_another_file_declares_lands_in_path_order`
// covers this for a file the index already holds (the restricted-merge
// `Ok(at)` arm); this is the same attack against the `Err(at)` arm, where
// every id renumbers rather than one record being replaced in place.
let held = [("z_late.sv", "module dup;\nendmodule\n")];
let mut ws = index(&held);
ws.update_file(PathBuf::from("a_early.sv"), "module dup;\nendmodule\n");
let files: Vec<&Path> = ws.units("dup").iter().map(|d| ws.path(d.file).unwrap()).collect();
assert_eq!(
files,
[Path::new("a_early.sv"), Path::new("z_late.sv")],
"the new, earlier-sorting file wins the disambiguation"
);
assert_eq!(
ws.fingerprint(),
index(&[("a_early.sv", "module dup;\nendmodule\n"), held[0]]).fingerprint()
);
let held = [("a_early.sv", "module dup;\nendmodule\n")];
let mut ws = index(&held);
ws.update_file(PathBuf::from("z_late.sv"), "module dup;\nendmodule\n");
let files: Vec<&Path> = ws.units("dup").iter().map(|d| ws.path(d.file).unwrap()).collect();
assert_eq!(
files,
[Path::new("a_early.sv"), Path::new("z_late.sv")],
"and the other way round, the existing file keeps the disambiguation win"
);
assert_eq!(
ws.fingerprint(),
index(&[held[0], ("z_late.sv", "module dup;\nendmodule\n")]).fingerprint()
);
}
#[test]
fn find_define_answers_in_current_file_id_order_after_cross_file_updates() {
// Defines are per-file (`WorkspaceIndex::defines`) and are not part of
// `Affected` at all — `find_define` just walks `self.facts` in current id
// order. The attack is renumbering: adding a file that sorts *before*
// both existing ones must move every entry's `FileId` and keep the answer
// in the new file order, `` `undef``s excluded either way.
let held = [("a.sv", "`define W 8\n"), ("b.sv", "`define W 16\n`undef W\n`define W 32\n")];
let mut ws = index(&held);
let bodies = |ws: &WorkspaceIndex| -> Vec<(u32, String)> {
ws.find_define("W").iter().map(|(f, d)| (f.0, d.body.clone())).collect()
};
assert_eq!(
bodies(&ws),
[(0, "8".to_string()), (1, "16".to_string()), (1, "32".to_string())],
"premise: file order, every definition (not just the latest), undef excluded"
);
ws.update_file(PathBuf::from("a.sv"), "`define W 9\n");
assert_eq!(
bodies(&ws),
[(0, "9".to_string()), (1, "16".to_string()), (1, "32".to_string())],
"the update landed and the order held"
);
ws.update_file(PathBuf::from("0_early.sv"), "`define W 1\n");
assert_eq!(ws.path(FileId(0)), Some(Path::new("0_early.sv")), "premise: it renumbered");
assert_eq!(
bodies(&ws),
[(0, "1".to_string()), (1, "9".to_string()), (2, "16".to_string()), (2, "32".to_string())],
"find_define's ids moved with the renumbering and the order is still file order"
);
}
#[test]
fn updating_a_file_to_empty_text_differs_from_removing_it() {
// Explicitly not the same operation, and not pinned as such anywhere else:
// an emptied file keeps its `FileId` slot (it is still a file the index
// holds, contributing nothing), while a removed file's slot is gone and
// every later id shifts down. Two different fingerprints, on purpose.
let held = [("a.sv", "module a;\nendmodule\n"), ("z.sv", "module z;\nendmodule\n")];
let mut emptied = index(&held);
emptied.update_file(PathBuf::from("a.sv"), "");
let mut removed = index(&held);
assert!(removed.remove_file(Path::new("a.sv")));
assert_ne!(
emptied.fingerprint(),
removed.fingerprint(),
"an emptied file is still a file; a removed one is not the same index at all"
);
assert_eq!(emptied.files().len(), 2, "the empty file still occupies a slot");
assert_eq!(removed.files().len(), 1, "the removed file's slot is gone");
assert_eq!(emptied.path(FileId(1)), Some(Path::new("z.sv")), "z.sv did not renumber");
assert_eq!(removed.path(FileId(0)), Some(Path::new("z.sv")), "z.sv renumbered down to 0");
}
#[test]
fn same_named_files_in_different_directories_updated_alternately_stay_correct() {
// Two files that share a *filename* but not a path are ordinary distinct
// entries to `WorkspaceIndex` (paths, not filenames, are the sort key and
// the identity `binary_search_by` uses) — attacked here by updating first
// one, then the other, then the first again, checking the full
// equivalence at each step so a bug keying off the filename rather than
// the path would show.
let held = [
("dir_a/defs.sv", "module defs_mod;\n sub u1 ();\nendmodule\n"),
("dir_b/defs.sv", "module defs_mod;\n sub u2 ();\nendmodule\n"),
];
let mut ws = index(&held);
assert_eq!(ws.units("defs_mod").len(), 2, "premise: both declare the same name");
// Two separate statements, not one comma-joined one — the census counts
// one edge per `Instantiation` node, so this really is two sites.
let dir_a_v2 = "module defs_mod;\n sub u3 ();\n sub u4 ();\nendmodule\n";
ws.update_file(PathBuf::from("dir_a/defs.sv"), dir_a_v2);
assert_eq!(ws.instantiations_of("sub").len(), 3, "dir_a now has two sites, dir_b still one");
assert_eq!(
ws.fingerprint(),
index(&[("dir_a/defs.sv", dir_a_v2), held[1]]).fingerprint(),
"after updating dir_a alone"
);
let dir_b_v2 = "package other;\nendpackage\n";
ws.update_file(PathBuf::from("dir_b/defs.sv"), dir_b_v2);
assert_eq!(ws.units("defs_mod").len(), 1, "only dir_a's module is left");
assert_eq!(ws.path(ws.units("defs_mod")[0].file), Some(Path::new("dir_a/defs.sv")));
assert_eq!(ws.instantiations_of("sub").len(), 2, "dir_b's site went with it");
assert_eq!(
ws.fingerprint(),
index(&[("dir_a/defs.sv", dir_a_v2), ("dir_b/defs.sv", dir_b_v2)]).fingerprint(),
"after updating dir_b too"
);
let dir_a_v3 = "module defs_mod;\nendmodule\n";
ws.update_file(PathBuf::from("dir_a/defs.sv"), dir_a_v3);
assert!(ws.instantiations_of("sub").is_empty(), "back to dir_a, and its sites go too");
assert_eq!(
ws.fingerprint(),
index(&[("dir_a/defs.sv", dir_a_v3), ("dir_b/defs.sv", dir_b_v2)]).fingerprint(),
"alternating back to the first file"
);
}
+31 -7
View File
@@ -68,22 +68,46 @@ computed by, so the lens and the hierarchy view can never disagree (TODO.md
invalidate. Not on a keystroke either — a `didChange` cannot change any
count, since the census is over instantiations in *other* files and a client
re-requests lenses for the buffer it just edited anyway.
- **The count is computed against `Workspace::sources()`**, which reads every
- ~~**The count is computed against `Workspace::sources()`**, which reads every
in-scope file from disk with open buffers overriding it. So an unsaved
instantiation typed into another open buffer *is* counted, and a file
changed on disk that no watcher reported is counted as of this request.
- **The cost is one workspace walk per request, not one per module.**
changed on disk that no watcher reported is counted as of this request.~~
**Superseded (incremental-index, 2026-08-27)** — see the assumption above.
- ~~**The cost is one workspace walk per request, not one per module.**
`hierarchy::callers_of_each` takes a batch precisely because `sources()`
re-reads the whole file set: measured over the 860-file corpus, a
three-module file costs 133 ms against 93 ms for a single name (debug build)
— amortized, not tripled. The absolute number is the honest cost of having
no instantiation-edge table in the index; see Status / TODO.
no instantiation-edge table in the index; see Status / TODO.~~
**Superseded (incremental-index, 2026-08-27): the cost is a lookup.** The
count comes from the index's instantiation-edge table, and the only I/O left
is reading the handful of files that really do instantiate one of the names,
to turn recorded byte spans into ranges — 0.26 ms for the same three-module
file over the same corpus. The batch stays the primitive for the same
reason at a smaller scale: one file instantiating three of the names is read
once.
- **The count is as of the index, which is as of its last build or update**
(incremental-index, 2026-08-27) — superseding the assumption below that the
count is computed against `Workspace::sources()` per request. A save, or any
other rescan trigger, folds every open buffer in and makes an edit count; a
keystroke alone no longer does. The trade and the alternatives considered are
in `docs/features/incremental-index/README.md`.
## Handshakes
### Request to `vlog_semantic` — an instantiation-edge table in the index
Filed by the lead (2026-08-26) on QA's recommendation, since **two** shipped
**Delivered (incremental-index, 2026-08-27).** `WorkspaceIndex::instantiations_of`
exists with the shape proposed below — plus the owning declaration's name and
full extent, which is what stopped `callers_of_each` re-parsing the file to
find them — and `hierarchy::callers_of_each` is a lookup with its walk-and-parse
body deleted. The census policies carried over by construction: the table is
built by the same `instantiations::sites` walk the handler used to run, which
was lifted into `vlog_semantic` for exactly that reason, and every one of this
feature's QA tests passes unchanged. Measured 92 ms → 0.26 ms for a
three-module file over the corpus. The original request, kept legible:
~~Filed by the lead (2026-08-26) on QA's recommendation, since **two** shipped
features now pay the same cost: every `textDocument/codeLens` request and
every `callHierarchy/incomingCalls` walks `Workspace::sources()` — a re-read
and tolerant re-parse of every in-scope file — because `WorkspaceIndex`
@@ -100,7 +124,7 @@ pub fn instantiations_of(&self, name: &str) -> &[InstantiationEdge]
so `hierarchy::callers_of_each` becomes a lookup and its whole
walk-and-parse body is deleted. The census policies (multi-instance
statements = one site, textual not elaborated, both `ifdef` arms) must carry
over unchanged — `lens.rs`'s QA tests pin the numbers that must not move.
over unchanged — `lens.rs`'s QA tests pin the numbers that must not move.~~
### `lucisv_server::hierarchy` — **changed, deliberately**
@@ -206,7 +230,7 @@ no-showDocument path — verified by running it.
is an instantiation-edge table in `WorkspaceIndex`, built once per
rescan, which would make both this and `incomingCalls` a lookup. That is
a `vlog_semantic` change and belongs in its own round; **request
recorded here, not made.**
recorded here, not made.** — **done, incremental-index, 2026-08-27.**
## Work log
+7
View File
@@ -15,6 +15,13 @@ per notification.
## Assumptions
- **Amended (incremental-index, 2026-08-27): one notification is still one
rescan, but a notification naming exactly one held source file takes the
incremental path** — that file's contribution replaced, no progress bar, no
log lines. A checkout filling the list, and a notification naming the
filelist, are whole rebuilds exactly as before. `watch::one_scope_file` is
the test. See `docs/features/incremental-index/README.md`.
- **Registration is the only way in.** The protocol has no static
`didChangeWatchedFiles` server capability — a server that wants file events
must ask for them with `client/registerCapability`, and only a client that
+33 -19
View File
@@ -59,13 +59,19 @@ pair unrolls as far as the user keeps clicking.
`TextRange::contains` excludes the end, which is right for a span of text
and wrong for a caret — that is where a double-click and an end-of-word
motion leave it.
- **The scope ladder decides which files are searched.** `incomingCalls`
reads `Workspace::sources()`, so a file a filelist or an `exclude` keeps out
of the index instantiates nothing, exactly as it references nothing
- **The scope ladder decides which files are searched.** `incomingCalls` reads
the index's instantiation-edge table (incremental-index, 2026-08-27; it read
`Workspace::sources()` before), so a file a filelist or an `exclude` keeps
out of the index instantiates nothing, exactly as it references nothing
(`docs/features/references-nav/README.md`).
- **Open buffers beat disk.** The same `sources()` overlay every other
- ~~**Open buffers beat disk.** The same `sources()` overlay every other
cross-file answer uses, so an instantiation just typed and not yet saved is
already a caller.
already a caller.~~ **Superseded (incremental-index, 2026-08-27): the census
is as of the index.** An index is built and updated from `collect_sources`,
which still overlays every open buffer — so a save, or any other rescan
trigger, makes a just-typed instantiation a caller. A keystroke alone no
longer does. The trade is argued in
`docs/features/incremental-index/README.md`.
- **Nested module declarations.** Legal SystemVerilog; today's parser recovers
them into sibling items rather than nesting them. The walk carries the
innermost enclosing declaration either way, so both spellings attribute
@@ -95,12 +101,13 @@ pair unrolls as far as the user keeps clicking.
- **Consumes `vlog_parser`** — `parse_source_tolerant` for every file that is
not the open buffer, `ast::Module`/`Instantiation` (read-only),
`Item::span`, `LineIndex`. Nothing new is asked of the crate.
- **Consumes `vlog_semantic::WorkspaceIndex`** — `units(name)` and
`path(file)`, to turn a module name into the file that declares it. The
index records what a file *declares* and **not what it instantiates**: there
is no edge table, which is why `incomingCalls` walks files rather than
querying. Adding such a table is a real option and is recorded as backlog
below rather than assumed here.
- **Consumes `vlog_semantic::WorkspaceIndex`** — `units(name)`, `path(file)`
and, since 2026-08-27, `instantiations_of(name)`. The index records what a
file instantiates now as well as what it declares, so `incomingCalls` is a
lookup and the walk-and-parse body it used to have is gone
(`docs/features/incremental-index/README.md`). The walk itself lives in
`vlog_semantic::instantiations` — lifted out of this crate so the index's
census and this module's per-buffer one are the same function.
- **Consumes `crate::state::Workspace`** — `document`, `index`, `text_of`,
`sources`. Nothing in `state.rs` was changed; the workspace stays immutable
through all three handlers, and no cache was added.
@@ -154,7 +161,14 @@ Release build, this machine, the checked-in 860-file corpus:
| `outgoingCalls` for the corpus's densest module (`uart_reg_top.sv`, 63 instantiation sites, 4 distinct resolvable targets) | **2.2 ms** |
| the same `incomingCalls` in a debug build | 106 ms |
Two things the table says. First, `incomingCalls` costs **4× less than M7's
**Superseded (incremental-index, 2026-08-27).** The table above is what the
walk cost; the edge table named below as "the place a future win lives" is
where it went — `incomingCalls` is a lookup, and the only I/O left is reading
the files that really do instantiate the name. The sibling measurement is a
whole file's code lenses over the same corpus, 92 ms → 0.26 ms
(`docs/features/incremental-index/README.md`). The reasoning the table
supported, kept legible:
~~Two things the table says. First, `incomingCalls` costs **4× less than M7's
`textDocument/references`** on the same corpus (218 ms) even though it answers
a superset of the question — it needs the *caller*, not just the span. The
reason is the prefilter: a module that is instantiated somewhere has its name
@@ -163,7 +177,7 @@ before it is parsed, and 834 of 860 files are. Second, what is left is
**almost entirely file I/O** — `sources()` reads every in-scope file whether
it will be parsed or not. That is the shared cost of every cross-file answer
in this server, and the place a future win lives (see backlog); nothing in
this feature can shave it alone.
this feature can shave it alone.~~
`prepare` and `outgoingCalls` never walk the workspace at all: they parse the
buffer and, at most, one file per distinct instantiated module.
@@ -208,12 +222,12 @@ lucisv-server qa_perf_worst_case -- --ignored --nocapture`).
- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets`,
`cargo test --workspace`, `editors/vscode/smoke.js`
- [x] `docs/features/lucisv-server/README.md` capability table + work log
- [ ] Not done, backlog: an **instantiation edge table in `WorkspaceIndex`**,
built with the index, which would make `incomingCalls` a map lookup and
cost one extra tree walk per file at index time. Worth doing when
something else wants the same edges (a design-tree view, an
unused-module lint); today one request in 56 ms does not justify
widening the index's contract.
- [x] ~~Not done, backlog:~~ **done (incremental-index, 2026-08-27):** an
**instantiation edge table in `WorkspaceIndex`**, built with the index,
which makes `incomingCalls` a map lookup and costs one extra tree walk
per file at index time. What finally wanted the same edges was the code
lens paying the same 56 ms on every request, and a round that had to
touch the index anyway.
- [ ] Not done, deliberately: type hierarchy (`typeHierarchy`) for classes,
interface and program instantiations as their own node kind, and any
whole-tree "show me the design" view — this milestone is exactly the
+673
View File
@@ -0,0 +1,673 @@
# incremental-index
## Goal
Until this round **any** change rebuilt the whole workspace index: a save of
one file re-read, re-tokenized, re-parsed and re-analyzed every file in scope,
rebuilt the completion tables and rebuilt the include graph. On the checked-in
860-file corpus that is 1.5 s of work, in a debug build, on every `didSave`.
This round makes the common case what it should always have been — **when
exactly one in-scope file changed, only that file's contribution is
replaced** — under an invariant strong enough to make the shortcut safe: the
index an update produces is *the index a whole rebuild would have produced*,
byte for byte. The same round lands the two edge tables that were filed as
Handshakes months apart and always wanted the same shape: **who instantiates
module M** and **who extends class C**, recorded as the index is built. With
them, `callHierarchy/incomingCalls`, `textDocument/codeLens` and
`typeHierarchy/subtypes` stop walking the workspace on every request and become
lookups — 92 ms → 0.26 ms for a whole file's code lenses, 82 ms → 0.71 ms for
`subtypes`, measured below.
## Assumptions
- **The equivalence invariant is the round.** For any workspace `W` and any
file `F` in it: `build(W)` and `build(W \ F).update_file(F)` are the *same
index* — same `FileId`s, same disambiguation order, same unit and member
tables, same edge tables, same per-file `` `define`` tables. Not "equivalent
where anything looks", **equal**: `WorkspaceIndex::fingerprint()` renders
every observable and the two fingerprints are compared directly. The same
holds for `remove_file`, and for the two composed into a rename.
- **A `FileId` is a position in the path-sorted file list and nothing else,
which is what it has always been.** The brief allowed interning ids per path
and retiring them, so that an insert or a remove would not renumber. That was
considered and **not** done, and the reason is the invariant above. Interned
ids differ between "a whole build" and "a build minus F, then F added back" —
F would take the next free id rather than its sorted-position one — so the
two histories could only be *equivalent*, never *equal*, and equality would
have to be re-established observable by observable in every consumer that
reads the numeral. Three do: `find_define` returns its hits in `FileId`
order, `candidates.rs` iterates `0..files().len()`, and the crate's own tests
compare `files()`. Renumbering keeps the strongest statement available —
*the same index* — and costs one merge pass over records already in memory,
no file read and no file re-parsed. **Disambiguation was already order-derived
and still is**: a name's declarations are pushed in one loop over the
path-sorted per-file records, so the order is the path order, and the ids
happen to agree with it because they are that same position. Nothing reads a
`FileId` numeral to decide an order.
- **Ids do not survive an add or a remove, and nothing in the tree holds one
across an update.** The only place a `FileId` is stored is a `Def` inside a
buffer's `ExternalResolutions`, and `update_one` refreshes every open
buffer's overlay exactly as `rebuild_index` does. The server is single
threaded and no update can interleave with a request.
- **The index keeps every file's contribution unmerged.** `FileFacts` — the
path, the define table, the file-scope declarations, the members, the
instantiation edges and the inheritance edges — used to live only until
`IndexBuilder::finish` and now lives in the index. That is what makes the
restricted re-merge possible, and it is the round's honest memory cost: the
same names and spans the merged tables hold, held once more, per file. No
`Semantics` and no source text is retained, exactly as before.
- **The cheap path is "a file the index already holds"**, and everything else
is a whole rebuild. A file *appearing* changes what other files' `` `include``s
resolve to, and answering that needs a walk; a file the index does not hold
is also how a brand-new file gets in at all. So the gate is one membership
test, and it is stated as such rather than guessed at per trigger.
- **A save carries no progress bar any more, and that is the visible protocol
delta.** The bar exists because a whole scan takes perceptible seconds; one
file is one parse. No bar, no per-file log line, and no scope warnings — the
last because warnings come from *resolving* the scope, and the scope was not
re-resolved. Everything else a rebuild does after the scan still happens: the
generation bump, the code-lens refresh, and a republish of every open buffer.
- **The republish stays wholesale.** Every open buffer's diagnostics are
computed against the index, so any of them may have moved; narrowing to "the
buffers that could have changed" needs a cross-file dependency graph this
server does not have. Filed, not guessed at.
- **The census is now as of the index, which is as of its last build or
update.** This is a real behaviour change and it is the one the round argues
hardest for. `hierarchy::callers_of_each` and `type_hierarchy::subtypes` used
to walk `Workspace::sources()` per request, which folds open buffers over
disk — so a keystroke in *another* buffer moved a code-lens count before
anything rebuilt. They read the index's edge tables now, and an index is only
ever as of its last build or update. Both of those fold every open buffer in,
so a save (or any rescan trigger) makes the edit count; a keystroke alone
does not. In exchange the lens, the call hierarchy and every other index-shaped
answer are consistent with each other by construction, and the census costs a
lookup instead of a workspace walk. Pinned from both sides in
`an_edited_buffers_instantiation_counts_from_the_moment_the_index_sees_it`
and `an_edited_buffers_extends_counts_from_the_moment_the_index_sees_it`.
- **The census *policies* did not move, and could not have**: the tables are
built by the very walks the request handlers used to run. One
`Instantiation` node is one site however many instances it declares; a
`generate for` body is one site, not the elaborated four; both arms of an
`` `ifdef`` are sites; matching is by the name as written; an instantiation at
file scope is not an edge, because nothing calls it; a gate primitive names
no module. Every one of `lens.rs`'s QA tests passes unchanged, and the same
policies are now pinned at the source of the numbers as well
(`the_instantiation_table_records_the_census_the_hierarchy_counts`).
- **An edge's spans are as of the index; the ranges are as of the text now.**
Turning a recorded byte span into a line/character range needs the file's
text, which is read fresh (open buffer beating disk, as always). For a buffer
edited since the last update the two disagree — the same staleness
`item_in_file` has carried since the hierarchy shipped, on the same files,
for the same reason.
- **The include graph's one incremental limit is stated rather than papered
over.** `IncludeGraph::update_file` re-scans the changed file's own edges and
re-learns the known-file and folded-spelling tables from the index's list; it
does **not** re-resolve any *other* file's edges. For the case the server uses
it in — one file's text changed, the file set did not — there is nothing
stale at all. When the update is a removal, another file's `` `include`` of
the removed file keeps its edge until the next whole rebuild. Named here
because it is the only thing in this round that is not exactly a rebuild.
- **The completion word table is exact, and pays for it in memory.**
`Candidates` keeps a per-file word list and a per-word file count, so one
file's words can be given back without re-lexing the other 859. Over the
corpus that is ~40k `String`s of per-file lists (QA measured 39,673 — the
work log's original ~170k estimate was 4.3x high; ~1.38 MB) on top of the
~17k distinct
words — single-digit megabytes, for the difference between "the word table is
correct" and "the word table drifts until something rebuilds".
## Handshakes
### `vlog_semantic` — the index gains an incremental API and two edge tables
```rust
impl WorkspaceIndex {
/// Insert or replace one file. Gives the index a whole build would have.
pub fn update_file(&mut self, path: PathBuf, src: &str);
/// Drop one file, reporting whether it was there.
pub fn remove_file(&mut self, path: &Path) -> bool;
/// Every observable, rendered — the equivalence witness.
pub fn fingerprint(&self) -> String;
pub fn instantiations_of(&self, name: &str) -> &[InstantiationEdge];
pub fn subclasses_of(&self, name: &str) -> &[InheritanceEdge];
pub fn instantiations(&self) -> impl Iterator<Item = (&str, &[InstantiationEdge])>;
pub fn subclasses(&self) -> impl Iterator<Item = (&str, &[InheritanceEdge])>;
}
pub struct DeclSite { pub name: String, pub name_span: TextRange, pub span: TextRange }
pub struct InstantiationEdge { pub file: FileId, pub owner: DeclSite, pub site_span: TextRange }
pub struct InheritanceEdge { pub file: FileId, pub subclass: DeclSite }
```
- `InstantiationEdge` carries the owner's whole `DeclSite` rather than just its
name span, because that is what a `CallHierarchyItem` is: `name` is the
item's name, `name_span` its `selectionRange`, `span` its `range`. The
code-lens README's proposed shape asked for "(file, instantiating-module name
span, instance site span)"; the extra two fields are what stopped
`callers_of_each` needing to re-parse the file to find them.
- `IndexCounts` gains `instantiations` and `inheritances`. Additive; every
field is still public and every existing read still compiles.
- **Two modules were lifted into this crate**, because the index now records
what they find and a second copy of either walk would be free to drift from
the one the request handlers use:
- `vlog_semantic::instantiations` — moved verbatim from
`lucisv_server::instantiations`. `hierarchy.rs`, `lens.rs` and `inlay.rs`
import it from here now; its own tests moved with it.
- `vlog_semantic::classes` — the class-declaration walk that was private to
`lucisv_server::type_hierarchy`, plus `extends_name`. `type_hierarchy.rs`
uses it and no longer has a copy.
- `IndexBuilder` is unchanged in shape and still sorts in `finish`; `finish` is
now `merge(None)` over the sorted records, which is the same loop
`update_file` runs restricted to the affected keys. **That is the equivalence
proof**: there is exactly one place any table's order is decided.
### `lucisv_server::state`
- `Workspace::update_one(&mut self, path: &Path) -> bool` — the incremental
rescan for one file. `false` means "not a file this index holds; rebuild".
It patches all four pieces of state a rebuild produces (index, completion
tables, include graph, every open buffer's overlay) and is documented
piece by piece at the function.
- `Workspace::update_one_checked` is the `#[cfg(test)]` paranoid form: it runs
the update, then rebuilds the whole workspace and asserts the two agree on
the index's fingerprint *and* on the completion word table.
### `lucisv_server::candidates` / `includes`
- `Candidates::update_file(index, path, text)` / `remove_file(index, path)` and
`IncludeGraph::update_file(path, text, known)` / `remove_file(path, known)`.
Both are the incremental forms of their `build`, and both are exact for the
case `update_one` uses them in.
### `lucisv_server::watch`
- `watch::one_scope_file(changes, filelist) -> Option<PathBuf>` — the one file a
watcher notification named, when it named exactly one and that one is not the
filelist. The gate on the fast path for the watcher trigger.
### `lucisv_server::server`
- `reindex_one(&mut self, path) -> bool`, taken by `didSave` and by a
one-file `didChangeWatchedFiles`, falling through to `reindex()` when it
declines.
## The fast-path trigger table
| trigger | path | bar |
|---|---|---|
| `didSave` naming one file the index holds | incremental | none |
| `didSave` naming a file the index does not hold (a new file) | whole rebuild | yes |
| `didChangeWatchedFiles` naming one held source file | incremental | none |
| `didChangeWatchedFiles` naming two or more files (a checkout) | whole rebuild | yes |
| `didChangeWatchedFiles` naming the filelist | whole rebuild | yes |
| `didChangeConfiguration` moving `exclude`/`filelist`/`maxFileSize`/`index.scope`/`index.scopeDepth` | whole rebuild | yes |
| `didOpen` that widened the scope | whole rebuild | yes |
| `didChangeWorkspaceFolders` that moved the root set | whole rebuild | yes |
| `didRenameFiles` / `didDeleteFiles` | whole rebuild | yes |
Pinned by `the_fast_path_is_taken_for_one_held_file_and_for_nothing_else`
(rows 1–5 and the settings row) and by the tests the earlier rounds left on
the remaining rows.
## Derived state, and how each piece is patched
| state | what it reads | on an incremental update |
|---|---|---|
| `WorkspaceIndex.files` / `facts` | the file set | one record replaced, inserted or removed |
| `units`, `members` | every file's declarations | the keys this file declared before or declares now, re-merged from the records in path order |
| `instantiations`, `subclasses` | every file's edges | same, keyed by instantiated module / base class |
| `defines` | this file only | replaced with the record |
| `Candidates::units` / `macros` | the index alone | re-derived from the (already updated) index |
| `Candidates::words` | every file's tokens | this file's words given back and its new ones taken, by per-word file count |
| `IncludeGraph::edges` | this file's `` `include``s | re-scanned for this file; other files' left standing (see Assumptions) |
| `IncludeGraph::known` / `folded` | the file set | re-learned from `index.files()` |
| every open buffer's `ExternalResolutions` | the index | refreshed, as after a rebuild |
| the diagnostics generation | — | bumped |
| the client's code lenses | the index | refresh requested |
An add or a remove takes the *whole* merge rather than the restricted one,
because every id after the change moves; it is still one pass over records in
memory, with no file read and no file re-parsed.
## Measured
Debug build, this Mac, the checked-in 860-file corpus, printed by the
`#[ignore]`d probes (`cargo test -p lucisv_server -- --ignored --nocapture`).
| | before | after |
|---|---:|---:|
| `textDocument/codeLens`, a three-module file | 92 ms (one workspace walk, then a parse of every file mentioning a name) | **0.26 ms** |
| `typeHierarchy/subtypes`, `core_ibex_base_test` | 82 ms (same shape) | **0.71 ms** |
| rescan after one file changed | 1.50 s (whole rebuild) | **33 ms** (45×) |
The "before" column for the two requests is measured in the same probe as the
"after": `Workspace::sources()` is still there and still costs what it always
did, so the row is one walk of the corpus against the lookup that replaced it,
in the same process on the same run. The reindex row is the whole rebuild and
the one-file update measured back to back over the same workspace.
The 33 ms is dominated by two things that are *not* the file: re-deriving the
completion `units`/`macros` tables from the index (a `workspace_symbols("")`
over ~12k members, sorted) and the merge pass over every file's records. Both
are O(index), not O(files read), and neither parses anything. Making them
O(change) is possible and was not done: 45× is the win that was asked for, and
the next 3× is a bigger change to `Candidates` than this round should carry.
## Status / TODO
- [x] `WorkspaceIndex::update_file` / `remove_file`, exact-equality equivalence
with a whole build, pinned from six directions
- [x] `WorkspaceIndex::fingerprint` as the one equivalence witness, used by
both crates' tests
- [x] Instantiation and inheritance edge tables, built by the walks the request
handlers used to run
- [x] `hierarchy::callers_of_each` is a lookup; its `sources()` walk deleted
- [x] `lens.rs` counts through it unchanged; `type_hierarchy::subtypes` is a
lookup
- [x] The census policies pinned at the source of the numbers as well as at the
lens
- [x] `Workspace::update_one` patching index, completion tables, include graph
and every open buffer's overlay
- [x] `Server::reindex_one`: no bar, no log, no scope warnings; generation
bumped, lenses refreshed, every open buffer republished
- [x] The fast-path trigger table, pinned row by row
- [x] The paranoid corpus sweep: every mutation checked against a whole rebuild
- [x] The three inherited obligations from index-scope's Review
- [ ] **Not done, deliberately:** no narrowing of the republish. A lint reads
the index, so any open buffer's diagnostics may have moved; narrowing
correctly needs a dependency graph this server does not have, and
narrowing incorrectly is a stale red squiggle.
- [ ] **Not done, deliberately:** no incremental path for a file appearing or
vanishing *without* the index already holding it. It is a rebuild, it is
rare, and the include graph's cross-file resolution is what makes it one.
- [ ] **Not done, deliberately:** the index is not updated on `didChange`. A
keystroke would cost a second parse and a second analysis of the buffer
on top of the one `Document::new` already does, per keystroke, to make a
count in *another* file fresher than the file on disk.
- [ ] **Filed, not done:** `Candidates::units`/`macros` are re-derived whole on
every incremental update. They are index-derived and correct; they are
also most of the 33 ms.
- [ ] **Filed, not done:** an incremental update cannot re-resolve another
file's `` `include`` when a file is removed. See Assumptions.
## Work log
### 2026-08-27 — dev agent (incremental single-file updates, the edge tables)
- **The FileId decision was the first one and it went against the brief, with
the invariant as the argument.** The brief asked for interned, retired ids so
that an insert would not renumber. Interning makes ids *stable* but makes the
two histories the round has to compare merely equivalent, and the brief's own
acceptance test says to make the equivalence exact if anything observable
reads the numeral — three things do. Renumbering keeps `FileId` meaning
exactly what it has always meant (a position in the path-sorted list), makes
the comparison a string equality on a fingerprint, and costs one merge pass
over in-memory records. The stability interning would have bought is worth
nothing here: the only `FileId`s that outlive a call are the ones in each
buffer's overlay, and those are refreshed by the update itself.
- **The merge is the equivalence proof, not a test of it.** `IndexBuilder::finish`
and `WorkspaceIndex::update_file` both end in one function, `merge`, which
loops over the path-sorted per-file records pushing what it meets. `merge(None)`
rebuilds every table; `merge(Some(affected))` clears and refills only the keys
the changed file could have moved. Same loop, same order, so a restricted
merge and a whole one cannot disagree — there is nowhere for them to disagree.
That is why the round could afford to keep the per-file records rather than
invent a patching scheme with its own ordering rules.
- **The affected set is coarse on purpose.** `members` is keyed by unit and the
affected set names *units*, not `(unit, member)` pairs: rebuilding one whole
package's member sub-table is a handful of entries, and a finer key would be
a second ordering rule to keep honest.
- **Two walks were lifted into `vlog_semantic` rather than copied.** The
instantiation census is what `lens.rs`'s QA tests pin, so a second copy of
that walk inside the index would have been licence for the numbers to drift.
`instantiations.rs` moved whole (its tests with it) and
`type_hierarchy`'s private class walk became `classes.rs`. Both moves are
mechanical; the census policies are now a property of one function each.
- **The unsaved-buffer census delta is the round's one behaviour loss and it is
argued rather than hidden.** Two tests pinned "a just-typed instantiation in
another buffer counts": they were the walk's own freshness, not a policy, and
they cannot survive a table built at index time. Both are rewritten in the
house style under `// Superseded this round:` to pin the new rule from both
sides — the buffer alone moves nothing, and the update moves it. The three
alternatives were considered and rejected in the README's Assumptions: a
per-keystroke index update (a second parse and analysis per keystroke), an
edges-only per-keystroke update (breaks the equivalence invariant outright —
edges from the buffer, declarations from disk, an index equal to no build at
all), and a live overlay of dirty buffers over the table (needs dirty
tracking the server does not do).
- **Eight progress tests changed, all for the same one reason and none of them
weakened.** A save is the trigger those tests reached for when they needed a
rescan, and a save is exactly what stops being one. Each now uses a trigger
that really does rescan — two files in one watcher event, or a settings
change — and keeps its own subject (the bar goes up and comes down, the bar
is down before the republish, the refresh rides after it, three outstanding
requests answer by id). `a_save_puts_a_bar_up_and_takes_it_down_again` was
renamed to name the trigger it now uses, and the property it used to carry —
that a save reports itself — is replaced by
`a_one_file_save_costs_no_bar_and_no_log_line`, which is the new rule.
- **One lens test's assertion was superseded, and its replacement is stronger.**
`code_lenses_for_a_whole_file_cost_about_one_workspace_walk` asserted
`whole_file < one_name * 2` — "the batch is one walk, not one per module".
There is no walk; both sides are microseconds dominated by one file read
each, so the ratio pins noise. It now asserts what the round actually bought:
a whole file's lenses cost less than a tenth of one workspace walk, measured
in the same loop.
- **The e2e progress transcript lost a bar**, which is the model becoming
visible on the wire again: startup (empty scope, `0 files indexed`), the
widening `didOpen` (`1 file indexed`), and then a save that reports nothing
because it is one parse.
- **The three inherited obligations are pinned as permanent tests**, in
`state.rs` beside the scope tests they belong with: lowering `scopeDepth`
narrows the index on the next rescan (the settings axis moves both ways,
unlike the open axis); a filelist appearing mid-session flips the ladder to
rung 1 *and changes what is indexed*, with the open buffer still overlaid;
and a buffer opened outside every root rides the folder rung like a rootless
one, its own directory at depth 0 and `/` at depth 99.
- Files touched: `crates/vlog_semantic/src/workspace.rs`,
`crates/vlog_semantic/src/lib.rs`,
`crates/vlog_semantic/src/instantiations.rs` (moved in),
`crates/vlog_semantic/src/classes.rs` (new),
`crates/vlog_semantic/tests/workspace.rs`,
`crates/lucisv_server/src/{state,server,hierarchy,lens,type_hierarchy,inlay,candidates,includes,watch,main}.rs`,
`crates/lucisv_server/tests/e2e.rs`, `TODO.md`,
`docs/features/{code-lens,type-hierarchy,hierarchy,workspace-index,lucisv-server,indexing-ux,work-done-progress,file-watching}/README.md`,
this README. No new dependency, no version bump, no `docs/site/`, no commits.
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
--all-targets --workspace`: zero warnings. `cargo test --workspace`: **2244
passed, 0 failed, 8 ignored** — measured against a clean `HEAD` worktree's
**2217 passed, 5 ignored**, so 27 new passing tests and 3 new `#[ignore]`d
probes, with 2 superseded in place and 1 renamed.
`cargo test -p vlog_formatter`: 180 passed across its seven binaries (114 of them `verification.rs`), untouched — `verify.rs` never appears in this round's diff. `cargo build && node
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`.
The 30 new tests, and what each is for:
| test | pins |
|---|---|
| `adding_a_file_gives_the_index_a_whole_build_would_have` (vlog_semantic) | the hard direction: the new file sorts first, so every later id and every table naming one moves |
| `replacing_a_file_touches_only_what_that_file_said` (vlog_semantic) | the restricted merge: the other file's edge survives, the replaced file's does not |
| `removing_a_file_gives_the_index_a_whole_build_would_have` (vlog_semantic) | removal, renumbering down, edges going with the file, removing twice |
| `removing_a_file_moves_the_disambiguation_winner` (vlog_semantic) | the sharpest derived answer: the file that won a duplicate name is the file that goes |
| `a_file_that_redefines_a_name_another_file_declares_lands_in_path_order` (vlog_semantic) | insertion into a table that already holds the other file's copy, both directions |
| `a_rename_is_a_remove_and_an_add_and_lands_where_a_build_would_put_it` (vlog_semantic) | the rename-shaped sequence |
| `an_update_survives_every_degenerate_file_there_is` (vlog_semantic) | empty, whitespace, not-Verilog, does-not-lex, comment-only; and an empty index |
| `a_full_build_and_a_build_minus_one_plus_that_one_are_the_same_index` (vlog_semantic) | the headline invariant, over a six-file fixture, with **every** file taken out and put back |
| `the_instantiation_table_records_the_census_the_hierarchy_counts` (vlog_semantic) | every census policy at the source of the numbers, plus the spans a hierarchy item is built from |
| `the_inheritance_table_records_every_class_that_names_a_base` (vlog_semantic) | file order, a parameterized base, a class in a package, a class in a module, the counts |
| `the_edge_tables_are_empty_for_a_workspace_with_no_edges` (vlog_semantic) | the degenerate lookups, and a default index |
| `only_a_file_the_index_already_holds_takes_the_incremental_path` (state) | the gate, from four sides, including a file that becomes held |
| `one_files_edit_reaches_every_table_the_index_answers_from` (state) | declaration, instantiation edge, inheritance edge, completion word, include edge — all five in one update |
| `a_file_the_cap_or_the_disk_takes_away_leaves_the_index` (state) | removal through `update_one`: deleted on disk, and grown past the cap |
| `an_open_buffer_beats_disk_on_the_incremental_path_too` (state) | `collect_sources`'s precedence, for one file |
| `the_incremental_update_agrees_with_a_whole_rebuild_over_the_real_corpus` (state) | the paranoid sweep: 172 real files, 6 mutated five ways, every one checked against a whole rebuild |
| `lowering_the_scope_depth_narrows_the_index_on_the_next_rescan` (state) | inherited obligation (a) |
| `a_filelist_appearing_mid_session_flips_the_ladder_to_rung_one` (state) | inherited obligation (b), on the index's content and not just the rescan |
| `a_buffer_opened_outside_every_root_rides_the_folder_rung_like_a_rootless_one` (state) | inherited obligation (c), at depth 0 and at depth 99 |
| `qa_perf_one_file_against_the_whole_rebuild` (state, `#[ignore]`) | the 45× |
| `the_fast_path_is_taken_for_one_held_file_and_for_nothing_else` (server) | the trigger table, five rows |
| `a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses` (server) | what the fast path keeps |
| `a_one_file_save_costs_no_bar_and_no_log_line` (server) | what it drops |
| `a_one_file_save_answers_from_the_file_it_saved` (server) | the edit reaches the index and the rest of the workspace is untouched |
| `a_whole_rescan_puts_a_bar_up_and_takes_it_down_again` (server, renamed) | the bar's own rule, on a trigger that still rescans |
| `qa_perf_lens_lookup_against_the_walk_it_replaced` (lens, `#[ignore]`) | 0.26 ms against 92 ms |
| `qa_perf_subtypes_lookup_against_the_walk_it_replaced` (type_hierarchy, `#[ignore]`) | 0.71 ms against 82 ms |
| `a_save_of_one_file_updates_the_index_over_the_wire` (e2e) | the real binary: the save moves the definition answer, and the untouched file answers exactly what it did |
| `a_class_is_found_wherever_it_may_be_written`, `a_parameterized_base_names_the_bare_class`, `a_declarations_extent_contains_its_own_name` (vlog_semantic `classes`) | the lifted walk, in its new home |
Two tests were superseded in place and are named in the work log above:
`an_unsaved_instantiation_is_a_caller_before_it_is_saved` and
`an_unsaved_extends_is_a_subtype_before_it_is_saved`, both replaced by the
`…counts_from_the_moment_the_index_sees_it` form; and
`code_lenses_for_a_whole_file_cost_about_one_workspace_walk` was renamed and
given the stronger assertion.
## QA log
### 2026-08-27 — QA agent (equivalence attack pass)
**Verdict up front: committable as-is.** No production-code defect found
under any constructed attack. One documentation-accuracy finding (LOW,
non-blocking) in the Assumptions section's memory estimate. Nine new tests
added, all passing, none exposing a bug — they pin behavior that was correct
but unverified against the specific adversarial shapes below.
**Gates, re-run from a clean state (before adding anything):**
`cargo fmt --all -- --check` clean. `cargo clippy --all-targets --workspace`
zero warnings. `cargo test --workspace`: 2244 passed, 0 failed, 8 ignored —
matches the dev's own count exactly. `cargo test -p vlog_formatter`: 180
passed across seven binaries (114 `verification.rs`) — `verify.rs` does not
appear anywhere in `git diff 7266b13` (`git diff --name-only | grep verify`:
empty). `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`:
`smoke: OK`. After adding the tests below, `cargo test --workspace`: **2253
passed, 0 failed, 8 ignored** (2244 + 9 new), fmt and clippy still clean.
**1. The ghost hunt and the affected-keys verdict — verified clean.**
`WorkspaceIndex::update_file`'s `Ok(at)` arm computes `affected` as
`Affected::of(&self.facts[at])` (the *old* record's names) then
`affected.add(&facts)` (the *new* record's names) — a union of both sides,
read directly at `crates/vlog_semantic/src/workspace.rs:311-315`. That is the
side that matters: a name only the old record declared is still in the
cleared set even though the new record no longer supplies it, so `merge`'s
`self.units.remove(name)` followed by a full re-scan of **every** file's
current facts (not just the changed one, `workspace.rs:422-460`) leaves
nothing behind for it — no stale one-entry `Vec` survives. Constructed the
exact ghost explicitly:
`a_name_only_one_file_declared_leaves_no_ghost_when_that_file_stops_declaring_it`
(vlog_semantic `tests/workspace.rs`) — a file that is the *sole* declarer of
`solo` stops declaring it; `units("solo")` comes back empty and the
fingerprint matches a fresh build. Passes. The same union covers edge-table
keys too: `Affected::add` extends `modules` from `facts.instantiations` and
`bases` from `facts.subclasses` (`workspace.rs:487-489`), so a file that stops
instantiating `M` shrinks `M`'s table the same way — already covered by the
dev's own `replacing_a_file_touches_only_what_that_file_said`, re-verified
here by re-running it and by the new sequence test below.
**2. Byte-identical histories, adversarially — six new tests, all pass**
(`crates/vlog_semantic/tests/workspace.rs`):
- `a_long_interleaved_sequence_matches_a_fresh_build_at_every_step` — update
A, update B, remove A, re-add A, update B again, fingerprint-checked after
**every** step (not just at the end, which would miss a bug that only shows
two steps later).
- `a_name_only_one_file_declared_leaves_no_ghost_when_that_file_stops_declaring_it`
— the ghost hunt above.
- `adding_a_new_file_that_duplicates_an_existing_name_lands_by_path_order_either_direction`
— the dev's own duplicate-name test only attacks the restricted-merge
(`Ok(at)`) arm; this attacks the whole-merge (`Err(at)`, brand-new file)
arm, both sort directions.
- `find_define_answers_in_current_file_id_order_after_cross_file_updates` —
`` `define``/`` `undef`` shadowing across files, then a renumbering add, then
the answer re-checked in the new id order.
- `updating_a_file_to_empty_text_differs_from_removing_it` — confirmed
**different**, deliberately: `update_file(path, "")` keeps the file's
`FileId` slot (still a file, contributing nothing); `remove_file` drops the
slot and renumbers everything after it. Not pinned anywhere else in the
round's own tests, so pinned here.
- `same_named_files_in_different_directories_updated_alternately_stay_correct`
— two files named `defs.sv` in different directories, updated A then B then
A again, fingerprint-checked at each step (identity is the path,
`binary_search_by` compares `PathBuf`s, never the filename alone).
**3. The moved walks — verbatim, confirmed byte-for-byte.**
`diff` of `crates/lucisv_server/src/instantiations.rs` (at `7266b13`) against
`crates/vlog_semantic/src/instantiations.rs`: the only changes are added doc
comments (the "Lifted from..." note and two new one-line field docs); every
line of code, every test, is identical. `classes.rs` is new but its three
functions (`declarations`, `collect`, `extends_name`) are line-for-line
identical to the private walk `type_hierarchy.rs` used to carry (compared
directly against `git show 7266b13:crates/lucisv_server/src/type_hierarchy.rs`
lines 141-274). `hierarchy::callers_of_each` and `type_hierarchy::subtypes`
were rewritten (not moved) to read the new edge tables instead of walking
`Workspace::sources()`; read both in full. The file-grouping `subtypes` and
`callers_in` rely on ("edges arrive in file order, so one file's are
consecutive") holds by construction: `merge` always fully clears and
rebuilds an affected key's whole vector by iterating `self.facts` in
ascending `FileId` order (never appends to a partial vector across separate
merges), so the grouping invariant cannot be violated by any sequence of
incremental updates, not just the initial build. Re-ran `lens.rs`'s QA policy
tests and `the_instantiation_table_records_the_census_the_hierarchy_counts` /
`the_inheritance_table_records_every_class_that_names_a_base` — unchanged,
passing. `git diff --stat` on `hierarchy.rs`/`type_hierarchy.rs`/`lens.rs`
test bodies: exactly the two superseded freshness tests
(`an_unsaved_instantiation_is_a_caller_before_it_is_saved` →
`an_edited_buffers_instantiation_counts_from_the_moment_the_index_sees_it`,
and the `extends` equivalent) plus the renamed/strengthened lens ratio test
(`code_lenses_for_a_whole_file_cost_about_one_workspace_walk` →
`..._a_fraction_of_a_workspace_walk`) and one doc-comment-only touch on
`qa_perf_worst_case_common_word_module_name` (no logic change). Each
supersession keeps the original point per house style: both rewritten tests
assert the buffer alone does *not* move the count and then that
`ws.update_one(path)` does — the same "unsaved edit is visible" property the
old tests pinned, restated for a table that is index-fresh rather than
per-request-fresh.
**4. `Candidates::words` exact bookkeeping — two new tests, both pass**
(`crates/lucisv_server/src/candidates.rs`):
`a_shared_word_dropped_from_one_file_is_still_offered_by_the_other` and
`updating_the_same_file_twice_in_a_row_never_double_counts_or_goes_negative`.
Read `set_words` (`candidates.rs:78-99`): it removes the *previous* call's
words for this path before counting the new ones, so calling it twice in a
row for the same path decrements based on the first call's own words, never
double-decrements, and never underflows.
**5. The freshness delta's edges — verified against the code, not just the
docs.** `hover::narrowed_to_the_include_graph` (`hover.rs:84-105`) is the
concrete case: `candidates` come from `find_define`, which only ever
enumerates files the index *currently* holds, while `reachable` comes from
`includes::reachable_from`, whose first hop is resolved live off the buffer's
own current text (`includes.rs:344-350`, "resolved against the buffer's
*current* text rather than looked up in the graph") — buffer-fresh — before
walking the rest of the graph via the index-fresh `IncludeGraph::edges`. The
docs (`code-lens`, `hierarchy`, `type-hierarchy` READMEs, and this feature's
own Assumptions) consistently say which surfaces are index-fresh (lens
counts, `incomingCalls`, `subtypes`) versus buffer-fresh (an include's own
first hop, go-to-definition, document links) — no surface was found
mismarked.
**6. Fast-path discipline.**
- Two saves in one batch: added
`two_saves_of_different_held_files_in_one_batch_are_two_incremental_updates`
(`server.rs`). `process_batch` handles one message at a time
(`for message in batch`, `server.rs:316`), so two `didSave`s in one burst
are **two independent incremental updates**, not coalesced and not a full
rebuild — confirmed: no progress bar, both files' edits land, generation
bumps by 4 (2 saves × 2 bumps each — `set_document` bumps once for the
buffer's own new text, `reindex_one` bumps once more for the fast path;
these are orthogonal and both fire per save, which the test now pins
explicitly since it was not obvious from the docs alone).
- Generation bump / lens refresh / resultId: `reindex_one` bumps `generation`
exactly once and calls `refresh_code_lenses()` exactly once
(`server.rs:1365-1374`), pinned by the dev's own
`a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses`.
`result_id()` is `self.generation.to_string()` (`server.rs:1024-1025`), so
a fast-path update does move a pull-diagnostics client's `resultId` — no
new test needed, it follows directly from the generation bump.
No-bar/no-log: pinned by `a_one_file_save_costs_no_bar_and_no_log_line`,
re-run, passing.
- A save during another operation: the server is single-threaded and
`process_batch` runs to completion before the next receive, so there is no
interleaving to attack — matches the dev's own note.
- A file whose *path* is held but which *is* the filelist: not reachable in
practice — a filelist is a `.f`/similar file, never a `.sv`/`.v`/`.svh`
source, so it is never a member of `self.index.files()` and
`Workspace::update_one`'s gate (`state.rs:36`) returns `false` for it
regardless of the watcher-side `one_scope_file` exclusion
(`watch.rs:27-38`) — the two gates agree by construction rather than by
coincidence, so no separate test was added for this shape.
**7. The include-graph gap — severity-checked, confirmed LOW/harmless
(dangling, not wrong).** Traced every consumer of `IncludeGraph::edges`: only
`reachable`/`reachable_from` read it (`document_links`/`definition` resolve
live off disk via `resolved()`, never consulting `self.edges`). After a file
`B` is removed, another file `A`'s stale forward-edge to `B` can make
`reachable(A)` include `B`'s now-dangling path — but `B` has no `FileId` in
the index any more, so `hover::narrowed_to_the_include_graph`'s filter
(`ws.index().path(*file).is_some_and(|p| reachable.contains(p))`) can never
match a *candidate* against that ghost path, because no surviving file's
current path can equal a path the index no longer assigns to anyone. The
answer is a superset that can only ever be harmlessly too permissive, never
one that manufactures a wrong single-file narrowing. It self-heals the moment
`A` itself is next incrementally updated (`IncludeGraph::update_file`
re-resolves `A`'s own edges fresh off disk). No test added — this is a
reachability argument about aliasing that a unit test would have to
special-case anyway; recorded here for the record instead.
**8. Perf and memory claims — spot-reproduced, one discrepancy found.**
Reproduced all three timing claims on this machine, same corpus, debug build:
`qa_perf_one_file_against_the_whole_rebuild`: 1.517 s → 33.8 ms (45×, matches
the README's 1.50 s → 33 ms exactly). `qa_perf_lens_lookup_against_the_walk_it_replaced`:
67.1 ms → 0.297 ms (README: 92 ms → 0.26 ms — same order of magnitude, machine
variance accounts for the rest). `qa_perf_subtypes_lookup_against_the_walk_it_replaced`:
66.9 ms → 0.720 ms (README: 82 ms → 0.71 ms — very close). All three: **verified
clean.**
**Finding (LOW, documentation accuracy, non-blocking).** The Assumptions
section's memory estimate for `Candidates::per_file` — "Over the corpus that
is ~170k `String`s of per-file lists on top of the ~17k distinct words —
single-digit megabytes" — was checked against the real corpus with a scratch
probe (`Candidates::build` over all 860 corpus files, then
`per_file.values().map(Vec::len).sum()` and a byte estimate from
`String::capacity()`; probe not kept, reproducible in one line from a REPL-ish
test). Measured: **16,750 distinct words** (matches the "~17k" half of the
claim) but **39,673 per-file word entries** — about **4.3× lower** than the
claimed "~170k" — and **~1.38 MB** of per-file `String` storage, itself well
under "single-digit megabytes." The *conclusion* ("single-digit megabytes,"
i.e. the design is memory-cheap enough) is not undermined — if anything the
real number is more favorable than claimed — but the specific "~170k" figure
in the Assumptions section does not match reality and is not pinned by any
test in the round. Not blocking; worth a one-line correction next time this
README is touched.
**9. CLAUDE.md compliance.** No `unwrap()`/`expect()`/`panic!` in library code
in any touched file, checked by grepping each file up to its own
`#[cfg(test)]` module (`workspace.rs`, `instantiations.rs`, `classes.rs`,
`state.rs`, `candidates.rs`, `includes.rs`, `server.rs`, `watch.rs`,
`hierarchy.rs`, `type_hierarchy.rs`, `lens.rs`) — zero matches in all eleven.
No `unsafe` anywhere in the diff. This README has all seven required
sections, each exactly once (plus three extra ones the format allows: the
fast-path trigger table, the derived-state table, Measured). `verify.rs` does
not appear in the diff at all. Every corpus-dependent test checked is
skip-guarded (`if !corpus.is_dir() { ...; return; }`). `TODO.md`'s completed
items are struck through with the original text kept and a note appended,
matching the project's existing convention for closing an item without
deleting it. `docs/site/` diff is empty — untouched, as required. Spot-checked
the struck Handshakes in `code-lens` and `hierarchy` READMEs against the
actual code (`instantiations_of`/`subclasses_of` signatures, the lifted
`vlog_semantic::instantiations`/`classes` modules) — accurate.
**Fixes made:** none to production code — every constructed attack passed.
**Tests added (9, all passing):** the six `vlog_semantic` tests and two
`candidates.rs` tests listed above, plus
`two_saves_of_different_held_files_in_one_batch_are_two_incremental_updates`
in `server.rs`.
## Review
### 2026-08-27 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself
(2253 workspace tests, 0 failed), clean. The round's deviation was
better than my brief: keeping FileIds as sorted positions and paying
one in-memory merge per update buys byte-identical histories — the
strongest equivalence there is — where my interned-ids design would
have bought mere observational equivalence plus three consumers to
audit forever. The structural argument (finish and update_file ending
in the one merge over path-sorted records) is the same
one-implementation discipline this codebase now uses everywhere, and
QA's ghost hunt confirmed the affected-keys union reads both the old
and new records, which is the single place the design could have
silently rotted. The moved census walks are byte-for-byte verbatim,
the policy numbers stand, and the freshness delta — counts as of the
index, not of unsaved keystrokes — is the right trade, pinned from
both sides.
The measured wins close two of the audit's oldest filed Handshakes
with a 350x lens speedup and a 45x one-file rescan, on top of the
scope round's narrowing — together these are the large-workarea story
the owner asked for. QA's nine adversarial tests (the long
sequences, define shadowing across renumbering, burst double-saves)
are permanent. I corrected the one LOW finding (the per-file word-list
estimate, 4.3x high; the conclusion stood). The three filed leftovers
(wholesale republish, Candidates re-derivation cost, the include
removal edge) are honest and none blocks. Accepted as shipped.
+7
View File
@@ -156,6 +156,13 @@ pub fn build<'a>(files: …) -> WorkspaceIndex {
unwatched forms. `server.rs` always watches, so the unwatched pair is now
reachable from tests alone and is `#[cfg(test)]` — several dozen call sites
across the crate, none of which has an opinion about progress.
- **Amended (incremental-index, 2026-08-27):** a rescan triggered by exactly
one file the index already holds does not go through `rebuild_index_with` at
all — it is `Workspace::update_one`, which reports no events, puts no bar up
and writes no log lines, because one parse is not a scan to narrate. Every
whole rescan is unchanged. The cap still applies, through the same
`oversize` test, and a file that grew past it leaves the index on the
incremental path too.
- `pub enum IndexEvent<'a> { Parsing { done, total, path }, Skipped { path,
size, cap } }`. Numbers and paths only: this module speaks no protocol, and
the wording of every message stays in `server.rs`.
+17 -11
View File
@@ -43,12 +43,12 @@ looks like language knowledge in here is a bug or a `Handshake` request.
| `textDocument/signatureHelp` | `vlog_refactor::instantiation_plan` | The instantiated module's ports (or, inside `#( ... )`, its parameters) with the active one highlighted — by name for a named list, by position for an ordered one. Triggers: `(` and `,`. Same feature README |
| `textDocument/inlayHint` | `vlog_refactor::instantiation_plan` | Ghost port names on an **ordered** connection list (`u1 (clk, rst_n)`) and parameter names on ordered `#( ... )` overrides, read from the instantiated module's declaration. Range-scoped; named lists, `.*`, omitted positions, connections past the last port, gate primitives and modules the index cannot resolve get nothing at all — a hint is decoration and never guesses. No `resolveProvider`. See `docs/features/inlay-hints/README.md` |
| `textDocument/prepareCallHierarchy` | `instantiations::{sites,declarations}`, `WorkspaceIndex::units` | The module under the cursor as a hierarchy node (`SymbolKind::Module`), from its own declaration or from any instantiation of it. Every other position answers `null`; an ambiguous name returns every declaration, as `definition` does. See `docs/features/hierarchy/README.md` |
| `callHierarchy/incomingCalls` | `instantiations::sites` over `Workspace::sources` | "Who instantiates X": one call per **instantiating module**, `fromRanges` naming every site inside it. Walks the in-scope files — the index holds no instantiation edges — skipping any file whose text does not contain the name (56 ms over the 860-file corpus). Since 2026-08-26 this is `hierarchy::callers_of_each` with a one-name batch; the batched form is what `textDocument/codeLens` counts from, so there is exactly one census. Same feature README |
| `callHierarchy/incomingCalls` | `WorkspaceIndex::instantiations_of` | "Who instantiates X": one call per **instantiating module**, `fromRanges` naming every site inside it. A **lookup in the index's instantiation-edge table** since 2026-08-27 (it walked every in-scope file before, 56 ms over the 860-file corpus); only the files that really do instantiate the name are read, to turn recorded spans into ranges. The census is as of the index — its last build or update, both of which fold every open buffer in. Since 2026-08-26 this is `hierarchy::callers_of_each` with a one-name batch; the batched form is what `textDocument/codeLens` counts from, so there is exactly one census. Same feature README |
| `callHierarchy/outgoingCalls` | `instantiations::sites`, `WorkspaceIndex::units` | "What X instantiates": one call per **distinct instantiated module**, `fromRanges` naming its sites. A target the index does not hold, or holds twice, is skipped silently. Same feature README |
| `textDocument/prepareTypeHierarchy` | the class walk over `Document.tree`, then `ExternalResolutions::definition_of` | The **class** under the cursor as a type hierarchy node (`SymbolKind::Class`), from its own declaration or from any use of its name (an `extends` base, a property's type, a method local's type). Every other position answers `null`; a name two files declare returns both, as `definition` does. Advertised by hand — `lsp-types` 0.97's `ServerCapabilities` has no `typeHierarchyProvider` field. See `docs/features/type-hierarchy/README.md` |
| `typeHierarchy/supertypes` | `ClassDecl::extends` + `ExternalResolutions::definition_of` | "What X extends": its base class, resolved by the same two layers F12 uses — in-file first, then the workspace overlay — asked at the **last byte** of the extends name, which is the tail of `pkg::base` and the whole of a bare `base`. A parameterized base resolves by its bare name; a base the workspace does not index (every UVM chain top) yields **no** item rather than a guess. Same feature README |
| `typeHierarchy/subtypes` | the class walk over `Workspace::sources` | "Who extends X": every class in scope whose `extends` names it, sorted by file then position. Walks the in-scope files — the index holds no inheritance edges — skipping any file whose text does not contain the name (55 ms over the 860-file corpus, 53 ms of it file I/O). A **qualified** base is not matched by a bare name, the `callHierarchy` precedent; 0 of the corpus's 270 `extends` clauses are qualified. Same feature README |
| `textDocument/codeLens` | `instantiations::declarations` + `hierarchy::callers_of_each` | **"N instantiations"** above every module and interface declaration in the buffer, on the declaration's own name span. N is the number of instantiation *sites* across the workspace — the same population `callHierarchy/incomingCalls` reports, from the same walk asked about every module in the file at once, so the two can never disagree. `resolveProvider: false`: every lens is complete. Clicking runs `lucisv.showInstantiations`; a module with **no** instantiations gets a display-only lens (empty `command`) instead of a click that leads nowhere. Unopened buffer → `null`; a declaration with no name span gets no lens. See `docs/features/code-lens/README.md` |
| `typeHierarchy/subtypes` | `WorkspaceIndex::subclasses_of` | "Who extends X": every class in scope whose `extends` names it, sorted by file then position. A **lookup in the index's inheritance-edge table** since 2026-08-27 (it walked every in-scope file before, 55 ms over the corpus; 0.71 ms now). A **qualified** base is not matched by a bare name, the `callHierarchy` precedent; 0 of the corpus's 270 `extends` clauses are qualified. Same feature README |
| `textDocument/codeLens` | `instantiations::declarations` + `hierarchy::callers_of_each` | **"N instantiations"** above every module and interface declaration in the buffer, on the declaration's own name span. N is the number of instantiation *sites* across the workspace — the same population `callHierarchy/incomingCalls` reports, from the same edge table asked about every module in the file at once, so the two can never disagree (92 ms → 0.26 ms for a three-module file, 2026-08-27). `resolveProvider: false`: every lens is complete. Clicking runs `lucisv.showInstantiations`; a module with **no** instantiations gets a display-only lens (empty `command`) instead of a click that leads nowhere. Unopened buffer → `null`; a declaration with no name span gets no lens. See `docs/features/code-lens/README.md` |
| `workspace/executeCommand` → `lucisv.showInstantiations` | `hierarchy::callers_of_each` | The code lens's own jump: `["module-name"]` in, every site as a `Location` out — one per site, file-then-position order. For a client that advertised `window.showDocument`, the server also pushes a `window/showDocument` for the **first** site, which is what makes the click navigate; LSP has no server-initiated peek-references, and this repo's extension declares no client-side command. A name with no sites answers `[]`; a missing or empty name is `RequestFailed`. Same feature README |
| `workspace/codeLens/refresh` | — | Server-**initiated**, once per workspace rescan, straight after the indexing bar comes down: a rescan can change any count on screen. Only for a client that advertised `workspace.codeLens.refreshSupport`; never at startup, where no buffer holds lenses. Same feature README |
| `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits |
@@ -234,7 +234,7 @@ reasoning and the measurements: `docs/features/cancel-request/README.md`.
| layer | rebuilt when | cost |
|---|---|---|
| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` — **once per notification**, however many ranges it carried | one file, full recompute |
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `textDocument/didOpen` that **widens the scope**, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist`/`lucisv.index.maxFileSize`/`lucisv.index.scope`/`lucisv.index.scopeDepth` (pushed **or** pulled) | full re-scan of the scope |
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `textDocument/didOpen` that **widens the scope**, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist`/`lucisv.index.maxFileSize`/`lucisv.index.scope`/`lucisv.index.scopeDepth` (pushed **or** pulled) | full re-scan of the scope — **except when the trigger names exactly one file the index already holds** (a `didSave`, a one-file watcher event), where only that file's contribution is replaced and the result is provably the index a full re-scan would have given (`docs/features/incremental-index/README.md`) |
| the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save |
**Per-file recompute on every keystroke** is the strategy TODO.md §6 states
@@ -296,17 +296,21 @@ point where the answer is expected to change anyway. Measured cost of a
rebuild: 0.68 s for the 860-file corpus (the workspace index's own baseline),
plus the file reads.
**Every rescan is visible since 2026-08-26**, for a client that advertised
`window.workDoneProgress`: the startup build and all three `reindex()` triggers
are wrapped in one `window/workDoneProgress/create` plus a `$/progress`
**Every *whole* rescan is visible since 2026-08-26**, for a client that
advertised `window.workDoneProgress`: the startup build and every whole
`reindex()` trigger are wrapped in one `window/workDoneProgress/create` plus a `$/progress`
begin/end pair on a fresh `lucisv-index-N` token, so a multi-second index on a
big filelist reads as work rather than as a hang. The `begin` does not wait for
the create's answer (the rescan blocks the loop immediately after), the answer
is ignored on the same path the watcher registrations' is, there is no
percentage and no intermediate report — the rescan is one opaque call — and the
`end` names the indexed file count. A client that did not advertise the
capability is sent nothing at all, which the spec requires. Rules and the
startup-legality argument: `docs/features/work-done-progress/README.md`.
capability is sent nothing at all, which the spec requires. **A rescan that
names exactly one file the index already holds puts no bar up** since
2026-08-27: it is one parse, sub-perceptual, and a bar that appears and
vanishes inside a frame is noise rather than progress
(`docs/features/incremental-index/README.md`). Rules and the startup-legality
argument: `docs/features/work-done-progress/README.md`.
**Changes made outside the editor close on the next notification, not on the
next save** (M9, `docs/features/file-watching/README.md`). The server registers
@@ -711,12 +715,14 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
is the tail of `pkg::base` and the whole of a bare `base`. That gets in-file
bases, cross-file bases, package-qualified bases and parameterized bases from
one line, and can never disagree with F12 on the same token.
- **`subtypes` is `callers_of_each`'s census in another key**: one
- **`subtypes` is `callers_of_each`'s census in another key**: ~~one
`sources()` pass, a substring prefilter before any parse, a deterministic
sort. 55 ms over the 860-file corpus, 53 ms of it file I/O — the same shape
`incomingCalls` measured, and the same backlog item (an edge table in
`WorkspaceIndex`, now filed for inheritance edges beside the instantiation
ones).
ones).~~ **The backlog item shipped (incremental-index, 2026-08-27):** both
are index lookups now, in the same deterministic sort, at 0.71 ms and
0.26 ms.
- **What the class model lacked:** interface classes. `vlog_parser` rejects
`interface class` outright, so `implements` can never resolve and no item can
carry `SymbolKind::Interface`; both facts are pinned by tests named to force a
+27 -12
View File
@@ -134,16 +134,28 @@ reader — to tell them apart. One item kind, done well.
subtypes}` never panic, never return an item whose `selectionRange` is outside
its `range`, and never return an item for a class the workspace does not
really declare.
- **Requested of `vlog_semantic`, not done here: an inheritance edge table in
`WorkspaceIndex`.** This is the *same* Handshake `docs/features/hierarchy`
filed for instantiation edges and `docs/features/code-lens` rode past — the
index records what a file *declares* and not what it uses, so "who extends X"
has to be a workspace walk. One table keyed by base name, built with the
index, would make `subtypes` a map lookup at the cost of one extra field per
class at index time. Filed together with the instantiation table rather than
separately: the two want the same shape and should land as one round when
something finally justifies widening the index's contract. Today one request
in 55 ms does not.
- **Requested of `vlog_semantic` — delivered (incremental-index,
2026-08-27).** `WorkspaceIndex::subclasses_of` is the table, keyed by base
name and built by the same class walk this module used to run per request —
lifted into `vlog_semantic::classes`, so the census and the declaration a
hierarchy item shows cannot drift apart. `subtypes` is a map lookup and the
`sources()` walk is gone: **82 ms → 0.71 ms** over the corpus for
`core_ibex_base_test`. It landed with the instantiation table, as filed. The
request, kept legible:
~~an inheritance edge table in `WorkspaceIndex`. This is the *same*
Handshake `docs/features/hierarchy` filed for instantiation edges and
`docs/features/code-lens` rode past — the index records what a file
*declares* and not what it uses, so "who extends X" has to be a workspace
walk. One table keyed by base name, built with the index, would make
`subtypes` a map lookup at the cost of one extra field per class at index
time. Filed together with the instantiation table rather than separately: the
two want the same shape and should land as one round when something finally
justifies widening the index's contract. Today one request in 55 ms does
not.~~
- **The answer is as of the index** (incremental-index, 2026-08-27), which is
as of its last build or update — both of which fold every open buffer in. A
keystroke in another buffer no longer moves the subtype list before a save
does; the trade is argued in `docs/features/incremental-index/README.md`.
- **`editors/vscode` needs no change.** `vscode-languageclient` 9.0.1 ships the
type-hierarchy feature and enables it off the advertised capability; the
extension sets no `initializationOptions` that would suppress it, and
@@ -197,12 +209,15 @@ Release build, this machine, the checked-in 860-file corpus, worst of three
| `supertypes` for `core_ibex_debug_intr_basic_test` | **0.69 ms** |
| the same `subtypes` in a debug build | 101 ms |
The shape is the same one `callHierarchy/incomingCalls` measured (56 ms), and
**Superseded (incremental-index, 2026-08-27): `subtypes` is 0.71 ms.** The
table above is what the walk cost; the edge table named as "the place a future
win lives" is where it went. The rest of the paragraph, kept legible:
~~The shape is the same one `callHierarchy/incomingCalls` measured (56 ms), and
for the same reason: what is left after the prefilter is **almost entirely file
I/O**, because `sources()` reads every in-scope file whether it will be parsed
or not. That is the shared cost of every cross-file answer in this server and
the place a future win lives (the edge table above, or a cheaper `sources()`);
nothing in this feature can shave it alone. The prefilter itself is not a
nothing in this feature can shave it alone.~~ The prefilter itself is not a
heuristic — `extends base` has to write `base` — and here it skips 857 of 860
files.
+10 -1
View File
@@ -15,6 +15,15 @@ scan, one `$/progress` end naming the file count. Gated on the client's own
`window.workDoneProgress` capability, because the spec forbids creating
progress a client never asked for (TODO.md §9b).
**Amended (incremental-index, 2026-08-27): a save is no longer a rescan.**
When a trigger names exactly one file the index already holds — a `didSave`, a
one-file watcher event — only that file's contribution is replaced, in ~33 ms
over the corpus, and **no bar goes up**: the bar exists because a whole scan
takes perceptible seconds, and one parse is not something a user can feel. Every
*whole* rescan below is unchanged, and a save of a file the index does not hold
is still one of them. The tests that used a save as their rescan trigger now use
one that still rescans; see `docs/features/incremental-index/README.md`.
## Assumptions
- **`window.workDoneProgress` is the gate, and there is no fallback.** A client
@@ -196,7 +205,7 @@ The ten tests, and what each is for:
| test | pins |
|---|---|
| `the_startup_index_build_runs_under_the_first_bar` | the startup determination above, as observable traffic |
| `a_save_puts_a_bar_up_and_takes_it_down_again` | create → begin → end, one token, on the save path |
| `a_whole_rescan_puts_a_bar_up_and_takes_it_down_again` (was `a_save_puts_a_bar_up_and_takes_it_down_again`, 2026-08-27) | create → begin → end, one token, on a trigger that still rescans |
| `the_bar_says_how_many_files_were_indexed` | the end message, plural and singular |
| `the_bar_is_down_before_the_republish` | the documented ordering against `publishDiagnostics` |
| `a_client_that_did_not_ask_for_a_bar_is_sent_no_progress_at_all` | zero messages of any kind, at startup and on save |
+25 -6
View File
@@ -29,6 +29,11 @@ impl WorkspaceIndex {
fn member(&self, unit: &str, member: &str) -> &[Def];
fn members_of(&self, unit: &str) -> impl Iterator<Item = (&str, &[Def])>;
fn defines(&self, FileId) -> Option<&DefineTable>;
fn instantiations_of(&self, name: &str) -> &[InstantiationEdge]; // 2026-08-27
fn subclasses_of(&self, name: &str) -> &[InheritanceEdge]; // 2026-08-27
fn update_file(&mut self, PathBuf, src: &str); // 2026-08-27
fn remove_file(&mut self, &Path) -> bool; // 2026-08-27
fn fingerprint(&self) -> String; // 2026-08-27
fn find_define(&self, name: &str) -> Vec<(FileId, &Define)>;
fn workspace_symbols(&self, query: &str) -> Vec<WorkspaceSymbol<'_>>;
fn counts(&self) -> IndexCounts;
@@ -202,9 +207,18 @@ caller does know which file it means.
## Non-goals
- **No incrementality.** `build` is a pure function of its inputs; a changed
- ~~**No incrementality.** `build` is a pure function of its inputs; a changed
workspace means calling it again. TODO.md §6 defers salsa-style
incrementality explicitly, and per-file recompute is fine at Verilog sizes.
incrementality explicitly, and per-file recompute is fine at Verilog sizes.~~
**Superseded (incremental-index, 2026-08-27): one file at a time.**
`WorkspaceIndex::update_file(path, src)` and `remove_file(path)` replace one
file's contribution, and what they produce is *the index a whole `build` over
the same files would have produced* — same `FileId`s, same disambiguation
order, same tables — because the merge they run is `finish`'s own loop
restricted to the keys that file could have moved. `build` is still a pure
function of its inputs and is still what a caller with no reason to be clever
should use. This is not salsa: there is no query graph and no dependency
tracking, just one file's records replaced in a sorted list.
- **No `` `include`` following.** The index does not build the include graph,
so it cannot say which define or which typedef a given file actually sees.
- **No elaboration**: no parameter binding, no instance hierarchy, no
@@ -268,8 +282,10 @@ workspace index: 860 files in 0.68s — 521 modules, 63 packages,
Build time is a debug build, single-threaded, sources already in memory
(reading them costs the caller another ~0.1 s). Well inside the ~2 s budget;
re-running the whole build on every workspace change is affordable, which is
why there is no incrementality.
re-running the whole build on every workspace change is affordable ~~, which is
why there is no incrementality~~ — **but not on every save, which is why there
is now `update_file` (incremental-index, 2026-08-27): one file costs 33 ms
against the whole rebuild's 1.5 s.**
**The headline.** For each file: analyze it, resolve its external candidates
against the index, and count what happened.
@@ -387,8 +403,11 @@ and more than half of all external candidates answered on clean files.
- [x] Corpus acceptance: build time, counts, resolution rate, determinism,
every answer's span slices back to the name
- [x] TODO.md §6 workspace-index checkbox
- [ ] Deferred (non-goals above): `` `include`` graph, incrementality,
elaboration
- [x] 2026-08-27 (`incremental-index`): `update_file`/`remove_file`, exactly
equal to a whole build; instantiation and inheritance edge tables
(`instantiations_of`, `subclasses_of`); `fingerprint` as the equivalence
witness
- [ ] Deferred (non-goals above): `` `include`` graph, elaboration
## Work log