TODO §71.1. On OpenTitan hw (4 058 files) every save cost ~160 ms of whole-index work, twice (the save and VS Code's watcher echo), and watcher events for files the index could not hold started whole rescans. - vlog_semantic: resolution records every table lookup per reading file, misses included (workspace/dependents.rs, references.rs, replace.rs); an update re-resolves the edited file and the readers of keys whose values changed in what resolution reads. An unchanged record merges nothing. When the readers hold more than an eighth of all references, old results are removed in one pass over the postings. - lucisv_server: watcher events are classified per file (state/watched.rs); the include graph keeps every include line as written and re-resolves the lines a named path could satisfy, in one pass per event; an event naming more paths than half the index takes the single rescan; an open buffer the index does not hold joins on its first save; completion tables are rebuilt only for the names a file declares. Every save still republishes every open buffer. The line-length lint follows the formatting style's width. - Fixed on the way: removing an included header left other files' include edges pointing at it. Typical saves: comment or watcher echo <0.3 ms, local signal 4 ms, package member 12 ms; warm startup +40..120 ms for the readers table. QA failed the first cut on four stale answers found with an independent fresh-server oracle; all four are fixed and are differential tests. Dev (three rounds), QA (two rounds) and lead review: docs/features/localized-reindex/README.md. TODO.md files lane 71.7 from what the QA rounds and an investigation found in earlier releases too. Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both package-lock.json spots); notes in CHANGELOG.md (## 0.65.6) and editors/vscode/CHANGELOG.md. Gates: tools/gates.sh PASS on this tree; vlog_semantic 435/0, lucisv_server 2011/0, lucisv_mcp 384/0. Co-Authored-By: Claude Mythos 5.2 <[email protected]>
430 lines
19 KiB
Rust
430 lines
19 KiB
Rust
//! How an index changes after it is built: replace one file's record, add
|
|
//! or remove a file, absorb a batch — each producing exactly the index a full
|
|
//! build over the same records would — the [`WorkspaceIndex::merge`] that
|
|
//! makes that hold by construction, and the [`WorkspaceIndex::fingerprint`]
|
|
//! that proves it.
|
|
|
|
use std::collections::HashSet;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use vlog_parser::defines::DefineKind;
|
|
|
|
use crate::model::Surface;
|
|
|
|
use super::record::{facts_of, FileFacts};
|
|
use super::{DefinitionKey, FileId, InheritanceEdge, InstantiationEdge, WorkspaceIndex};
|
|
|
|
impl WorkspaceIndex {
|
|
/// 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).
|
|
///
|
|
/// Reports whether the index moved: `false` exactly when the file's new
|
|
/// record equals the one held, which is the watcher's echo of a save and a
|
|
/// save that changed nothing — the cheapest answer there is, and a sound
|
|
/// one, since an index is a function of its records.
|
|
pub fn update_file(&mut self, path: PathBuf, src: &str) -> bool {
|
|
self.update_facts(facts_of(path, src))
|
|
}
|
|
|
|
/// [`WorkspaceIndex::update_file`] for a file whose facts are already
|
|
/// known — read from a cache, or from an analysis the caller already holds
|
|
/// ([`FileFacts::from_analysis`]) — so the update costs no parse at all.
|
|
///
|
|
/// Exactly [`WorkspaceIndex::update_file`] with the parse already done, the
|
|
/// same way [`IndexBuilder::add_facts`](super::IndexBuilder::add_facts) is
|
|
/// [`IndexBuilder::add_file`](super::IndexBuilder::add_file) with
|
|
/// the parse already done: same contract, same result. Whether the record
|
|
/// really describes the file is the caller's business.
|
|
///
|
|
/// Reports whether the index moved, as [`WorkspaceIndex::update_file`]
|
|
/// does.
|
|
pub fn update_facts(&mut self, facts: FileFacts) -> bool {
|
|
let path = facts.path.clone();
|
|
match self.facts.binary_search_by(|held| held.path.cmp(&path)) {
|
|
Ok(at) if self.facts[at] == facts => return false,
|
|
// 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) => {
|
|
self.replace_facts(at, facts);
|
|
}
|
|
// 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();
|
|
}
|
|
}
|
|
true
|
|
}
|
|
|
|
/// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for
|
|
/// many files at once — and for **one** merge rather than one each.
|
|
///
|
|
/// Same contract as both — what comes out is the index a full
|
|
/// [`WorkspaceIndex::build`] over the records it now holds would have
|
|
/// produced — **provided each path appears once in `records`**. It holds
|
|
/// for the same reason theirs does: the records are kept path-sorted and
|
|
/// one file to a path, and [`WorkspaceIndex::merge`] is then the same loop
|
|
/// [`IndexBuilder::finish`](super::IndexBuilder::finish) runs over the
|
|
/// same list. A batch that names one path twice is an update applied
|
|
/// twice, so the **last** record wins,
|
|
/// where a `build` over the same duplicated input keeps the *first*
|
|
/// (`index_order` dedups) — the update semantic is the right one for an
|
|
/// "absorb what changed" API, and the one caller that feeds a scan
|
|
/// (`Scan::work`) is deduped before anything is staged. QA pinned the
|
|
/// divergence
|
|
/// (`absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records`).
|
|
///
|
|
/// One merge, because a merge is a pass over **every** record the index
|
|
/// holds: a scan that merged after each of its files would be quadratic in
|
|
/// the size of the workspace, which is measured rather than argued in
|
|
/// `docs/features/scan-interleave/README.md`. A caller feeding a scan
|
|
/// therefore batches — it stages records as it takes them and folds a
|
|
/// batch in only when something is about to read the index.
|
|
///
|
|
/// `gone` is dropped first, so a path in both lists ends up held: a file
|
|
/// that moved out of one scan's scope and back into the next's is one
|
|
/// file, not a removal that happens to run second.
|
|
pub fn absorb(&mut self, records: Vec<FileFacts>, gone: &[PathBuf]) {
|
|
for path in gone {
|
|
if let Ok(at) = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)) {
|
|
self.files.remove(at);
|
|
self.facts.remove(at);
|
|
}
|
|
}
|
|
for facts in records {
|
|
match self.facts.binary_search_by(|held| held.path.cmp(&facts.path)) {
|
|
Ok(at) => self.facts[at] = facts,
|
|
Err(at) => {
|
|
self.files.insert(at, facts.path.clone());
|
|
self.facts.insert(at, facts);
|
|
}
|
|
}
|
|
}
|
|
self.merge();
|
|
}
|
|
|
|
/// 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();
|
|
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());
|
|
// The census's size, on the same rule the `define` table follows:
|
|
// the words themselves are per-file and never merged, so a count
|
|
// is enough to catch the failure a fingerprint exists to catch —
|
|
// a record lost, duplicated or attached to the wrong file.
|
|
let words = self.facts.get(id).map_or(0, |facts| facts.words.len());
|
|
out.push_str(&format!(
|
|
"file {id} {} defines={defines} words={words}\n",
|
|
path.display()
|
|
));
|
|
}
|
|
for symbol in self.workspace_symbols("") {
|
|
out.push_str(&format!(
|
|
"sym {} in {:?} {:?} {}:{}..{} decl={}..{} line={} detail={:?} at={:?} type={:?}\n",
|
|
symbol.name,
|
|
symbol.container,
|
|
symbol.def.kind,
|
|
symbol.def.file.0,
|
|
symbol.def.name_span.start,
|
|
symbol.def.name_span.end,
|
|
symbol.def.decl_span.start,
|
|
symbol.def.decl_span.end,
|
|
symbol.def.lines.name,
|
|
symbol.def.lines.detail,
|
|
symbol.def.lines.positions,
|
|
symbol.def.type_name
|
|
));
|
|
}
|
|
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<(&DefinitionKey, &u32)> = self.ambiguous_references.iter().collect();
|
|
ambiguous.sort();
|
|
for (definition, count) in ambiguous {
|
|
out.push_str(&format!(
|
|
"ambiguous-ref {}:{}..{} x{count}\n",
|
|
definition.file.0, definition.name_start, definition.name_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 instance in &edge.instances {
|
|
out.push_str(&format!(
|
|
" instance {} name {}..{} span {}..{} at {:?} {:?}\n",
|
|
instance.name,
|
|
instance.name_span.start,
|
|
instance.name_span.end,
|
|
instance.span.start,
|
|
instance.span.end,
|
|
instance.name_positions,
|
|
instance.positions
|
|
));
|
|
}
|
|
}
|
|
}
|
|
// The re-export edges, which decide what `a_pkg::x` means and are
|
|
// therefore an observable in their own right — a merge that dropped
|
|
// one would otherwise show up only as whichever references happened to
|
|
// resolve through it.
|
|
for (exporter, edges) in &self.reexports {
|
|
for edge in edges {
|
|
out.push_str(&format!("reexport {exporter} <- {}::{}\n", edge.package, edge.item));
|
|
}
|
|
}
|
|
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
|
|
));
|
|
}
|
|
}
|
|
// Not an answer any caller reads, but the table that decides which
|
|
// files the *next* update re-resolves: one that drifted from a
|
|
// rebuild's would be a stale posting waiting to happen.
|
|
self.dependents.render(&mut out);
|
|
out
|
|
}
|
|
|
|
/// Rebuild every merged table, the postings and the readers table from
|
|
/// the per-file records.
|
|
///
|
|
/// The tables are one loop over the path-sorted records pushing in the
|
|
/// order it meets them ([`WorkspaceIndex::merge_tables`]), which is the
|
|
/// *only* place any table's order is decided — so a restricted merge over
|
|
/// a few files and a whole one agree by construction, and both agree with
|
|
/// [`IndexBuilder::finish`](super::IndexBuilder::finish).
|
|
pub(super) fn merge(&mut self) {
|
|
self.merge_tables(None, None);
|
|
self.merge_bases();
|
|
// 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();
|
|
}
|
|
|
|
/// The table half of [`WorkspaceIndex::merge`]: clear the keys `affected`
|
|
/// names (all of them for `None`) and push back every record under them,
|
|
/// visiting `files` — the files that hold such records, in id order — or
|
|
/// every file for `None`. Visiting fewer files is the same loop, because a
|
|
/// file with no record under a cleared key pushes nothing.
|
|
pub(super) fn merge_tables(&mut self, affected: Option<&Affected>, files: Option<&[usize]>) {
|
|
match affected {
|
|
None => {
|
|
self.units.clear();
|
|
self.members.clear();
|
|
self.hier_members.clear();
|
|
self.instantiations.clear();
|
|
self.subclasses.clear();
|
|
self.reexports.clear();
|
|
self.macro_definitions.clear();
|
|
}
|
|
Some(affected) => {
|
|
for name in &affected.units {
|
|
self.units.remove(name);
|
|
}
|
|
for name in &affected.containers {
|
|
self.members.remove(name);
|
|
self.hier_members.remove(name);
|
|
}
|
|
for name in &affected.modules {
|
|
self.instantiations.remove(name);
|
|
}
|
|
for name in &affected.bases {
|
|
self.subclasses.remove(name);
|
|
}
|
|
for name in &affected.exporters {
|
|
self.reexports.remove(name);
|
|
}
|
|
for name in &affected.macros {
|
|
self.macro_definitions.remove(name);
|
|
}
|
|
}
|
|
}
|
|
match files {
|
|
Some(files) => files.iter().for_each(|&id| self.push_records(id, affected)),
|
|
None => (0..self.facts.len()).for_each(|id| self.push_records(id, affected)),
|
|
}
|
|
}
|
|
|
|
/// Push one file's records under the keys `affected` names (every key for
|
|
/// `None`), in the order the record holds them.
|
|
fn push_records(&mut self, id: usize, affected: Option<&Affected>) {
|
|
let file = FileId(id as u32);
|
|
let Some(facts) = self.facts.get(id) else { return };
|
|
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;
|
|
}
|
|
// The record's own tag picks the table; the two are keyed
|
|
// alike, are cleared together above, and a caller that names
|
|
// no surface reads the connection one.
|
|
let table = match decl.surface {
|
|
Surface::Connection => &mut self.members,
|
|
Surface::Hierarchical => &mut self.hier_members,
|
|
};
|
|
table
|
|
.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,
|
|
instances: edge.instances.clone(),
|
|
});
|
|
}
|
|
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() });
|
|
}
|
|
for (exporter, entry) in &facts.reexports {
|
|
if affected.is_some_and(|a| !a.exporters.contains(exporter)) {
|
|
continue;
|
|
}
|
|
self.reexports.entry(exporter.clone()).or_default().push(entry.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));
|
|
}
|
|
}
|
|
|
|
/// The reverse inheritance edge, rebuilt whole: one entry per `extends`
|
|
/// written anywhere (a few thousand on opentitan), first in file order
|
|
/// winning, which is `units`' rule.
|
|
pub(super) fn merge_bases(&mut self) {
|
|
self.bases.clear();
|
|
for facts in &self.facts {
|
|
for (base, subclass) in &facts.subclasses {
|
|
self.bases.entry(subclass.name.clone()).or_insert_with(|| base.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)]
|
|
pub(super) struct Affected {
|
|
pub(super) 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.
|
|
pub(super) containers: HashSet<String>,
|
|
pub(super) modules: HashSet<String>,
|
|
pub(super) bases: HashSet<String>,
|
|
/// Keys of the `reexports` table — the package that writes the `export`,
|
|
/// never the package it takes the name from: a file changing what `a_pkg`
|
|
/// re-exports moves `a_pkg`'s edges and no one else's.
|
|
pub(super) exporters: HashSet<String>,
|
|
pub(super) macros: HashSet<String>,
|
|
/// Keys of the `bases` table — the *extending* class, which is what a
|
|
/// member lookup up the `extends` chain asks it by.
|
|
pub(super) classes: HashSet<String>,
|
|
}
|
|
|
|
impl Affected {
|
|
pub(super) fn of(facts: &FileFacts) -> Affected {
|
|
let mut out = Affected::default();
|
|
out.add(facts);
|
|
out
|
|
}
|
|
|
|
pub(super) 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()));
|
|
self.classes.extend(facts.subclasses.iter().map(|(_, class)| class.name.clone()));
|
|
self.exporters.extend(facts.reexports.iter().map(|(exporter, _)| exporter.clone()));
|
|
self.macros.extend(facts.defines.entries().iter().map(|define| define.name.clone()));
|
|
}
|
|
}
|