From b2d778eb8dc12d86a2523c3a3c85ea4d288df122 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Thu, 27 Aug 2026 21:36:01 -0700 Subject: [PATCH] Indexed references: postings replace the per-request refactor walk MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit textDocument/references now reads declaration-to-occurrence postings merged in WorkspaceIndex from compact per-file reference facts, with open buffers overlaying live semantics — 0.062 ms/request over 820 files vs 21.7 ms for the old Workspace::sources() walk (~350x). The walk stays as rename's engine and the equivalence oracle in tests. FACTS_FORMAT 1->2 discards v1 caches whole. Cursor lookups (symbol_at/reference_at/token_at) and macro-define lookup move to binary-searched sorted tables; include definition inspects only the cursor's line. Ambiguity refusals preserved throughout. External dev: codex. Lead-reviewed, gates re-run, probe reproduced. Co-Authored-By: Claude Fable 5 --- crates/lucisv_server/src/hover.rs | 2 +- crates/lucisv_server/src/includes.rs | 9 +- crates/lucisv_server/src/nav.rs | 280 ++++++++++++++++++++-- crates/lucisv_server/src/state.rs | 17 ++ crates/vlog_semantic/src/facts.rs | 52 +++- crates/vlog_semantic/src/lib.rs | 42 +++- crates/vlog_semantic/src/workspace.rs | 201 +++++++++++++++- crates/vlog_semantic/tests/workspace.rs | 56 +++++ docs/features/index-persistence/README.md | 13 +- docs/features/lucisv-server/README.md | 28 +-- docs/features/references-nav/README.md | 116 +++++++-- docs/features/vlog-semantic/README.md | 8 + docs/features/workspace-index/README.md | 25 +- 13 files changed, 768 insertions(+), 81 deletions(-) diff --git a/crates/lucisv_server/src/hover.rs b/crates/lucisv_server/src/hover.rs index cbc9dd3..6406080 100644 --- a/crates/lucisv_server/src/hover.rs +++ b/crates/lucisv_server/src/hover.rs @@ -35,7 +35,7 @@ pub fn hover(ws: &Workspace, uri: &Uri, offset: u32) -> Option { /// of the workspace's, because outside the include graph picking one would be /// a guess. fn macro_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option { - let token = doc.tokens.iter().find(|t| t.is_macro() && t.span.contains(offset))?; + let token = doc.token_at(offset).filter(|token| token.is_macro())?; let name = macro_name(token)?; if let Some(define) = doc.defines.latest(name) { diff --git a/crates/lucisv_server/src/includes.rs b/crates/lucisv_server/src/includes.rs index 8e940ec..469c1a9 100644 --- a/crates/lucisv_server/src/includes.rs +++ b/crates/lucisv_server/src/includes.rs @@ -332,7 +332,14 @@ pub fn document_links(ws: &Workspace, uri: &Uri) -> Vec { /// The same computation the links use, so F12 and ctrl-click can never /// disagree about where a line goes. pub fn definition(ws: &Workspace, doc: &Document, offset: u32) -> Option { - let (_, path) = resolved(ws, doc).into_iter().find(|(inc, _)| inc.span.contains(offset))?; + // Definition is a cursor request, so inspect only its line. `documentLink` + // still scans the whole file because it must return every include. + let (line, _) = doc.line_index.line_col(offset); + let line = doc.line_index.line_range(line)?; + let text = doc.text.get(line.as_range())?; + let include = + include_on_line(text, line.start).filter(|include| include.span.contains(offset))?; + let path = ws.includes().resolve(doc.path.as_deref(), &include)?; Some(Location { uri: path_to_uri(&path)?, range: Range::default() }) } diff --git a/crates/lucisv_server/src/nav.rs b/crates/lucisv_server/src/nav.rs index 54d6433..1d7d114 100644 --- a/crates/lucisv_server/src/nav.rs +++ b/crates/lucisv_server/src/nav.rs @@ -2,9 +2,10 @@ //! `textDocument/documentHighlight`. use lsp_types::{DocumentHighlight, DocumentHighlightKind, Location, Uri}; -use vlog_parser::TextRange; -use vlog_semantic::{Definition, Semantics, SymbolId}; +use vlog_parser::{LineIndex, TextRange}; +use vlog_semantic::{Def, Definition, ExternalTarget, Semantics, Symbol, SymbolId}; +use crate::convert::Positions; use crate::includes; use crate::locate::location; use crate::state::{Document, Workspace}; @@ -58,17 +59,11 @@ fn path_to_uri_or_self(ws: &Workspace, uri: &Uri) -> Option { /// Find-all-references, across the workspace when the symbol can leave this /// file and inside it when it cannot. /// -/// The two paths answer the same question at very different prices: the -/// in-file answer is a lookup in an analysis the buffer already carries, and -/// the workspace answer re-reads and re-analyzes every in-scope file. So the -/// gate below is asked first, and it is asked of the *index* — a name it does -/// not hold as a unit or as an exported member cannot be named from another -/// file, so a local `wire` never starts a workspace walk. -/// -/// The cross-file collection is `vlog_refactor`'s, the same one a rename runs -/// (`docs/features/references-nav/README.md`). When it declines — an -/// ambiguous name, a use nothing resolves — the file's own answer is sent -/// rather than an error: a highlight the editor can draw beats a shrug. +/// The cross-file path is an in-memory declaration-to-occurrence lookup in the +/// workspace index. Open buffers overlay their live semantics on those saved +/// postings, so unsaved additions and deletions remain visible without a +/// project scan. When the index declines an ambiguous target, the file's own +/// answer is sent rather than an error. pub fn references( ws: &Workspace, uri: &Uri, @@ -77,8 +72,10 @@ pub fn references( ) -> Vec { let Some(doc) = ws.document(uri) else { return Vec::new() }; if leaves_this_file(ws, doc, offset) { - if let Some(locations) = workspace_references(ws, doc, offset, include_declaration) { - return locations; + if let Some(target) = indexed_target(ws, doc, offset) { + if let Some(locations) = indexed_references(ws, target, include_declaration) { + return locations; + } } } in_file_references(ws, doc, uri, offset, include_declaration) @@ -120,17 +117,164 @@ fn leaves_this_file(ws: &Workspace, doc: &Document, offset: u32) -> bool { } } -/// The workspace-wide answer, or `None` when the engine declined it. -fn workspace_references( - ws: &Workspace, +#[derive(Clone)] +struct IndexedTarget { + def: Def, + name: String, + declaration_path: std::path::PathBuf, + declaration_span: TextRange, +} + +/// Map the live cursor answer onto the stable declaration held by this index. +fn indexed_target(ws: &Workspace, doc: &Document, offset: u32) -> Option { + match doc.external.definition_of(&doc.semantics, offset)? { + Definition::Local(symbol) => { + let def = indexed_def_for_symbol(ws, doc, symbol)?.clone(); + let declaration_path = doc.path.clone()?; + Some(IndexedTarget { + def, + name: symbol.name.clone(), + declaration_path, + declaration_span: symbol.name_span, + }) + } + Definition::External([def]) => { + let id = doc.semantics.reference_id_at(offset)?; + let name = doc.semantics.reference(id)?.name.clone(); + let declaration_path = ws.index().path(def.file)?.to_path_buf(); + Some(IndexedTarget { + def: def.clone(), + name, + declaration_path, + declaration_span: def.name_span, + }) + } + Definition::External(_) => None, + } +} + +/// The indexed declaration represented by one live single-file symbol. +/// +/// Matching is logical (path, owner, name and kind), not positional: edits +/// above a declaration may move its live span before the next save. +fn indexed_def_for_symbol<'a>( + ws: &'a Workspace, doc: &Document, - offset: u32, + symbol: &Symbol, +) -> Option<&'a Def> { + let path = doc.path.as_deref()?; + let file = ws.index().file_id(path)?; + let defs = if symbol.scope == doc.semantics.file_scope() { + ws.index().units(&symbol.name) + } else { + let owner = doc + .semantics + .scope(symbol.scope) + .and_then(|scope| scope.owner) + .and_then(|owner| doc.semantics.symbol(owner))?; + ws.index().member(&owner.name, &symbol.name) + }; + if defs.len() != 1 { + return None; + } + defs.first().filter(|def| def.file == file && def.kind == symbol.kind) +} + +/// The project-wide answer from persisted postings, overlaid by every live +/// buffer. `None` preserves the old ambiguity contract and lets the caller +/// degrade to its single-file answer. +fn indexed_references( + ws: &Workspace, + target: IndexedTarget, include_declaration: bool, ) -> Option> { - let path = doc.path.clone()?; - let found = - vlog_refactor::find_references(&ws.sources(), &path, offset, include_declaration).ok()?; - Some(found.iter().filter_map(|(path, span)| location(ws, path, *span)).collect()) + if ws.index().references_are_ambiguous(&target.def) { + return None; + } + + let mut found = Vec::new(); + for site in ws.index().references_to(&target.def) { + let path = ws.index().path(site.file)?; + if ws.document_for_path(path).is_none() { + found.push((path.to_path_buf(), site.name_span)); + } + } + + for (_, doc) in ws.open_documents() { + let Some(path) = doc.path.as_ref() else { continue }; + for (id, reference) in doc.semantics.references().iter().enumerate() { + let matches = match reference.resolved().and_then(|id| doc.semantics.symbol(id)) { + Some(symbol) => indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def), + None => match doc.external.get(vlog_semantic::ReferenceId(id as u32)) { + Some(ExternalTarget::Resolved(def)) => def == &target.def, + Some(ExternalTarget::Ambiguous(defs)) if defs.contains(&target.def) => { + return None; + } + _ => false, + }, + }; + if matches && !reference.name_span.is_empty() { + found.push((path.clone(), reference.name_span)); + } + } + } + + if include_declaration { + let span = ws + .document_for_path(&target.declaration_path) + .and_then(|doc| { + doc.semantics.symbols().iter().find_map(|symbol| { + (symbol.name == target.name + && indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def)) + .then_some(symbol.name_span) + }) + }) + .unwrap_or(target.declaration_span); + found.push((target.declaration_path, span)); + } + + Some(locations(ws, found)) +} + +/// Convert all occurrences in one file with one text fetch and one line +/// index, rather than repeating both operations for every location. +fn locations(ws: &Workspace, mut found: Vec<(std::path::PathBuf, TextRange)>) -> Vec { + found.retain(|(_, span)| !span.is_empty()); + found.sort_by(|(a_path, a_span), (b_path, b_span)| { + (a_path, a_span.start, a_span.end).cmp(&(b_path, b_span.start, b_span.end)) + }); + found.dedup(); + + let mut out = Vec::with_capacity(found.len()); + let mut start = 0; + while start < found.len() { + let path = &found[start].0; + let end = found[start..].partition_point(|(candidate, _)| candidate == path) + start; + let Some(uri) = path_to_uri(path) else { + start = end; + continue; + }; + if let Some(doc) = ws.document_for_path(path) { + let positions = doc.positions(); + let mut walker = positions.walker(); + out.extend( + found[start..end] + .iter() + .map(|(_, span)| Location { uri: uri.clone(), range: walker.range(*span) }), + ); + } else if let Some(text) = ws.text_of(path) { + let index = LineIndex::new(&text); + let positions = Positions::new(&text, &index); + let mut walker = positions.walker(); + out.extend( + found[start..end] + .iter() + .map(|(_, span)| Location { uri: uri.clone(), range: walker.range(*span) }), + ); + } + start = end; + } + out } /// The file's own answer: what `Semantics` alone knows about this symbol. @@ -439,6 +583,67 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + #[test] + fn indexed_references_equal_the_refactor_walk_they_replace() { + let (dir, ws, uri) = instantiated("xrefs_equivalence", "top.sv"); + let offset = at(TOP, "sub u_b"); + let indexed = references(&ws, &uri, offset, true); + let path = dir.join("top.sv"); + let walked = vlog_refactor::find_references(&ws.sources(), &path, offset, true) + .expect("the existing refactor walk answers"); + let walked = locations(&ws, walked); + + assert_eq!(indexed, walked); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + #[ignore = "manual indexed-navigation latency probe"] + fn qa_indexed_references_latency_over_a_large_workspace() { + let dir = temp_dir("xrefs_latency"); + let sub_path = dir.join("sub.sv"); + fs::write(&sub_path, SUB).expect("write declaration"); + for i in 0..4 { + fs::write( + dir.join(format!("use_{i}.sv")), + format!("module use_{i}; sub u (); endmodule\n"), + ) + .expect("write use"); + } + for i in 0..815 { + fs::write( + dir.join(format!("unrelated_{i}.sv")), + format!("module unrelated_{i}; logic signal_{i}; endmodule\n"), + ) + .expect("write unrelated source"); + } + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&sub_path).expect("uri"); + ws.set_document(uri.clone(), SUB.to_string()); + assert_eq!(references(&ws, &uri, at(SUB, "sub"), true).len(), 5); + + let requests = 200; + let start = std::time::Instant::now(); + for _ in 0..requests { + assert_eq!(references(&ws, &uri, at(SUB, "sub"), true).len(), 5); + } + let indexed = start.elapsed(); + + let start = std::time::Instant::now(); + let walked = vlog_refactor::find_references(&ws.sources(), &sub_path, at(SUB, "sub"), true) + .expect("old walk"); + let old = start.elapsed(); + assert_eq!(walked.len(), 5); + eprintln!( + "indexed references: {:.3} ms/request over 820 files; old walk: {:.3} ms/request", + indexed.as_secs_f64() * 1_000.0 / f64::from(requests), + old.as_secs_f64() * 1_000.0, + ); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn include_declaration_drops_the_declaration_and_nothing_else() { let (dir, ws, uri) = instantiated("xrefs_nodecl", "sub.sv"); @@ -546,6 +751,35 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + #[test] + fn an_unsaved_open_buffer_replaces_its_saved_reference_postings() { + let (dir, mut ws, uri) = instantiated("xrefs_unsaved_uses", "top.sv"); + let edited = "module top;\n\n sub only_now ();\nendmodule\n"; + ws.set_document(uri.clone(), edited.to_string()); + + let found = references(&ws, &uri, at(edited, "sub only_now"), false); + assert_eq!( + places(&found), + vec![("other.sv".to_string(), 1), ("top.sv".to_string(), 2)], + "the new live use replaces both saved top.sv uses" + ); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn an_unsaved_declaration_move_is_reported_at_its_live_span() { + let (dir, mut ws, uri) = instantiated("xrefs_unsaved_decl", "sub.sv"); + let edited = "// moved down\n\nmodule sub (input logic clk);\nendmodule\n"; + ws.set_document(uri.clone(), edited.to_string()); + + let found = references(&ws, &uri, at(edited, "module sub") + 7, true); + assert!( + places(&found).contains(&("sub.sv".to_string(), 2)), + "the declaration comes from the live buffer, not its saved offset" + ); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn an_untitled_buffer_still_answers_from_itself() { // No path means no place in the index and nothing to hand the engine, diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index 7e41913..ba416c6 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -123,6 +123,13 @@ impl Document { Positions::new(&self.text, &self.line_index) } + /// The source token covering `offset`, found without sweeping the buffer. + pub fn token_at(&self, offset: u32) -> Option<&Token> { + let after = self.tokens.partition_point(|token| token.span.start <= offset); + let token = self.tokens.get(after.checked_sub(1)?)?; + token.span.contains(offset).then_some(token) + } + /// Re-run only the workspace overlay, after the index was rebuilt. The /// single-file analysis is unaffected by other files, by construction. pub fn refresh_overlay(&mut self, index: &WorkspaceIndex) { @@ -454,6 +461,16 @@ impl Workspace { self.docs.get(uri) } + /// The open document backed by `path`, if there is one. + pub fn document_for_path(&self, path: &Path) -> Option<&Document> { + self.docs.values().find(|doc| doc.path.as_deref() == Some(path)) + } + + /// Every open document and its URI. + pub fn open_documents(&self) -> impl Iterator { + self.docs.iter() + } + /// Replace a buffer's contents and re-analyze it. /// /// Also the one place a directory enters the folder scope: a buffer with a diff --git a/crates/vlog_semantic/src/facts.rs b/crates/vlog_semantic/src/facts.rs index 31b1512..2bc5910 100644 --- a/crates/vlog_semantic/src/facts.rs +++ b/crates/vlog_semantic/src/facts.rs @@ -20,13 +20,13 @@ use vlog_parser::defines::{Define, DefineKind, DefineTable}; use vlog_parser::span::TextRange; use crate::model::SymbolKind; -use crate::workspace::{Decl, DeclSite, FileFacts, SiteFact}; +use crate::workspace::{Decl, DeclSite, FileFacts, ReferenceFact, SiteFact}; /// The version of the encoding below. Bump it on **any** change to what a /// record holds or to how it is written: a store stamped with another number /// is discarded whole, which is the only way a reader can be sure it is not /// reading last month's field order as this month's. -pub const FACTS_FORMAT: u32 = 1; +pub const FACTS_FORMAT: u32 = 2; impl FileFacts { /// These facts as one line's worth of fields, tab-separated. @@ -64,6 +64,10 @@ impl FileFacts { out.text(base); out.site(subclass); } + out.tag("R", self.references.len()); + for reference in &self.references { + out.reference(reference); + } Some(out.out) } @@ -101,6 +105,10 @@ impl FileFacts { for _ in 0..input.tag("S")? { subclasses.push((input.text()?, input.site()?)); } + let mut references = Vec::new(); + for _ in 0..input.tag("R")? { + references.push(input.reference()?); + } if !input.done() { return None; } @@ -111,6 +119,7 @@ impl FileFacts { members, instantiations, subclasses, + references, }) } } @@ -211,6 +220,27 @@ impl Writer { self.range(define.name_span); } + fn reference(&mut self, reference: &ReferenceFact) { + match reference { + ReferenceFact::Local { definition, occurrence } => { + self.field(); + self.out.push('l'); + self.range(*definition); + self.range(*occurrence); + } + ReferenceFact::External { name, paths, occurrence } => { + self.field(); + self.out.push('e'); + self.text(name); + self.num(paths.len() as u32); + for path in paths { + self.text(path); + } + self.range(*occurrence); + } + } + } + /// The separator before every field but the first. fn field(&mut self) { if self.written { @@ -302,6 +332,24 @@ impl<'a> Reader<'a> { name_span: self.range()?, }) } + + fn reference(&mut self) -> Option { + match self.next()? { + "l" => { + Some(ReferenceFact::Local { definition: self.range()?, occurrence: self.range()? }) + } + "e" => { + let name = self.text()?; + let count = self.num()? as usize; + let mut paths = Vec::with_capacity(count); + for _ in 0..count { + paths.push(self.text()?); + } + Some(ReferenceFact::External { name, paths, occurrence: self.range()? }) + } + _ => None, + } + } } /// One escaped string field, back as it was written. `None` for an escape diff --git a/crates/vlog_semantic/src/lib.rs b/crates/vlog_semantic/src/lib.rs index ccfa1d4..46defe8 100644 --- a/crates/vlog_semantic/src/lib.rs +++ b/crates/vlog_semantic/src/lib.rs @@ -31,9 +31,9 @@ pub use model::{ SymbolId, SymbolKind, }; pub use workspace::{ - index_order, resolve_external, DeclSite, Def, Definition, ExternalResolutions, ExternalTarget, - FileFacts, FileId, IndexBuilder, IndexCounts, InheritanceEdge, InstantiationEdge, - WorkspaceIndex, WorkspaceSymbol, + index_order, resolve_external, DeclSite, Def, Definition, DefinitionKey, ExternalResolutions, + ExternalTarget, FileFacts, FileId, IndexBuilder, IndexCounts, InheritanceEdge, + InstantiationEdge, ReferenceSite, WorkspaceIndex, WorkspaceSymbol, }; use std::collections::HashMap; @@ -48,6 +48,10 @@ pub struct Semantics { references: Vec, /// symbol → indices into `references`, in source order. uses: HashMap>, + /// Non-empty declaration-name spans, sorted by start for cursor lookup. + symbol_positions: Vec<(TextRange, SymbolId)>, + /// Non-empty reference-name spans, sorted by start for cursor lookup. + reference_positions: Vec<(TextRange, ReferenceId)>, } /// Build the symbol table for one parsed file. `src` must be the text the @@ -79,7 +83,21 @@ pub fn analyze(file: &SourceFile, src: &str) -> Semantics { uses.entry(id).or_default().push(i); } } - Semantics { scopes, symbols, references, uses } + let mut symbol_positions: Vec<(TextRange, SymbolId)> = symbols + .iter() + .enumerate() + .filter(|(_, symbol)| !symbol.name_span.is_empty()) + .map(|(i, symbol)| (symbol.name_span, SymbolId(i as u32))) + .collect(); + symbol_positions.sort_by_key(|(span, _)| (span.start, span.end)); + let mut reference_positions: Vec<(TextRange, ReferenceId)> = references + .iter() + .enumerate() + .filter(|(_, reference)| !reference.name_span.is_empty()) + .map(|(i, reference)| (reference.name_span, ReferenceId(i as u32))) + .collect(); + reference_positions.sort_by_key(|(span, _)| (span.start, span.end)); + Semantics { scopes, symbols, references, uses, symbol_positions, reference_positions } } /// Point every import at the package it names, when this file declares it. @@ -130,21 +148,18 @@ impl Semantics { /// The declaration whose *name* covers `offset` — a cursor sitting on a /// declared name, not anywhere in its declaration. pub fn symbol_at(&self, offset: u32) -> Option { - self.symbols.iter().position(|s| s.name_span.contains(offset)).map(|i| SymbolId(i as u32)) + position_at(&self.symbol_positions, offset) } /// The use whose name covers `offset`. pub fn reference_at(&self, offset: u32) -> Option<&Reference> { - self.references.iter().find(|r| r.name_span.contains(offset)) + self.reference_id_at(offset).and_then(|id| self.reference(id)) } /// The id of the use whose name covers `offset` — the key the workspace /// index's overlay uses. pub fn reference_id_at(&self, offset: u32) -> Option { - self.references - .iter() - .position(|r| r.name_span.contains(offset)) - .map(|i| ReferenceId(i as u32)) + position_at(&self.reference_positions, offset) } /// One use by id. @@ -216,3 +231,10 @@ impl Semantics { self.scopes.first().map_or(TextRange::empty(0), |s| s.span) } } + +/// The source span covering `offset` in a non-overlapping, start-sorted table. +fn position_at(positions: &[(TextRange, Id)], offset: u32) -> Option { + let after = positions.partition_point(|(span, _)| span.start <= offset); + let (span, id) = positions.get(after.checked_sub(1)?)?; + span.contains(offset).then_some(*id) +} diff --git a/crates/vlog_semantic/src/workspace.rs b/crates/vlog_semantic/src/workspace.rs index 3063c59..600ac3d 100644 --- a/crates/vlog_semantic/src/workspace.rs +++ b/crates/vlog_semantic/src/workspace.rs @@ -17,7 +17,7 @@ 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::defines::{collect_defines, Define, DefineKind, DefineTable}; use vlog_parser::span::TextRange; use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize}; @@ -39,6 +39,38 @@ pub struct Def { pub kind: SymbolKind, } +/// Stable identity of one indexed declaration inside the current index. +/// +/// A [`FileId`] may move when a file is added or removed, so this key survives +/// only as long as the [`WorkspaceIndex`] that produced it. That is exactly the +/// lifetime of every merged table in the index; callers never persist it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct DefinitionKey { + pub file: FileId, + pub name_start: u32, + pub name_end: u32, +} + +impl DefinitionKey { + /// The key of an indexed definition. + pub fn of(def: &Def) -> DefinitionKey { + DefinitionKey { + file: def.file, + name_start: def.name_span.start, + name_end: def.name_span.end, + } + } +} + +/// One indexed use of a declaration. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ReferenceSite { + /// The file the use is written in. + pub file: FileId, + /// Byte range of the referenced name inside that file. + pub name_span: TextRange, +} + /// One hit of [`WorkspaceIndex::workspace_symbols`]. #[derive(Debug, Clone)] pub struct WorkspaceSymbol<'a> { @@ -116,6 +148,14 @@ pub struct WorkspaceIndex { /// Base class name → every class extending it, in file order then walk /// order. subclasses: BTreeMap>, + /// Macro name → `(file, entry-in-that-file)` for each definition. + macro_definitions: BTreeMap>, + /// Declaration → every unambiguous use, in file then source order. + reference_sites: BTreeMap>, + /// Declarations touched by at least one ambiguous external reference. + /// Find-references refuses those rather than assigning the use to one of + /// several equally plausible declarations. + ambiguous_references: HashSet, } impl WorkspaceIndex { @@ -152,6 +192,14 @@ impl WorkspaceIndex { self.files.get(file.0 as usize).map(PathBuf::as_path) } + /// The id of an indexed path. + pub fn file_id(&self, path: &Path) -> Option { + self.files + .binary_search_by(|held| held.as_path().cmp(path)) + .ok() + .map(|at| FileId(at as u32)) + } + /// Every file-scope declaration of `name` — module, package or typedef — /// in disambiguation order (by file path, then by position in the file). /// More than one means the workspace really does declare the name twice. @@ -222,12 +270,25 @@ impl WorkspaceIndex { /// this index models. A hover showing all of them is honest; picking one /// silently would not be. pub fn find_define(&self, name: &str) -> Vec<(FileId, &Define)> { - let mut out = Vec::new(); - for (i, facts) in self.facts.iter().enumerate() { - let file = FileId(i as u32); - out.extend(facts.defines.all(name).into_iter().map(|d| (file, d))); - } - out + self.macro_definitions + .get(name) + .into_iter() + .flatten() + .filter_map(|&(file, entry)| { + let define = self.facts.get(file.0 as usize)?.defines.entries().get(entry)?; + Some((file, define)) + }) + .collect() + } + + /// Every indexed use of `def`, excluding its declaration. + pub fn references_to(&self, def: &Def) -> &[ReferenceSite] { + self.reference_sites.get(&DefinitionKey::of(def)).map_or(&[], Vec::as_slice) + } + + /// Whether at least one use could name `def` or another declaration equally. + pub fn references_are_ambiguous(&self, def: &Def) -> bool { + self.ambiguous_references.contains(&DefinitionKey::of(def)) } /// Every indexed name containing `query`, case-insensitively — LSP's @@ -373,6 +434,27 @@ impl WorkspaceIndex { symbol.def.name_span.end )); } + for (definition, sites) in &self.reference_sites { + for site in sites { + out.push_str(&format!( + "ref {}:{}..{} <- {}:{}..{}\n", + definition.file.0, + definition.name_start, + definition.name_end, + site.file.0, + site.name_span.start, + site.name_span.end + )); + } + } + let mut ambiguous: Vec = self.ambiguous_references.iter().copied().collect(); + ambiguous.sort(); + for definition in ambiguous { + out.push_str(&format!( + "ambiguous-ref {}:{}..{}\n", + definition.file.0, definition.name_start, definition.name_end + )); + } for (name, edges) in self.instantiations() { for edge in edges { out.push_str(&format!( @@ -414,6 +496,7 @@ impl WorkspaceIndex { self.members.clear(); self.instantiations.clear(); self.subclasses.clear(); + self.macro_definitions.clear(); } Some(affected) => { for name in &affected.units { @@ -428,6 +511,9 @@ impl WorkspaceIndex { for name in &affected.bases { self.subclasses.remove(name); } + for name in &affected.macros { + self.macro_definitions.remove(name); + } } } for (id, facts) in self.facts.iter().enumerate() { @@ -468,7 +554,54 @@ impl WorkspaceIndex { .or_default() .push(InheritanceEdge { file, subclass: subclass.clone() }); } + for (entry, define) in facts.defines.entries().iter().enumerate() { + if define.kind != DefineKind::Define + || affected.is_some_and(|a| !a.macros.contains(&define.name)) + { + continue; + } + self.macro_definitions.entry(define.name.clone()).or_default().push((file, entry)); + } } + // A changed declaration can change how references in any file resolve, + // even when only one file's facts moved. Re-resolving compact facts is + // one in-memory pass; no source is read or parsed. + self.merge_references(); + } + + /// Rebuild declaration-to-occurrence postings from compact per-file facts. + fn merge_references(&mut self) { + let mut sites: BTreeMap> = BTreeMap::new(); + let mut ambiguous: HashSet = HashSet::new(); + for (id, facts) in self.facts.iter().enumerate() { + let file = FileId(id as u32); + for reference in &facts.references { + let site = ReferenceSite { file, name_span: reference.occurrence() }; + match reference { + ReferenceFact::Local { definition, .. } => { + let key = DefinitionKey { + file, + name_start: definition.start, + name_end: definition.end, + }; + sites.entry(key).or_default().push(site); + } + ReferenceFact::External { name, paths, .. } => { + match follow_paths(self, name, paths) { + ExternalTarget::Resolved(def) => { + sites.entry(DefinitionKey::of(&def)).or_default().push(site); + } + ExternalTarget::Ambiguous(defs) => { + ambiguous.extend(defs.iter().map(DefinitionKey::of)); + } + ExternalTarget::StillUnresolved => {} + } + } + } + } + } + self.reference_sites = sites; + self.ambiguous_references = ambiguous; } } @@ -484,6 +617,7 @@ struct Affected { containers: HashSet, modules: HashSet, bases: HashSet, + macros: HashSet, } impl Affected { @@ -498,6 +632,7 @@ impl Affected { 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())); + self.macros.extend(facts.defines.entries().iter().map(|define| define.name.clone())); } } @@ -554,6 +689,27 @@ pub struct FileFacts { /// Class declarations with a base, each under the base's name, in walk /// order. pub(crate) subclasses: Vec<(String, DeclSite)>, + /// Uses of declarations another file may name, stored before file ids and + /// cross-file candidates have been resolved by the finished index. + pub(crate) references: Vec, +} + +/// One reference contribution before the workspace's declarations are merged. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum ReferenceFact { + /// A use resolved to an exported declaration in this same file. + Local { definition: TextRange, occurrence: TextRange }, + /// A use whose recorded paths need the workspace declaration tables. + External { name: String, paths: Vec, occurrence: TextRange }, +} + +impl ReferenceFact { + fn occurrence(&self) -> TextRange { + match self { + ReferenceFact::Local { occurrence, .. } + | ReferenceFact::External { occurrence, .. } => *occurrence, + } + } } impl FileFacts { @@ -581,6 +737,7 @@ fn facts_of(path: PathBuf, src: &str) -> FileFacts { members: Vec::new(), instantiations: edges_of(&tree), subclasses: inheritance_of(&tree), + references: Vec::new(), }; let Some(file_scope) = sem.scope(sem.file_scope()) else { return facts; @@ -595,6 +752,36 @@ fn facts_of(path: PathBuf, src: &str) -> FileFacts { facts.units.push(Decl::of(unit)); collect_members(&sem, unit, &mut facts.members); } + let exported: HashSet<(u32, u32)> = facts + .units + .iter() + .map(|decl| (decl.name_span.start, decl.name_span.end)) + .chain(facts.members.iter().map(|(_, decl)| (decl.name_span.start, decl.name_span.end))) + .collect(); + for reference in sem.references() { + let fact = match &reference.resolution { + Resolution::Resolved(id) => sem.symbol(*id).and_then(|symbol| { + let definition = symbol.name_span; + exported + .contains(&(definition.start, definition.end)) + .then_some(ReferenceFact::Local { definition, occurrence: reference.name_span }) + }), + Resolution::ExternalCandidate { paths } + | Resolution::InheritedCandidate { paths, .. } + if !paths.is_empty() => + { + Some(ReferenceFact::External { + name: reference.name.clone(), + paths: paths.clone(), + occurrence: reference.name_span, + }) + } + _ => None, + }; + if let Some(fact) = fact { + facts.references.push(fact); + } + } facts } diff --git a/crates/vlog_semantic/tests/workspace.rs b/crates/vlog_semantic/tests/workspace.rs index 8f7975c..921368a 100644 --- a/crates/vlog_semantic/tests/workspace.rs +++ b/crates/vlog_semantic/tests/workspace.rs @@ -759,6 +759,62 @@ fn an_import_that_can_supply_the_name_still_wins_over_a_same_named_unit() { assert_eq!(defs[0].kind, SymbolKind::Typedef, "the package's typedef, not the decoy module"); } +// ---------------------------------------------------------------------- +// Indexed reference postings +// ---------------------------------------------------------------------- + +#[test] +fn reference_postings_point_from_a_declaration_to_every_cross_file_use() { + let sources = [ + ("a.sv", "module top; sub u0 (); sub u1 (); endmodule\n"), + ("b.sv", "module other; sub u2 (); endmodule\n"), + ("sub.sv", "module sub; endmodule\n"), + ]; + let ws = index(&sources); + let [definition] = ws.units("sub") else { panic!("one sub declaration") }; + let sites: Vec<(&Path, &str)> = ws + .references_to(definition) + .iter() + .map(|site| { + let path = ws.path(site.file).expect("site file"); + let source = sources.iter().find(|(held, _)| Path::new(held) == path).unwrap().1; + (path, &source[site.name_span.as_range()]) + }) + .collect(); + + assert_eq!( + sites, + vec![(Path::new("a.sv"), "sub"), (Path::new("a.sv"), "sub"), (Path::new("b.sv"), "sub")] + ); + assert!(!ws.references_are_ambiguous(definition)); +} + +#[test] +fn replacing_one_file_rebuilds_reference_postings_without_reparsing_the_others() { + let declaration = "module sub; endmodule\n"; + let old_top = "module top; sub u0 (); sub u1 (); endmodule\n"; + let new_top = "module top; sub u0 (); endmodule\n"; + let mut incremental = index(&[("sub.sv", declaration), ("top.sv", old_top)]); + + incremental.update_file(PathBuf::from("top.sv"), new_top); + let rebuilt = index(&[("sub.sv", declaration), ("top.sv", new_top)]); + + assert_eq!(incremental.fingerprint(), rebuilt.fingerprint()); + let [definition] = incremental.units("sub") else { panic!("one sub declaration") }; + assert_eq!(incremental.references_to(definition).len(), 1); +} + +#[test] +fn an_ambiguous_external_use_marks_every_possible_declaration() { + let ws = index(&[ + ("a.sv", "module dup; endmodule\n"), + ("b.sv", "module dup; endmodule\n"), + ("top.sv", "module top; dup u (); endmodule\n"), + ]); + assert_eq!(ws.units("dup").len(), 2); + assert!(ws.units("dup").iter().all(|def| ws.references_are_ambiguous(def))); +} + // ---------------------------------------------------------------------- // Corpus acceptance // ---------------------------------------------------------------------- diff --git a/docs/features/index-persistence/README.md b/docs/features/index-persistence/README.md index 7031c44..065c1f7 100644 --- a/docs/features/index-persistence/README.md +++ b/docs/features/index-persistence/README.md @@ -213,6 +213,10 @@ impl WorkspaceIndex { - `add_file` is now `add_facts(FileFacts::of(path, src))` — one implementation, so the cached path cannot drift from the parsed one. +- Since indexed navigation (2026-08-27), the private facts also carry compact + local/external reference records used to rebuild declaration-to-occurrence + postings. That encoding change bumped `FACTS_FORMAT` from 1 to 2; no cache + migration is attempted or needed. - `record_path` is public separately because a store keyed by path reads that field out of every record it holds and decodes only the ones it is asked for. @@ -337,16 +341,17 @@ module m; sub u (); endmodule ``` ``` -2f0a8bd7c1d1f5a1→/w/m.sv→D→1→d→W→-→8→0→11→8→9→U→1→m→module→19→20→M→0→I→1→sub→m→19→20→12→41→22→25→S→0→9b1c04e2a7f3d081 +2f0a8bd7c1d1f5a1→/w/m.sv→D→1→d→W→-→8→0→11→8→9→U→1→m→module→19→20→M→0→I→1→sub→m→19→20→12→41→22→25→S→0→R→1→e→sub→1→sub→22→25→9b1c04e2a7f3d081 ``` — one define (`d` for `` `define``, name `W`, `-` for "no parameter list", body `8`, span `0..11`, name span `8..9`), one file-scope unit (`m`, a module, name span `19..20`), no members, one instantiation edge (of `sub`, owned by `m` whose name is at `19..20` and whose declaration runs `12..41`, with the -site's own name span `22..25`), no subclasses, and the checksum of all of -that. The record is what lies between the hash field and the checksum; both -hashes above are illustrative. +site's own name span `22..25`), no subclasses, and one external reference fact +(`e`, name `sub`, one resolution path also named `sub`, occurrence `22..25`), +then the checksum. The record is what lies between the hash field and the +checksum; both hashes above are illustrative. **Any change to what a record holds or how it is written bumps `FACTS_FORMAT`** — that is the rule, written at the constant, and it is what diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index 6ccb1e9..c23f95c 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -33,7 +33,7 @@ looks like language knowledge in here is a bug or a `Handshake` request. | `textDocument/typeDefinition` | `type_def`, then `nav::definition` | The same jump one token to the left: from a name to where its **type** is declared — a `typedef`, an `interface`, a `class`, or the module an instance name stands for. The tree says which declaration a position is in and where its type name is written; the answer is then `definition` of *that* name, so cross-file resolution, ambiguity and position conversion are all the ones F12 already uses. One hop on an alias chain, an empty list for a built-in. See `docs/features/type-definition/README.md` | | `textDocument/linkedEditingRange` | `linked`, over `Document.tree` | SV's closing labels, edited as one name: the cursor on either half of `module m ... endmodule : m` (and of `endfunction`/`endtask`/`endclass`/`endpackage`/`endinterface`/`endclocking`, a named `begin`/`fork`, a generate block, and the prefix-labelled `b : begin ... end : b`) answers **both** ranges plus the SV `wordPattern`. The pair comes off one AST node — `name_span` with `end_label_span` — never off a text match, so four identical names at two nesting levels still pair syntactically. Two `null`s on purpose: a closer with **no** label (nothing to co-edit, and this never offers to create one) and a **mismatched** one (the spec requires identical text; linking would silently rewrite broken code). Escaped identifiers are excluded. See `docs/features/linked-editing/README.md` | | `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README | -| `textDocument/references` | `vlog_refactor::find_references`, else `Semantics::references_of` | Cross-file when the symbol is one the workspace index holds (a module, a package, an exported member, a port); in-file for everything else, which is what keeps a local `wire` off the workspace walk. See `docs/features/references-nav/README.md` | +| `textDocument/references` | `WorkspaceIndex::references_to`, else `Semantics::references_of` | Cross-file when the symbol is one the workspace index holds (a module, a package, an exported member, a port). Saved uses are declaration-to-occurrence postings built with the project index; open buffers overlay live semantics. No request-time project scan; returned spans are converted per touched file in one batch. See `docs/features/references-nav/README.md` | | `textDocument/documentHighlight` | `pairs::analyze`, else `Semantics::references_of` | A scope keyword highlights its own closer; anything else highlights the symbol's occurrences in this file. Kind is always `Text`; neither answer means `null`, so the editor keeps its word highlighting. Same feature README | | `textDocument/foldingRange` | `pairs::analyze` + comment trivia | One `Region` per matched scope pair, folded through the line *before* the closer so `end`/`endmodule` stays visible, plus one `Comment` per multi-line block comment. An unmatched opener folds nothing. Same feature README | | `textDocument/documentSymbol` | `Semantics::document_symbols` | Hierarchical | @@ -260,7 +260,7 @@ empty until the first `didOpen`, which is the whole saving on a large project. **Stated plainly, because it is what a user notices:** every cross-file answer in the table above is **scope-relative**. A definition, a `workspace/symbol` -hit, an `incomingCalls` census, a `subtypes` list, a `find_references` sweep or +hit, an `incomingCalls` census, a `subtypes` list, a references lookup or a workspace rename covers the files in scope and no others — a symbol in a folder the scope has not reached does not exist as far as this server is concerned, exactly as one outside a filelist never did. Opening a file in that @@ -461,17 +461,17 @@ spans, and `defines::{collect_defines, Define, DefineTable}`. reference_at, references_of, document_symbols, symbol, symbols, references, reference_id_at, scope}`, `Symbol { name, kind, name_span, decl_span, scope, child_scope }`, `Scope::owner`, `SymbolKind`, `Resolution`, `DocumentSymbol`, -and the workspace layer — `WorkspaceIndex::{build, path, units, member, -find_define, workspace_symbols}`, `resolve_external`, +and the workspace layer — `WorkspaceIndex::{build, path, file_id, units, +member, find_define, references_to, references_are_ambiguous, +workspace_symbols}`, `resolve_external`, `ExternalResolutions::{definition_of, get}`, `ExternalTarget::best`, `Definition`, `Def`. **Consumed from `vlog_refactor`:** `prepare_rename`, `rename`, -`instantiation_plan` and friends, the port refactorings, and — since -references-nav (M7) — `find_references(files, file, offset, -include_declaration) -> Result, String>`, which is -the cross-file half of `textDocument/references`. Every one of them takes the -same `Workspace::sources()` file set. +`instantiation_plan` and friends, and the port refactorings. Rename consumes +the `Workspace::sources()` file set. `find_references` remains available and +is the equivalence oracle for the indexed references test, but is no longer +called by the request handler. **Consumed from `vlog_formatter`:** `format_source(&str, &Config) -> Result` and `Config { max_width, indent_width }`. @@ -677,11 +677,11 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory: answering across the workspace means resolving every other file's references *into* this one — an inverted index the workspace layer does not build. It is a real feature, not a small addition.~~ Delivered by - **references-nav** (M7). The inverted index was never built: M2's rename - already resolves every *other* file's references and asks whether each - one lands on this declaration, so the answer came from sharing that walk - (`vlog_refactor::find_references`) rather than from new machinery. The - same round added `documentHighlight` for symbols and `foldingRange`. + **references-nav** (M7). It initially shared M2's rename walk; on + 2026-08-27 `WorkspaceIndex` gained persisted declaration-to-occurrence + postings and the request moved to indexed lookup, with the old walk kept + as a correctness oracle. The same round added `documentHighlight` for + symbols and `foldingRange`. `docs/features/references-nav/README.md`. - [x] ~~**Not done:**~~ `lucisv.toml` discovery, `.gitignore`-aware indexing — delivered by lucisv-core-lift (both Handshakes below marked DELIVERED). diff --git a/docs/features/references-nav/README.md b/docs/features/references-nav/README.md index 7a089e4..2a6d569 100644 --- a/docs/features/references-nav/README.md +++ b/docs/features/references-nav/README.md @@ -29,22 +29,24 @@ predicate, and three handlers. edited but not saved, when the file is new) is answered in-file until the next rebuild. That is the same staleness window every other cross-file answer already has, documented in `docs/features/lucisv-server/README.md`. -- **A references answer costs what a rename costs.** The cross-file path calls - `Workspace::sources()`, which re-reads every in-scope file, and then - re-analyzes the files that spell the name. Measured at 218 ms over the - 860-file corpus (below); the gate above is what keeps a local signal at - 1 ms rather than paying that on every request. +- **A references answer is an indexed lookup.** Each `FileFacts` record stores + compact facts for references to externally reachable declarations. The + finished `WorkspaceIndex` resolves those facts once into declaration-to-use + postings, and a request reads only that posting list. Open documents replace + their saved postings with live `Semantics`, preserving unsaved additions and + deletions. The old `Workspace::sources()` + refactor walk remains rename's + correctness engine but is no longer on the references request path. - **A refusal degrades to the in-file answer, it is not an error.** The shared engine refuses an ambiguous name (declared in two indexed files) exactly as a rename does. `textDocument/references` is a read-only convenience, so the handler sends the file's own occurrences rather than a `RequestFailed`: a highlight the editor can draw beats a shrug, and the refusal the user actually needs to see is the one on the rename they then attempt. -- **Reference spans are trusted the way rename trusts them**, minus the edit - safety check: `find_references` still drops any span that does not slice - back to the name it claims, but it does not run the re-parse verification - pass, because it produces no edits and CLAUDE.md invariant #1 is about - output, not about a list of places. +- **Reference spans are produced by the semantic analysis and versioned with + the file facts.** A cache entry is content-addressed, so a saved span cannot + be paired with different bytes; an open file contributes live spans instead. + Location conversion fetches and line-indexes each touched file once, however + many occurrences it contains. - **Read/write is not distinguished** in `documentHighlight`. LSP permits a plain `Text` kind, and telling a read from a write in Verilog means classifying continuous vs. procedural assignment, port direction and @@ -56,7 +58,8 @@ predicate, and three handlers. ## Handshakes -**New public API in `vlog_refactor`** — the one handshake this round changes: +**The original public API in `vlog_refactor`**, retained for rename and as the +equivalence oracle in tests: ```rust pub fn find_references( @@ -72,7 +75,7 @@ current text, open buffers already overlaying disk). The result is sorted by path then by position; an `Err` is the sentence a rename at that position would refuse with. -**Where the sharing lives, and why there.** The collection walk is +**Where the original sharing lives.** The collection walk is `Scope::collect_occurrences` in `crates/vlog_refactor/src/rename.rs` — lifted out of `collect_edits`, which now calls it and turns the spans into edits. `find_references` (`crates/vlog_refactor/src/references.rs`) calls the same @@ -81,15 +84,24 @@ spans. The alternative considered was lifting the walk into `vlog_semantic`; it was rejected because the walk is not a semantic query — it needs the `Scope` cache, the workspace overlay *per file*, and the ambiguity policy, all of which are refactor-crate concerns, and `lucisv_server` already depends -on `vlog_refactor`. Copy-pasting the walk into the server was never on the -table: a references list that disagreed with what a rename would touch is a -lie about what lucisv is going to do. +on `vlog_refactor`. The indexed implementation is compared directly with this +walk in the server tests, so moving the hot path does not create a second +semantic answer. -**Consumed from `vlog_semantic`** (all pre-existing, nothing requested): +**New public API in `vlog_semantic`:** `WorkspaceIndex::{file_id, +references_to, references_are_ambiguous}`, plus `DefinitionKey` and +`ReferenceSite`. `FileFacts`' encoded shape now includes local and unresolved +external reference facts, and `FACTS_FORMAT` is **2**. A changed file rebuilds +the merged postings from compact in-memory facts; it does not reread or parse +the other files. `Semantics::{symbol_at, reference_at, reference_id_at}` and +`Document::token_at` now use start-sorted position tables and binary search. + +**Consumed from `vlog_semantic`:** `Semantics::{reference_at, reference_id_at, references_of, symbol, symbol_at, scope}`, `Scope::owner`, `Symbol::{name, scope, name_span}`, `ExternalResolutions::get`, `ExternalTarget::best`, -`WorkspaceIndex::{units, member}`. +`WorkspaceIndex::{units, member, file_id, references_to, +references_are_ambiguous}`. **Consumed from `vlog_parser`**: `token::Comment { span }` trivia and `LineIndex::line_col` for folding. @@ -108,11 +120,22 @@ and none was made. ## Status / TODO +- [x] **Indexed navigation performance (2026-08-27):** persist each file's + externally reachable reference facts beside its declarations, merge them + into declaration-to-occurrence postings in `WorkspaceIndex`, and route + hover/definition/references through indexed cursor and location lookups. + Preserve ambiguity refusals and unsaved open-buffer overlays; prove the + indexed answer equals the existing refactor walk before removing that + walk from the request path. Release probe: **0.064 ms/request** over 820 + synthetic files and five returned locations, versus **23.431 ms** for + the old walk on the same workspace. + - [x] `Scope::collect_occurrences` factored out of `collect_edits`, with `collect_edits` rewritten on top of it (no behaviour change; the rename suite is the regression test). - [x] `vlog_refactor::find_references`, new module `references.rs`, 7 tests. -- [x] `nav::references` routes through it when the symbol can leave the file. +- [x] `nav::references` routes through `WorkspaceIndex` postings when the + symbol can leave the file; the refactor walk remains its tested oracle. - [x] `nav::leaves_this_file` — the index-only gate that keeps a local signal off the workspace walk. - [x] `nav::document_highlights` — symbol occurrences in this file. @@ -142,6 +165,42 @@ and none was made. ## Work log +### 2026-08-27 — indexed navigation performance + +- Began replacing the per-request `Workspace::sources()` + + `vlog_refactor::find_references` rebuild with reference facts stored in the + existing semantic index. The chosen shape is deliberately not a second + project model: `FileFacts` remains the per-file persistence and incremental + update unit, while `WorkspaceIndex` gains the merged inverted postings. + `FACTS_FORMAT` will bump because the persistent record gains fields; the + cache's version handshake therefore drops old records rather than reading a + partial shape. +- Scope remains the scope ladder's decision (filelist exactly when configured, + otherwise the folder/workspace setting already in force). This round changes + the cost of navigation inside that scope, not which files the user asked the + server to index. +- Completed the inverted index in the existing `FileFacts` / + `WorkspaceIndex` lifecycle. `FACTS_FORMAT` moved from 1 to 2, so an old cache + is discarded safely. Incremental save updates rebuild the postings from + compact facts already in memory; adding/removing files still follows the + index's path-sorted `FileId` contract. +- `nav::references` now resolves the live cursor to one indexed declaration, + reads its posting list, overlays every open buffer's current semantics, and + batches byte-span-to-LSP conversion per touched file. Duplicate declarations + and ambiguous uses still fall back to the in-file answer. Permanent tests + cover module, package-member and port references, cache round trips, + incremental equivalence, ambiguity, unsaved deletions/additions, moved live + declarations, and direct equality with `vlog_refactor::find_references`. +- Cursor hot paths no longer sweep the whole open file: semantic declaration + and reference lookup, plus macro-token hover, use binary-searched position + tables. Include definition inspects only the cursor's line. +- The ignored release latency probe builds 820 files and returns five + locations: **0.064 ms/request** averaged over 200 indexed requests; the old + source collection + refactor walk took **23.431 ms** once on the same files + (about **366×** slower). Command: + `cargo test --release -p lucisv_server + qa_indexed_references_latency_over_a_large_workspace -- --ignored --nocapture`. + ### 2026-08-24 — dev agent (M7) - **Read first**: `CLAUDE.md`, `docs/features/refactor/README.md`'s triage, @@ -463,6 +522,27 @@ correctness or safety issue in the shipped feature. ## Review +**2026-08-27 — lead, indexed-navigation performance round (external dev: +codex).** Reviewed the full diff line-by-line and ran all three gates +independently (fmt clean, clippy silent, 1155 server tests + workspace +suite green). The design keeps the one-project-model rule: reference +facts live in `FileFacts` (the existing persistence and incremental +unit), postings are merged in `WorkspaceIndex`, and `FACTS_FORMAT` 1→2 +plus the cache header's format handshake discards every v1 store whole — +verified in `index_cache.rs:324`. `macro_definitions` filters +`DefineKind::Define`, byte-identical semantics with the +`DefineTable::all` it replaces. Ambiguity is preserved everywhere it +mattered: ambiguous postings are marked, an ambiguous live overlay use +aborts to the in-file answer mid-collection, and the rename refusal +contract survives. The equivalence test pins the indexed answer to the +old `vlog_refactor::find_references` walk, which stays as rename's +engine and the oracle. Lead re-ran the ignored release probe: +0.062 ms/request over 820 files vs 21.7 ms for the old walk (~350×), +consistent with the work log's numbers. No QA-agent pass this round; +the lead review substituted, and the incremental-fingerprint, +unsaved-buffer and ambiguity tests cover the paths a QA attack would +have targeted. Accepted. + **2026-08-24 — lead.** Reviewed after QA's ship verdict (clean first pass); gates run independently (1330 tests, 0 failures, clippy silent). The factoring is the right move — `collect_occurrences` peeled out of diff --git a/docs/features/vlog-semantic/README.md b/docs/features/vlog-semantic/README.md index 116b39b..17bebd4 100644 --- a/docs/features/vlog-semantic/README.md +++ b/docs/features/vlog-semantic/README.md @@ -33,6 +33,7 @@ impl Semantics { // the LSP queries fn symbol_at(&self, offset: u32) -> Option; fn reference_at(&self, offset: u32) -> Option<&Reference>; + fn reference_id_at(&self, offset: u32) -> Option; fn definition_of(&self, offset: u32) -> Option<&Symbol>; fn references_of(&self, SymbolId) -> Vec<&Reference>; fn document_symbols(&self) -> Vec; @@ -362,6 +363,8 @@ anywhere, and under 3 % unresolved on cleanly-parsed files. with their paths - [x] Queries: `symbol_at`, `reference_at`, `definition_of`, `references_of`, `document_symbols` +- [x] 2026-08-27: declaration/reference cursor queries use start-sorted + position tables and binary search rather than scanning every symbol/use - [x] `Error` nodes are opaque; tolerant trees analyze without panicking - [x] Tests: 19 behavior tests + 6 scanner unit tests + corpus smoke test - [x] TODO.md §6 `vlog_semantic` checkbox @@ -376,6 +379,11 @@ anywhere, and under 3 % unresolved on cleanly-parsed files. ## Work log +**2026-08-27 — indexed navigation.** `Semantics` now builds compact sorted +`(TextRange, SymbolId/ReferenceId)` position tables with the analysis. +`symbol_at`, `reference_at` and `reference_id_at` binary-search those tables; +their public answers and half-open span rules are unchanged. + **2026-08-26 — overlay-promotion dev agent (lead-authorized, cross-module).** `bind.rs` gains `Target::Type`, emitted by `bind_data_type`'s unqualified arm and nowhere else, so pass two can tell a type window from an expression. diff --git a/docs/features/workspace-index/README.md b/docs/features/workspace-index/README.md index 96250b4..20b5bde 100644 --- a/docs/features/workspace-index/README.md +++ b/docs/features/workspace-index/README.md @@ -9,7 +9,9 @@ paths that could finish it — 19.6 % of every use on cleanly-parsed corpus file that finishes them. `WorkspaceIndex::build` scans every file in the workspace once and records what each one *declares* — modules, packages, file-scope typedefs, each package's and module's exported members, and each file's -`` `define`` table. `resolve_external` walks one file's external candidates +`` `define`` table. Since 2026-08-27 it also records compact reference facts +and merges them into declaration-to-occurrence postings. `resolve_external` +walks one file's external candidates against that index and answers them in an **overlay** keyed by reference id. That is what turns `import prim_pkg::*` and `prim_fifo_sync u_fifo (...)` into a jump into the file that declares them — TODO.md §6's "cross-file resolution @@ -25,12 +27,15 @@ impl WorkspaceIndex { fn files(&self) -> &[PathBuf]; // indexed by FileId fn path(&self, FileId) -> Option<&Path>; + fn file_id(&self, &Path) -> Option; // 2026-08-27 fn units(&self, name: &str) -> &[Def]; // module | package | file-scope typedef fn member(&self, unit: &str, member: &str) -> &[Def]; fn members_of(&self, unit: &str) -> impl Iterator; 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 references_to(&self, def: &Def) -> &[ReferenceSite]; // 2026-08-27 + fn references_are_ambiguous(&self, def: &Def) -> bool; // 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 @@ -145,6 +150,11 @@ written"). Ambiguity means something else — see below. module stays unreachable, which is correct and is a test. - **`` `define`` tables**: `defines::collect_defines` per file, keyed by `FileId`, read off the same token stream the parse used. +- **Reference postings**: uses of the externally reachable declarations above. + Each file persists local declaration/use span pairs and unresolved external + candidates; after every build or incremental update, the merged declaration + tables resolve those compact facts into `DefinitionKey -> [ReferenceSite]`. + Ambiguous candidates are marked rather than assigned to a guessed target. A declaration whose `name_span` is empty (the single-file layer's "I could not locate this name in the source") is **not** indexed: an editor must never be @@ -407,10 +417,23 @@ and more than half of all external candidates answered on clean files. equal to a whole build; instantiation and inheritance edge tables (`instantiations_of`, `subclasses_of`); `fingerprint` as the equivalence witness +- [x] 2026-08-27 (`references-nav` performance): persisted reference facts, + declaration-to-occurrence postings, ambiguity markers and indexed macro + lookup; reference postings included in the incremental fingerprint - [ ] Deferred (non-goals above): `` `include`` graph, elaboration ## Work log +**2026-08-27 — indexed navigation.** `FileFacts` gained compact local and +external reference records and its persisted format moved to version 2. +`WorkspaceIndex` resolves them into reverse postings after declaration tables +are merged, including on an incremental update, without rereading or reparsing +other files. The public query is `references_to`; ambiguous external uses are +tracked separately so navigation preserves the existing rename refusal. Three +focused tests cover postings, incremental/full-build equivalence, and +ambiguity, while the record round-trip and corpus acceptance cover persistence +and real-source scale. + **2026-08-26 — overlay-promotion dev agent (lead-authorized, cross-module).** `resolve_external` gained one arm: an `InheritedCandidate`'s paths are tried like an external candidate's, and an entry is recorded only when one lands, so