Persistent index cache: a half-indexed workarea resumes where it stopped
ci / checks (push) Failing after 8s
ci / corpus (push) Failing after 5s

Owner-requested round. Every parsed file's FileFacts record is written
through to an index-cache store (append per file, atomic compaction at
scan end — a crash loses at most the file in flight), keyed by a
content hash that is the whole key: no mtime fast path, by measured
argument (6 ms of a 181 ms warm scan, and unsound against save-time
write-through). On reopen, hits skip parsing and the resume is
visible — cached: vs indexing: log lines, the bar counting through
hits, and an end message saying how many came from cache. Warm rescan
322 to 179 ms release, 1.5 s to 0.76 s debug; 910 KB store for the
860-file corpus. Location: lucisv.index.cachePath > the extension's
context.storageUri via initializationOptions (the one extension.js
change) > the OS cache dir keyed by workspace identity > nowhere;
lucisv.index.persist (default on) gates both directions immediately.

The cache is a performance artifact, never a correctness input, and
after the fix round that promise is total against everything but
intentional forgery — which the threat model now formally excludes
(same-user disk; a keyed MAC would be theater): a per-record checksum
drops every corrupt-but-parseable line (poisoned and reforged shapes
both pinned so the checksum is never mistaken for a MAC), first-writer
initialization is a create_new claim with structural 100/100 survival,
and a torn multi-byte tail costs exactly the torn record (0 of 583
offsets lose more). Old-format stores discard wholesale. Load==fresh
fingerprint equality swept over the corpus.

45 tests added across the main and fix rounds (dev 33+2, QA 9+3, one
QA test-construction bug self-caught), 2 ignored probes.

docs/features/index-persistence/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-27 16:33:52 -07:00
1 parent 5e4aa7bd6f
commit e4b1f55c12
17 files changed
+4280 -50

No files matched your search

+14 -2
View File
@@ -493,7 +493,10 @@ later:
in other files. Start as a full-scan-on-startup index (Verilog
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`).
(`docs/features/incremental-index/README.md`); and ~~re-scanned from zero on
every startup~~ — what a scan learns persists since 2026-08-27, so a reopened
workspace indexes from records rather than parses and an interrupted scan
resumes (`docs/features/index-persistence/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),
@@ -565,7 +568,11 @@ later:
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.
still deferred. **A second piece answered without salsa, 2026-08-27**
(`docs/features/index-persistence/README.md`): every file's `FileFacts` are
written to a content-keyed store as a scan parses them, so the recompute a
*new session* would otherwise repeat is skipped instead — 1.8x on a whole
corpus rescan, and a scan interrupted halfway resumes where it stopped.
- [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
@@ -768,6 +775,11 @@ and are not gaps.
1000 reports per rescan), a per-file `window/logMessage` under
`lucisv.index.logFiles`, and a 1 MiB default walk-file size cap under
`lucisv.index.maxFileSize` whose skips the `end` message counts.
→ **Extended again, 2026-08-27**
(`docs/features/index-persistence/README.md`): a file restored from the
persistent index cache logs `cached:` rather than `indexing:` and is counted
in the `end` message — `860 files indexed, 860 from cache` — so a rescan that
flew past says why.
Everything else above — the capability gate, the token scheme, the
create's ignored answer, the ordering against the republish — is
unchanged.
File diff suppressed because it is too large. Load diff
+22 -1
View File
@@ -18,6 +18,7 @@ mod format;
mod hierarchy;
mod hover;
mod includes;
mod index_cache;
mod inlay;
mod inline;
mod lens;
@@ -71,6 +72,10 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
// capabilities have no field for it and drop it on the floor — see
// `ranges_formatting_support`.
let ranges_formatting = ranges_formatting_support(&params);
// Read from the raw params for the same reason, and because it is not a
// capability at all: `initializationOptions` is whatever the client's
// extension put there.
let storage = storage_path(&params);
// A client that sends params we cannot read still gets a server; every
// field we want is optional anyway.
let params: InitializeParams = serde_json::from_value(params).unwrap_or_default();
@@ -87,7 +92,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
};
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
Server::new(connection, roots, abilities).run()?;
Server::new(connection, roots, abilities, storage).run()?;
io_threads.join()?;
Ok(())
}
@@ -373,6 +378,22 @@ fn ranges_formatting_support(params: &serde_json::Value) -> bool {
params["capabilities"]["textDocument"]["rangeFormatting"]["rangesSupport"] == true
}
/// The folder the client set aside for this workspace's server state —
/// `initializationOptions.storagePath`, which the VS Code extension fills in
/// with `context.storageUri`.
///
/// The persistent index cache goes here when there is one: it is
/// per-workspace, the editor cleans it up when the workspace is forgotten,
/// and it needs no guess about where this platform keeps caches. A client
/// that sends nothing — every client but ours, and ours before this — leaves
/// the OS cache directory to decide
/// (`docs/features/index-persistence/README.md`). A blank value counts as
/// unset, the same reading `lucisv.serverPath` gives a blank setting.
fn storage_path(params: &serde_json::Value) -> Option<PathBuf> {
let path = params["initializationOptions"]["storagePath"].as_str()?;
(!path.trim().is_empty()).then(|| PathBuf::from(path))
}
/// Whether the client can expand `${1:x}` tabstops in a completion item.
///
/// A client that did not say so gets the skeleton as plain text: a literal
+172 -14
View File
@@ -189,8 +189,9 @@ impl Server {
connection: Connection,
roots: Vec<std::path::PathBuf>,
abilities: ClientAbilities,
storage: Option<std::path::PathBuf>,
) -> Server {
Server::started(connection, roots, abilities, ClientSettings::default())
Server::started(connection, roots, abilities, ClientSettings::default(), storage)
}
/// [`Server::new`] with a client's settings already in hand — the seam the
@@ -203,6 +204,7 @@ impl Server {
roots: Vec<std::path::PathBuf>,
abilities: ClientAbilities,
client: ClientSettings,
storage: Option<std::path::PathBuf>,
) -> Server {
let mut server = Server {
connection,
@@ -222,6 +224,10 @@ impl Server {
// `true` this returns for a non-default `client` is the rebuild that
// is about to happen anyway.
let _ = server.workspace.set_client_settings(client);
// Before the first build, because it is one rung of the ladder that
// decides where that build reads its cache from
// (`docs/features/index-persistence/README.md`).
server.workspace.set_storage_path(storage);
// The earliest legal moment for anything server-initiated: `main`
// builds this only after `initialize_finish`, which returns once the
// client's `initialized` notification has arrived — and consumes it,
@@ -236,8 +242,8 @@ impl Server {
let Server { connection, workspace, .. } = &mut server;
let mut watch = IndexWatch::new(connection, bar.as_ref(), workspace.client_settings());
let warnings = workspace.open_roots_with(roots, &mut |event| watch.see(event));
let skipped = watch.skipped;
server.end_indexing(bar, skipped);
let (skipped, cached) = (watch.skipped, watch.cached);
server.end_indexing(bar, skipped, cached);
server.report_scope(warnings);
server.register_watchers();
// The pull half of the settings model. Asked here because this is the
@@ -1398,8 +1404,8 @@ impl Server {
let Server { connection, workspace, .. } = self;
let mut watch = IndexWatch::new(connection, bar.as_ref(), workspace.client_settings());
let warnings = workspace.rebuild_index_with(&mut |event| watch.see(event));
let skipped = watch.skipped;
self.end_indexing(bar, skipped);
let (skipped, cached) = (watch.skipped, watch.cached);
self.end_indexing(bar, skipped, cached);
// A rescan can change any module's instantiation count, so every lens
// a client is holding may now read wrong. Sent after the bar comes
// down, for the same reason the bar comes down before the republishes:
@@ -1462,16 +1468,22 @@ impl Server {
/// `skipped` is how many files the size cap kept out, and it is named here
/// whether or not the per-file log is on: the log is the *detail*, and a
/// user who turned it off should still learn that part of their workspace
/// is not in the index.
fn end_indexing(&self, token: Option<ProgressToken>, skipped: usize) {
/// is not in the index. `cached` is how many were restored from the
/// persistent index cache rather than parsed, and is named for the
/// opposite reason — a scan that finished suspiciously fast should say
/// why (`docs/features/index-persistence/README.md`).
fn end_indexing(&self, token: Option<ProgressToken>, skipped: usize, cached: usize) {
let Some(token) = token else { return };
let files = self.workspace.index().files().len();
let plural = if files == 1 { "" } else { "s" };
let message = Some(match skipped {
0 => format!("{files} file{plural} indexed"),
_ => format!("{files} file{plural} indexed, {skipped} skipped"),
});
self.progress(token, WorkDoneProgress::End(WorkDoneProgressEnd { message }));
let mut message = format!("{files} file{plural} indexed");
if cached > 0 {
message.push_str(&format!(", {cached} from cache"));
}
if skipped > 0 {
message.push_str(&format!(", {skipped} skipped"));
}
self.progress(token, WorkDoneProgress::End(WorkDoneProgressEnd { message: Some(message) }));
}
/// Ask the client to re-request its code lenses, because the rescan just
@@ -1619,6 +1631,11 @@ struct IndexWatch<'a> {
/// How many files the size cap kept out of this rebuild. Counted whether
/// or not the log is on, because the end message names it either way.
skipped: usize,
/// How many files came out of the persistent cache instead of being
/// parsed. Counted for the same reason and named in the same message: it
/// is the difference between "this scan was fast" and "this scan was fast
/// **because** it did not have to redo last session's work".
cached: usize,
}
impl<'a> IndexWatch<'a> {
@@ -1627,7 +1644,7 @@ impl<'a> IndexWatch<'a> {
bar: Option<&'a ProgressToken>,
settings: &ClientSettings,
) -> IndexWatch<'a> {
IndexWatch { connection, bar, log_files: settings.log_files, skipped: 0 }
IndexWatch { connection, bar, log_files: settings.log_files, skipped: 0, cached: 0 }
}
/// Report one thing the rebuild just did.
@@ -1637,6 +1654,14 @@ impl<'a> IndexWatch<'a> {
self.say(format!("indexing: {}", path.display()));
self.tick(done, total, path);
}
// A different word for a file that cost nothing, and the same
// tick: a cached file is a file of the work list, and the bar
// flying through them is exactly what the cache bought.
IndexEvent::Cached { done, total, path } => {
self.cached += 1;
self.say(format!("cached: {}", path.display()));
self.tick(done, total, path);
}
IndexEvent::Skipped { path, size, cap } => {
self.skipped += 1;
self.say(format!(
@@ -1962,9 +1987,21 @@ mod tests {
roots: Vec<PathBuf>,
abilities: ClientAbilities,
settings: ClientSettings,
) -> Session {
Session::started_in(roots, abilities, settings, None)
}
/// [`Session::started`] against a client that offered a storage
/// folder — `initializationOptions.storagePath`, which is where the
/// persistent index cache goes.
fn started_in(
roots: Vec<PathBuf>,
abilities: ClientAbilities,
settings: ClientSettings,
storage: Option<PathBuf>,
) -> Session {
let (server_end, client) = Connection::memory();
let server = Server::started(server_end, roots, abilities, settings);
let server = Server::started(server_end, roots, abilities, settings, storage);
Session { server, client }
}
@@ -2569,6 +2606,127 @@ mod tests {
})
}
/// The `message` of every `$/progress` end in one drained batch, and every
/// `window/logMessage` line in it. Read off one drain rather than through
/// `Session::ended`/`logged`, because a test that wants both cannot drain
/// twice.
fn ends(messages: &[Message]) -> Vec<Option<String>> {
messages
.iter()
.filter_map(|message| match message {
Message::Notification(n) if n.method == Progress::METHOD => {
let params: ProgressParams =
serde_json::from_value(n.params.clone()).expect("progress params");
let ProgressParamsValue::WorkDone(work) = params.value;
match work {
WorkDoneProgress::End(end) => Some(end.message),
_ => None,
}
}
_ => None,
})
.collect()
}
fn log_lines(messages: &[Message]) -> Vec<String> {
messages
.iter()
.filter_map(|message| match message {
Message::Notification(n) if n.method == LogMessage::METHOD => {
let params: LogMessageParams =
serde_json::from_value(n.params.clone()).expect("log params");
Some(params.message)
}
_ => None,
})
.collect()
}
#[test]
fn a_second_session_over_the_same_storage_folder_resumes_from_the_cache() {
// The owner's case, end to end through the real dispatch: a session
// indexes a tree, the editor goes away, and the next session over the
// same storage folder gets the same index without parsing anything.
let tree = Tree::new("resume");
tree.package("rtl/a.sv", "a_pkg");
tree.package("rtl/b.sv", "b_pkg");
let storage = Tree::new("resume_storage");
let wide = ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
};
let mut first = Session::started_in(
vec![tree.path.clone()],
watching_progress(),
wide.clone(),
Some(storage.path.clone()),
);
let cold = first.drain();
assert_eq!(ends(&cold), vec![Some("2 files indexed".to_string())], "a cold session");
assert_eq!(
log_lines(&cold).iter().filter(|line| line.starts_with("indexing: ")).count(),
2,
"both files were parsed: {:?}",
log_lines(&cold)
);
let before = first.server.workspace.index().fingerprint();
let answer =
first.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query": "pkg"}));
drop(first);
let mut second = Session::started_in(
vec![tree.path.clone()],
watching_progress(),
wide,
Some(storage.path.clone()),
);
let warm = second.drain();
assert_eq!(
ends(&warm),
vec![Some("2 files indexed, 2 from cache".to_string())],
"the bar says where the files came from"
);
let lines = log_lines(&warm);
assert_eq!(
lines.iter().filter(|line| line.starts_with("cached: ")).count(),
2,
"and so does the log, file by file: {lines:?}"
);
assert!(
!lines.iter().any(|line| line.starts_with("indexing: ")),
"nothing was parsed: {lines:?}"
);
assert_eq!(
second.server.workspace.index().fingerprint(),
before,
"the same index, byte for byte"
);
assert_eq!(
second.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query": "pkg"})),
answer,
"and the same answers over the wire"
);
}
#[test]
fn a_session_that_was_offered_no_storage_folder_keeps_its_index_in_memory() {
// What every client but ours does, and what `smoke.js` does: no
// `storagePath`, no workspace root to key an OS-directory store on,
// so nothing is persisted and nothing is read — today's behaviour,
// unchanged.
let tree = Tree::new("nostorage");
tree.package("rtl/a.sv", "a_pkg");
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
let first = session.drain();
assert_eq!(ends(&first), vec![Some("1 file indexed".to_string())]);
assert!(
log_lines(&first).iter().all(|line| !line.starts_with("cached: ")),
"nothing can come from a cache that was never written: {:?}",
log_lines(&first)
);
}
#[test]
fn the_end_message_names_what_the_cap_skipped() {
// The count survives even when the per-file log is off, because it is
+62 -1
View File
@@ -112,6 +112,18 @@ pub struct ClientSettings {
/// file's own folder. Ignored when `index_scope` is
/// [`IndexScope::Workspace`] or when a filelist defines the scope.
pub index_scope_depth: u64,
/// `lucisv.index.persist`: whether what a scan parsed is written to disk
/// so the next session can skip parsing the files that have not changed.
/// On unless a client says otherwise — a half-finished scan that has to
/// start again from zero is the thing this exists to prevent. Off means
/// off in both directions: nothing is read and nothing is written
/// (`docs/features/index-persistence/README.md`).
pub index_persist: bool,
/// `lucisv.index.cachePath`: where that store lives, absolute or relative
/// to the first workspace root. Empty means "unset", and then the
/// editor's own storage folder — or this platform's cache directory —
/// decides; see `index_cache::cache_dir` for the ladder.
pub index_cache_path: Option<String>,
}
/// The settings a client that said nothing is treated as having asked for.
@@ -132,6 +144,8 @@ impl Default for ClientSettings {
log_files: true,
index_scope: IndexScope::Folder,
index_scope_depth: 0,
index_persist: true,
index_cache_path: None,
}
}
}
@@ -180,6 +194,13 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
// guess in.
index_scope: scope(index.and_then(|i| i.get("scope"))).unwrap_or_default(),
index_scope_depth: count(index.and_then(|i| i.get("scopeDepth"))).unwrap_or(0),
// A wrong-typed `persist` leaves the cache on. The direction that
// costs something is turning it *off* by accident — a user who never
// touched the setting would silently pay for every parse again — and
// a cache that is on can only ever cost a file's parse, because every
// hit is verified against the file's own bytes.
index_persist: flag(index.and_then(|i| i.get("persist"))).unwrap_or(true),
index_cache_path: path(index.and_then(|i| i.get("cachePath"))),
}
}
@@ -362,7 +383,8 @@ mod tests {
let section = json!({
"index": {
"maxFileSize": 4096, "logFiles": false,
"scope": "workspace", "scopeDepth": 2
"scope": "workspace", "scopeDepth": 2,
"persist": false, "cachePath": "/tmp/store"
}
});
let pulled = from_section(&section);
@@ -370,9 +392,48 @@ mod tests {
assert!(!pulled.log_files);
assert_eq!(pulled.index_scope, IndexScope::Workspace);
assert_eq!(pulled.index_scope_depth, 2);
assert!(!pulled.index_persist);
assert_eq!(pulled.index_cache_path.as_deref(), Some("/tmp/store"));
assert_eq!(pulled, settings(json!({ "lucisv": section })), "one set of rules");
}
#[test]
fn the_index_cache_is_on_until_a_client_turns_it_off() {
// Same shape as the file log, and the same direction for junk: the
// setting that costs a user work if it is guessed wrong is "off", so
// anything unreadable leaves it on.
assert!(settings(json!({ "lucisv": {} })).index_persist, "absence is on");
assert!(settings(json!({ "lucisv": { "index": {} } })).index_persist, "so is an empty one");
assert!(settings(json!({ "lucisv": { "index": { "persist": true } } })).index_persist);
assert!(!settings(json!({ "lucisv": { "index": { "persist": false } } })).index_persist);
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
let found = settings(json!({ "lucisv": { "index": { "persist": bad } } }));
assert!(found.index_persist, "persist {bad} must be ignored");
}
}
#[test]
fn the_cache_path_is_unset_until_a_client_names_one() {
// The empty string is `lucisv.index.cachePath`'s own default and means
// "you decide", exactly as it does for `lucisv.filelist` — not "the
// directory named by the empty path".
assert_eq!(settings(json!({ "lucisv": {} })).index_cache_path, None);
assert_eq!(
settings(json!({ "lucisv": { "index": { "cachePath": "" } } })).index_cache_path,
None
);
assert_eq!(
settings(json!({ "lucisv": { "index": { "cachePath": ".cache/lucisv" } } }))
.index_cache_path
.as_deref(),
Some(".cache/lucisv")
);
for bad in [json!(1), json!(true), json!(null), json!(["/a"]), json!({ "path": "/a" })] {
let found = settings(json!({ "lucisv": { "index": { "cachePath": bad } } }));
assert_eq!(found.index_cache_path, None, "cachePath {bad} must be ignored");
}
}
#[test]
fn the_index_scope_is_the_open_folder_until_a_client_asks_for_the_workspace() {
// The default is the narrow one, and it is what silence, an empty
+574 -4
View File
@@ -13,8 +13,8 @@ use vlog_parser::defines::{collect_defines, DefineTable};
use vlog_parser::token::Token;
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic};
use vlog_semantic::{
analyze, index_order, resolve_external, ExternalResolutions, IndexBuilder, Semantics,
WorkspaceIndex,
analyze, index_order, resolve_external, ExternalResolutions, FileFacts, IndexBuilder,
Semantics, WorkspaceIndex,
};
use lucisv_core::config::Discovery;
@@ -23,6 +23,7 @@ use lucisv_core::walk::{collect_files, EXTENSIONS};
use crate::candidates::Candidates;
use crate::convert::Positions;
use crate::includes::IncludeGraph;
use crate::index_cache::IndexCache;
use crate::settings::{ClientSettings, IndexScope};
use crate::uri::uri_to_path;
@@ -114,6 +115,12 @@ pub enum IndexEvent<'a> {
/// counts from 0, so the file being reported is number `done + 1` of
/// `total`.
Parsing { done: usize, total: usize, path: &'a Path },
/// One file went into the index from the persistent cache instead of
/// being parsed. The same three numbers [`IndexEvent::Parsing`] carries,
/// because it is the same file of the same work list — it is *how* it got
/// there that differs, and a user watching a rescan fly through a
/// thousand files deserves to be told why.
Cached { done: usize, total: usize, path: &'a Path },
/// A walked file was skipped without being read, because it is bigger
/// than the size cap in force.
Skipped { path: &'a Path, size: u64, cap: u64 },
@@ -150,6 +157,15 @@ pub struct Workspace {
includes: IncludeGraph,
/// The last `lucisv.*` settings a client pushed. Default until it does.
client: ClientSettings,
/// What previous sessions' scans parsed, keyed by content: a file whose
/// bytes are in here is indexed without being parsed again. Re-opened at
/// the start of every whole rescan, because that is when the directory it
/// should live in can have moved (`docs/features/index-persistence`).
cache: IndexCache,
/// `initializationOptions.storagePath`: the per-workspace folder the
/// editor offered for exactly this. One rung of the cache-directory
/// ladder, and the only one the server cannot work out for itself.
storage: Option<PathBuf>,
/// Every directory a buffer has been opened from this session, unraised
/// and deduped. The folder scope is derived from these rather than from
/// the currently-open buffers, so **closing a file never narrows the
@@ -336,10 +352,53 @@ impl Workspace {
|| self.client.max_file_size != settings.max_file_size
|| self.client.index_scope != settings.index_scope
|| self.client.index_scope_depth != settings.index_scope_depth;
// Neither cache setting changes *which files exist*, so neither asks
// for a rescan — but both change where, or whether, the cache writes,
// and the cache in hand was opened under the old ones. Dropping it
// here is what makes `persist: false` take effect at once in both
// directions: nothing more is written, and nothing held is read. The
// next whole rescan opens the store the new settings name.
if self.client.index_persist != settings.index_persist
|| self.client.index_cache_path != settings.index_cache_path
{
self.cache = IndexCache::disabled();
}
self.client = settings;
rescan
}
/// Where the persistent index cache should live, by
/// [`crate::index_cache::cache_dir`]'s ladder — the client's setting, the
/// editor's storage folder, this platform's cache directory, or nowhere.
fn cache_dir(&self) -> Option<PathBuf> {
// In this crate's own tests nothing falls through to the OS cache
// directory: a unit test must not write into the developer's own
// `~/Library/Caches`, and every test that is *about* the cache names
// a directory of its own — a `cachePath` or a `storagePath` — which
// the ladder below still answers with. The OS rung itself is tested
// where it is written, against `index_cache::cache_dir` directly.
#[cfg(test)]
if self.client.index_cache_path.is_none() && self.storage.is_none() {
return None;
}
crate::index_cache::cache_dir(
&self.client,
self.storage.as_deref(),
&self.roots,
self.filelist_path().as_deref(),
)
}
/// Adopt `initializationOptions.storagePath` — the folder the editor set
/// aside for this workspace's server state.
///
/// Called once, before the first index build, because it is one rung of
/// the ladder that decides where the cache is read from. A client that
/// sends nothing leaves the OS cache directory to decide.
pub fn set_storage_path(&mut self, storage: Option<PathBuf>) {
self.storage = storage;
}
pub fn document(&self, uri: &Uri) -> Option<&Document> {
self.docs.get(uri)
}
@@ -404,12 +463,35 @@ impl Workspace {
let ordered =
self.open_first(index_order(sources.iter().map(|(p, t)| (p.clone(), t.as_str()))));
let total = ordered.len();
// Re-opened here rather than held across rescans: the directory it
// belongs in depends on settings that arrive after startup, and a
// second session over the same workspace may have written records
// this one has not seen.
self.cache = IndexCache::open(self.cache_dir());
let mut builder = IndexBuilder::new();
for (done, (path, text)) in ordered.into_iter().enumerate() {
watch(IndexEvent::Parsing { done, total, path: &path });
builder.add_file(path, text);
// The cache answers for the exact bytes about to be indexed, so a
// hit is the parse and not a guess at it. A miss — a new file, a
// changed one, a record this version cannot read — parses, and
// the result is written through immediately, which is what makes
// an interrupted scan resumable.
match self.cache.facts_for(&path, text) {
Some(facts) => {
watch(IndexEvent::Cached { done, total, path: &path });
builder.add_facts(facts);
}
None => {
watch(IndexEvent::Parsing { done, total, path: &path });
let facts = FileFacts::of(path, text);
self.cache.record(&facts, text);
builder.add_facts(facts);
}
}
}
self.index = builder.finish();
// The one moment the live set of entries is known, so the one moment
// the append log is worth rewriting.
self.cache.compact();
// Built here, from the same list, so a file the scope ladder excluded
// contributes no completion candidates either.
self.candidates = Candidates::build(&self.index, &sources);
@@ -457,6 +539,15 @@ impl Workspace {
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());
// Written through here too, so an hour of saves is an hour of
// work the next session does not repeat. The record is the
// one the update just made — no second parse — and it is
// keyed by the text it was made from, which is the buffer's
// when a buffer beat disk. That record is simply never hit
// again if the file on disk says something else.
if let Some(facts) = self.index.facts_for(path) {
self.cache.record(facts, &text);
}
}
None => {
self.index.remove_file(path);
@@ -2206,4 +2297,483 @@ mod tests {
"and with nothing to clamp against the climb stops at the filesystem root"
);
}
// ------------------------------------------------------------------
// the persistent index cache (docs/features/index-persistence)
// ------------------------------------------------------------------
/// A client that keeps its index cache in `dir`.
fn caching(dir: &Path) -> ClientSettings {
ClientSettings {
index_cache_path: Some(dir.to_string_lossy().into_owned()),
..Default::default()
}
}
/// What one whole scan did, file by file: what it parsed, and what it
/// took from the cache instead. The two together are the work list.
#[derive(Debug, Default, PartialEq, Eq)]
struct Scan {
parsed: Vec<String>,
cached: Vec<String>,
}
/// Scan `roots` (or rescan what is already open, with `None`) and record
/// which files were parsed and which came out of the cache.
fn scan(ws: &mut Workspace, roots: Option<Vec<PathBuf>>) -> Scan {
let mut out = Scan::default();
{
let mut see = |event: IndexEvent| match event {
IndexEvent::Parsing { path, .. } => out.parsed.push(file_name(path)),
IndexEvent::Cached { path, .. } => out.cached.push(file_name(path)),
IndexEvent::Skipped { .. } => {}
};
match roots {
Some(roots) => ws.open_whole_workspace_with(roots, &mut see),
None => ws.rebuild_index_with(&mut see),
};
}
out
}
fn file_name(path: &Path) -> String {
path.file_name().expect("a file").to_string_lossy().into_owned()
}
/// A workspace that keeps its cache in `store` and indexes every root.
fn cached_workspace(store: &Path) -> Workspace {
let mut ws = Workspace::default();
ws.set_client_settings(wide(caching(store)));
ws
}
#[test]
fn a_second_session_over_the_same_store_parses_nothing_it_parsed_before() {
let tree = Tree::new("cachewarm");
tree.package("a.sv", "a_pkg");
tree.package("b.sv", "b_pkg");
let store = Tree::new("cachewarm_store");
let mut cold = cached_workspace(&store.path);
let first = scan(&mut cold, Some(vec![tree.path.clone()]));
assert_eq!(first.parsed, ["a.sv", "b.sv"], "a cold scan parses everything");
assert!(first.cached.is_empty(), "{first:?}");
let fingerprint = cold.index().fingerprint();
// A whole new server over the same tree and the same store — which is
// what reopening the editor is.
let mut warm = cached_workspace(&store.path);
let second = scan(&mut warm, Some(vec![tree.path.clone()]));
assert!(second.parsed.is_empty(), "a warm scan parses nothing: {second:?}");
assert_eq!(second.cached, ["a.sv", "b.sv"]);
assert_eq!(
warm.index().fingerprint(),
fingerprint,
"and the index it built is the index the parses built"
);
}
#[test]
fn a_half_warm_scan_parses_exactly_what_the_store_cannot_answer_for() {
// The resume case, which is the whole feature: a store holding some
// of the workspace — because the last session was killed halfway, or
// because files have changed since — costs exactly the files it does
// not answer for, and nothing else.
let tree = Tree::new("cachehalf");
tree.package("a.sv", "a_pkg");
tree.package("b.sv", "b_pkg");
let store = Tree::new("cachehalf_store");
let mut first = cached_workspace(&store.path);
scan(&mut first, Some(vec![tree.path.clone()]));
tree.package("b.sv", "b_renamed_pkg"); // changed since
tree.package("c.sv", "c_pkg"); // never seen
let mut second = cached_workspace(&store.path);
let half = scan(&mut second, Some(vec![tree.path.clone()]));
assert_eq!(half.cached, ["a.sv"], "only the untouched file: {half:?}");
assert_eq!(half.parsed, ["b.sv", "c.sv"]);
let mut fresh = Workspace::default();
fresh.set_client_settings(wide(ClientSettings::default()));
fresh.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(
second.index().fingerprint(),
fresh.index().fingerprint(),
"a half-cached index is the index a cacheless scan would have built"
);
}
#[test]
fn the_key_is_the_content_and_only_the_content() {
// Both directions of "no timestamp is trusted": a file rewritten with
// the same bytes still hits (its modification time moved and nothing
// else did), and a file rewritten with *different* bytes of the same
// length misses. A cache keyed on size and mtime would get both of
// these exactly the wrong way round.
let tree = Tree::new("cachekey");
tree.write("a.sv", "package a_pkg;\n localparam K = 1;\nendpackage\n");
let store = Tree::new("cachekey_store");
let mut ws = cached_workspace(&store.path);
scan(&mut ws, Some(vec![tree.path.clone()]));
tree.write("a.sv", "package a_pkg;\n localparam K = 1;\nendpackage\n");
let touched = scan(&mut ws, None);
assert_eq!(touched.cached, ["a.sv"], "the same bytes are the same file: {touched:?}");
tree.write("a.sv", "package a_pkg;\n localparam K = 2;\nendpackage\n");
let changed = scan(&mut ws, None);
assert_eq!(changed.parsed, ["a.sv"], "one byte of difference is a miss: {changed:?}");
}
#[test]
fn the_cache_never_puts_back_a_file_the_scan_no_longer_visits() {
// A record is not a file. The scope ladder decides what is walked;
// the cache only ever answers *for* something already on the work
// list, so a session whose scope has narrowed has an index that
// narrowed with it, records or no records.
let tree = Tree::new("cachescope");
tree.package("rtl/a.sv", "a_pkg");
tree.package("tb/b.sv", "b_pkg");
let store = Tree::new("cachescope_store");
let mut wide_session = cached_workspace(&store.path);
scan(&mut wide_session, Some(vec![tree.path.clone()]));
assert_eq!(indexed(&wide_session, &["a_pkg", "b_pkg"]), ["a_pkg", "b_pkg"]);
// The next session is folder-scoped and only ever opens a file in
// `rtl/`, so `tb/` is not walked at all.
let mut narrow = Workspace::default();
narrow.set_client_settings(caching(&store.path));
narrow.open_roots_with(vec![tree.path.clone()], &mut |_| {});
open(&mut narrow, &tree, "rtl/a.sv");
let narrowed = scan(&mut narrow, None);
assert_eq!(narrowed.cached, ["a.sv"], "{narrowed:?}");
assert_eq!(
indexed(&narrow, &["a_pkg", "b_pkg"]),
["a_pkg"],
"the record for tb/b.sv exists and is still not an indexed file"
);
}
#[test]
fn persistence_off_reads_nothing_and_writes_nothing() {
let tree = Tree::new("cacheoff");
tree.package("a.sv", "a_pkg");
let store = Tree::new("cacheoff_store");
// Nothing is written while it is off…
let mut off = Workspace::default();
off.set_client_settings(wide(ClientSettings {
index_persist: false,
..caching(&store.path)
}));
scan(&mut off, Some(vec![tree.path.clone()]));
assert!(!store.path.join("index-cache").exists(), "persist: false must not write");
// …and a store that already exists is not read when it goes off.
let mut on = cached_workspace(&store.path);
scan(&mut on, Some(vec![tree.path.clone()]));
assert!(store.path.join("index-cache").exists(), "premise: a store to ignore");
let mut ignoring = Workspace::default();
ignoring.set_client_settings(wide(ClientSettings {
index_persist: false,
..caching(&store.path)
}));
let scanned = scan(&mut ignoring, Some(vec![tree.path.clone()]));
assert_eq!(scanned.parsed, ["a.sv"], "persist: false must not read: {scanned:?}");
}
#[test]
fn turning_persistence_off_mid_session_stops_the_write_through_at_once() {
// A save takes the incremental path, which writes its record through
// without any rescan — so `persist: false` has to reach it the moment
// it lands, not at the next scan.
let tree = Tree::new("cachemidsession");
tree.package("a.sv", "a_pkg");
let store = Tree::new("cachemidsession_store");
let mut ws = cached_workspace(&store.path);
scan(&mut ws, Some(vec![tree.path.clone()]));
tree.package("a.sv", "a_pkg_v2");
assert!(ws.update_one(&tree.path.join("a.sv")), "premise: the fast path took it");
let after_save = fs::read_to_string(store.path.join("index-cache")).expect("a store");
assert!(after_save.contains("a_pkg_v2"), "a save writes its record through");
ws.set_client_settings(wide(ClientSettings {
index_persist: false,
..caching(&store.path)
}));
tree.package("a.sv", "a_pkg_v3");
assert!(ws.update_one(&tree.path.join("a.sv")));
let after_off = fs::read_to_string(store.path.join("index-cache")).expect("a store");
assert_eq!(after_off, after_save, "nothing more is written once it is off");
}
/// QA (2026-08-27), the no-mtime deviation's save-path half: the
/// write-through on `update_one` must key its record on the *buffer's*
/// bytes, never on what happens to be on disk — that is the argument the
/// README gives for why a stored `(size, mtime)` would have been unsound
/// (a save's text can come from an unsaved buffer). Constructed
/// directly: open a buffer whose text disagrees with the file on disk,
/// let the incremental path write its record through, and check the
/// store's record is keyed by the *buffer's* hash and holds the
/// *buffer's* facts — and that disk's actual bytes, hashed, do not
/// match what got written.
#[test]
fn a_saved_buffers_record_is_keyed_and_filled_from_the_buffer_not_stale_disk() {
let tree = Tree::new("cachebuffer");
tree.package("a.sv", "a_pkg_on_disk");
let store = Tree::new("cachebuffer_store");
let mut ws = cached_workspace(&store.path);
scan(&mut ws, Some(vec![tree.path.clone()]));
// The buffer disagrees with disk — as it does the moment a user
// types, before the editor's next `didSave` reaches disk at all.
let path = tree.path.join("a.sv");
let buffer_text = "package a_pkg_in_buffer;\n localparam K = 1;\nendpackage\n";
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, buffer_text.to_string());
assert!(ws.update_one(&path), "premise: the fast path took it");
// The append log still holds the earlier, disk-keyed line too — it is
// not rewritten until the next whole-scan compaction — so the write
// itself is checked by what it added, and the *effective* record
// (what `open` resolves a repeated path to: the last line wins) is
// checked separately below, which is the property that actually
// matters for correctness.
let store_text = fs::read_to_string(store.path.join("index-cache")).expect("a store");
assert!(
store_text.contains("a_pkg_in_buffer"),
"the write-through must have appended the buffer's facts: {store_text}"
);
let buffer_hash = lucisv_core::cache::content_hash(buffer_text.as_bytes());
assert!(
store_text.contains(&format!("{buffer_hash:016x}")),
"the appended record's key is the buffer's content hash: {store_text}"
);
let disk_text = fs::read_to_string(&path).expect("disk");
let disk_hash = lucisv_core::cache::content_hash(disk_text.as_bytes());
assert_ne!(disk_hash, buffer_hash, "premise: disk and buffer really do disagree");
let reopened = IndexCache::open(Some(store.path.clone()));
assert_eq!(
reopened.facts_for(&path, buffer_text),
Some(FileFacts::of(path.clone(), buffer_text)),
"the record a fresh session resolves to is the buffer's, not disk's stale one"
);
assert!(
reopened.facts_for(&path, &disk_text).is_none(),
"disk's own current bytes must not hit — no record was ever keyed on them"
);
}
#[test]
fn a_configured_cache_path_beats_the_editors_storage_folder() {
// Rung 1 over rung 2 of `index_cache::cache_dir`'s ladder, through
// the workspace rather than against the function: the store lands
// where the *setting* says, and the editor's folder is left alone.
let tree = Tree::new("cacheladder");
tree.package("a.sv", "a_pkg");
let storage = Tree::new("cacheladder_storage");
let configured = Tree::new("cacheladder_configured");
let mut ws = Workspace::default();
ws.set_storage_path(Some(storage.path.clone()));
ws.set_client_settings(wide(caching(&configured.path)));
scan(&mut ws, Some(vec![tree.path.clone()]));
assert!(configured.path.join("index-cache").exists(), "the setting won");
assert!(!storage.path.join("index-cache").exists(), "the editor's folder is untouched");
// Unset it and the editor's folder is what is left standing — on the
// next scan, which is when the store is re-opened.
ws.set_client_settings(wide(ClientSettings::default()));
ws.set_storage_path(Some(storage.path.clone()));
scan(&mut ws, None);
assert!(storage.path.join("index-cache").exists(), "and now the editor's folder");
}
#[test]
fn a_storage_folder_that_does_not_exist_yet_is_made_on_demand() {
// What VS Code hands over: `context.storageUri` names a folder the
// editor has not necessarily created.
let tree = Tree::new("cachemkdir");
tree.package("a.sv", "a_pkg");
let storage = Tree::new("cachemkdir_storage");
let nested = storage.path.join("deep/inner");
let mut ws = Workspace::default();
ws.set_storage_path(Some(nested.clone()));
ws.set_client_settings(wide(ClientSettings::default()));
scan(&mut ws, Some(vec![tree.path.clone()]));
assert!(nested.join("index-cache").exists(), "made on demand");
let mut warm = Workspace::default();
warm.set_storage_path(Some(nested));
warm.set_client_settings(wide(ClientSettings::default()));
let second = scan(&mut warm, Some(vec![tree.path.clone()]));
assert_eq!(second.cached, ["a.sv"], "{second:?}");
}
#[test]
fn the_cached_index_is_the_index_a_fresh_scan_would_have_built_over_the_corpus() {
// The paranoid sweep, against the real corpus: every file in, every
// file out of the cache, and the two indexes compared observable by
// observable through the fingerprint.
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let store = Tree::new("cachecorpus_store");
let mut cold = cached_workspace(&store.path);
let first = scan(&mut cold, Some(vec![corpus.clone()]));
assert!(first.parsed.len() > 500, "premise: the corpus was really scanned");
assert!(first.cached.is_empty());
let mut warm = cached_workspace(&store.path);
let second = scan(&mut warm, Some(vec![corpus]));
assert_eq!(second.cached.len(), first.parsed.len(), "every file came back");
assert!(second.parsed.is_empty(), "and none was parsed again");
assert_eq!(
warm.index().fingerprint(),
cold.index().fingerprint(),
"the cached index is the parsed index, file ids and all"
);
assert_eq!(warm.index().counts(), cold.index().counts());
// The completion tables and the include graph are built from the
// files' text either way, so they cannot drift — pinned rather than
// assumed, since the cache is the one thing that skips a file's parse.
assert_eq!(warm.candidates().words(""), cold.candidates().words(""));
}
/// QA (2026-08-27), attack surface 1/4, fixed 2026-08-27: the negative
/// control the equivalence sweep above cannot run on its own, through the
/// whole workspace rather than the store. A record used to be verified
/// only against the *file's* content hash, so a line whose hash matched
/// `a.sv`'s real bytes but whose facts were altered was a hit and the
/// index it produced silently diverged from what a fresh parse gives.
/// Every record now carries a checksum of its own facts, so the damaged
/// line is dropped: the file is parsed, the scan reports it as parsed
/// rather than cached, and the fingerprint is exactly a fresh scan's.
/// That is `docs/features/index-persistence`'s "a performance artifact
/// and never a correctness input" holding against *accidental* damage of
/// any shape; a store deliberately reforged is out of the threat model
/// and pinned as such in `index_cache.rs`.
#[test]
fn a_poisoned_cache_record_is_dropped_and_the_index_is_a_fresh_scans() {
let tree = Tree::new("poisonfingerprint");
tree.package("a.sv", "a_pkg");
let store = Tree::new("poisonfingerprint_store");
let mut cold = cached_workspace(&store.path);
scan(&mut cold, Some(vec![tree.path.clone()]));
let honest = cold.index().fingerprint();
// Hand-tamper the store on disk: keep the header, the hash of `a.sv`'s
// *real* bytes and the checksum the genuine record was written with,
// but swap in facts a parse of those bytes never produced (a different
// package name entirely) — which is what every accidental way a
// written record can change looks like from the reader's side.
let store_file = store.path.join("index-cache");
let text = fs::read_to_string(&store_file).expect("a store");
let header_line = text.lines().next().expect("header").to_string();
let record = text.lines().nth(1).expect("a record").to_string();
let checksum = record.rsplit('\t').next().expect("a checksum field");
let real_text = "package a_pkg;\n localparam K = 1;\nendpackage\n";
let hash = lucisv_core::cache::content_hash(real_text.as_bytes());
let evil = FileFacts::of(
tree.path.join("a.sv"),
"package poisoned_pkg;\n localparam K = 999;\nendpackage\n",
);
let poisoned = format!(
"{header_line}\n{hash:016x}\t{}\t{checksum}\n",
evil.encode().expect("encodes")
);
fs::write(&store_file, poisoned).expect("write");
let mut warm = cached_workspace(&store.path);
let scanned = scan(&mut warm, Some(vec![tree.path.clone()]));
assert_eq!(scanned.parsed, ["a.sv"], "the tampered record is dropped: {scanned:?}");
assert!(scanned.cached.is_empty(), "and it is not served: {scanned:?}");
assert_eq!(
warm.index().fingerprint(),
honest,
"a record whose facts no longer match their checksum cannot reach the index, so \
the equivalence sweep's own claim holds against damage as well as staleness"
);
}
/// The measurement behind the README's numbers: a scan with no cache at
/// all, a cold one that fills the store, a warm one that reads it, and a
/// half-warm one with a single file changed.
#[test]
#[ignore = "measurement, not a test"]
fn qa_perf_cold_warm_and_half_warm_scans() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let store = Tree::new("cacheperf_store");
let timed = |ws: &mut Workspace| {
let started = std::time::Instant::now();
let scanned = scan(ws, None);
(started.elapsed(), scanned)
};
// The baseline: what a rescan cost before this feature existed.
let mut off = Workspace::default();
off.set_client_settings(wide(ClientSettings {
index_persist: false,
..caching(&store.path)
}));
scan(&mut off, Some(vec![corpus.clone()]));
let (cacheless, _) = timed(&mut off);
let mut ws = cached_workspace(&store.path);
let started = std::time::Instant::now();
let cold_scan = scan(&mut ws, Some(vec![corpus.clone()]));
let cold = started.elapsed();
let (warm, warm_scan) = timed(&mut ws);
// Half-warm: the store answers for every file but the one edited.
let one = ws.index().files()[0].clone();
let text = fs::read_to_string(&one).expect("read");
fs::write(&one, format!("{text}\n// edited\n")).expect("write");
let (half, half_scan) = timed(&mut ws);
fs::write(&one, &text).expect("restore");
let files = ws.index().files().len();
eprintln!(
"{files} files: no cache {cacheless:?}; cold {cold:?} ({} parsed); \
warm {warm:?} ({} cached); half-warm {half:?} ({} parsed, {} cached) — \
warm is {:.2}x the cacheless scan",
cold_scan.parsed.len(),
warm_scan.cached.len(),
half_scan.parsed.len(),
half_scan.cached.len(),
cacheless.as_secs_f64() / warm.as_secs_f64().max(f64::MIN_POSITIVE)
);
let store_size = fs::metadata(store.path.join("index-cache")).expect("a store").len();
eprintln!("store: {store_size} bytes for {files} files");
// What the key costs, which is the whole argument for keying on
// content rather than on a timestamp: the text is read on every scan
// anyway (the completion tables and the include graph are built from
// it), so the alternative would only ever have saved this.
let texts: Vec<String> =
ws.index().files().iter().filter_map(|path| fs::read_to_string(path).ok()).collect();
let bytes: usize = texts.iter().map(String::len).sum();
let started = std::time::Instant::now();
let mut sink = 0u64;
for text in &texts {
sink ^= lucisv_core::cache::content_hash(text.as_bytes());
}
eprintln!("hashing {bytes} bytes of {files} files: {:?} ({sink:016x})", started.elapsed());
}
}
+110 -2
View File
@@ -61,6 +61,27 @@ fn read_message(input: &mut impl BufRead) -> Option<serde_json::Value> {
serde_json::from_slice(&body).ok()
}
/// The server binary, with its OS cache directory pointed somewhere a test
/// may write.
///
/// Without a client-supplied `storagePath` the persistent index cache falls
/// back to this platform's cache directory
/// (`docs/features/index-persistence/README.md`), and the developer's own
/// `~/Library/Caches` is not somewhere a test run may leave anything. The
/// three variables below are the ones that decide it on the three platforms.
/// A test whose subject *is* the cache passes a `storagePath` of its own,
/// which outranks all of them.
fn server_command() -> Command {
let sandbox =
std::env::temp_dir().join(format!("lucisv_server_e2e_home_{}", std::process::id()));
let mut command = Command::new(env!("CARGO_BIN_EXE_lucisv-server"));
command
.env("HOME", &sandbox)
.env("XDG_CACHE_HOME", sandbox.join("cache"))
.env("LOCALAPPDATA", sandbox.join("cache"));
command
}
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("lucisv_server_e2e_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
@@ -74,7 +95,7 @@ fn temp_dir(name: &str) -> PathBuf {
/// processes the messages in order and exits on `exit`, so stdout closes and
/// the read terminates on its own.
fn talk(session: &str) -> Vec<serde_json::Value> {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server"))
let mut child = server_command()
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
@@ -2167,7 +2188,7 @@ struct Live {
impl Live {
fn start() -> Live {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server"))
let mut child = server_command()
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
@@ -4374,3 +4395,90 @@ fn a_save_of_one_file_updates_the_index_over_the_wire() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_second_session_over_the_same_storage_path_indexes_from_the_cache() {
// The owner's case on the wire, with the real binary: one session indexes
// a workspace and writes what it learned into the folder the client named
// in `initializationOptions.storagePath`; a second session over the same
// folder gets the same index without parsing a file
// (docs/features/index-persistence/README.md).
let dir = temp_dir("persist");
let storage = temp_dir("persist_storage");
std::fs::write(dir.join("a.sv"), "module a;\nendmodule\n").expect("write");
std::fs::write(dir.join("b.sv"), "module b;\nendmodule\n").expect("write");
let root = format!("file://{}", dir.display());
let session = || {
[
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","initializationOptions":{{"storagePath":{}}},"capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"#,
serde_json::to_string(&storage.display().to_string()).expect("json")
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
// The scope push is what makes the workspace really get walked;
// it also rescans, which is the scan these assertions are about.
frame(WIDE_SCOPE),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat()
};
/// Every `window/logMessage` line of a transcript.
fn log_lines(messages: &[serde_json::Value]) -> Vec<String> {
messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.filter_map(|m| m["params"]["message"].as_str().map(str::to_string))
.collect()
}
/// Every progress `end` message of a transcript.
fn ends(messages: &[serde_json::Value]) -> Vec<String> {
messages
.iter()
.filter(|m| m["params"]["value"]["kind"] == "end")
.filter_map(|m| m["params"]["value"]["message"].as_str().map(str::to_string))
.collect()
}
let cold = talk(&session());
assert_eq!(ends(&cold), ["0 files indexed", "2 files indexed"], "{cold:#?}");
let parsed: Vec<String> =
log_lines(&cold).into_iter().filter(|l| l.starts_with("indexing: ")).collect();
assert_eq!(parsed.len(), 2, "the first session parses both files: {parsed:?}");
assert!(
storage.join("index-cache").exists(),
"and writes what it found where the client said: {}",
storage.display()
);
let warm = talk(&session());
assert_eq!(
ends(&warm),
["0 files indexed", "2 files indexed, 2 from cache"],
"the second session's bar says where its files came from: {warm:#?}"
);
let lines = log_lines(&warm);
assert_eq!(
lines.iter().filter(|l| l.starts_with("cached: ")).count(),
2,
"and its log names them one by one: {lines:?}"
);
assert!(
!lines.iter().any(|l| l.starts_with("indexing: ")),
"with nothing parsed at all: {lines:?}"
);
// A file changed between sessions is the only thing the third one parses.
std::fs::write(dir.join("b.sv"), "module b_renamed;\nendmodule\n").expect("write");
let half = talk(&session());
let lines = log_lines(&half);
assert_eq!(lines.iter().filter(|l| l.starts_with("cached: ")).count(), 1, "{lines:?}");
assert_eq!(lines.iter().filter(|l| l.starts_with("indexing: ")).count(), 1, "{lines:?}");
assert_eq!(ends(&half), ["0 files indexed", "2 files indexed, 1 from cache"], "{half:#?}");
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&storage);
}
+432
View File
@@ -0,0 +1,432 @@
//! [`FileFacts`] as one line of text: the format the index cache stores a
//! parse's result in, and reads it back from.
//!
//! Hand-rolled, because the alternative is a serialization dependency in a
//! crate that has one dependency and it is the parser. The shape is the one
//! `lucisv_core::cache` established for the formatter's store — tab-separated
//! fields on one line, so a torn write is a line without a newline and a
//! record that does not parse is a record that is dropped — with lists
//! length-prefixed rather than nested, so reading a record is one pass over a
//! flat token stream and nothing is ambiguous.
//!
//! **Anything that changes what a record holds, or how it is written, bumps
//! [`FACTS_FORMAT`].** A record written by another format is not read at all;
//! see `docs/features/index-persistence/README.md` for why the cache would
//! rather redo the work than guess.
use std::path::PathBuf;
use vlog_parser::defines::{Define, DefineKind, DefineTable};
use vlog_parser::span::TextRange;
use crate::model::SymbolKind;
use crate::workspace::{Decl, DeclSite, FileFacts, 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;
impl FileFacts {
/// These facts as one line's worth of fields, tab-separated.
///
/// `None` for a path that cannot be written on a line of text — not UTF-8,
/// or holding a tab or a newline. Such a file is simply never cached, the
/// same answer `lucisv_core::cache` gives for the same shape of path.
/// Every *other* string a record holds is escaped instead, because a macro
/// body really can contain a tab.
pub fn encode(&self) -> Option<String> {
let path = self.path.to_str()?;
let mut out = Writer::default();
out.text(path);
out.tag("D", self.defines.entries().len());
for define in self.defines.entries() {
out.define(define);
}
out.tag("U", self.units.len());
for decl in &self.units {
out.decl(decl);
}
out.tag("M", self.members.len());
for (unit, decl) in &self.members {
out.text(unit);
out.decl(decl);
}
out.tag("I", self.instantiations.len());
for (module, site) in &self.instantiations {
out.text(module);
out.site(&site.owner);
out.range(site.site_span);
}
out.tag("S", self.subclasses.len());
for (base, subclass) in &self.subclasses {
out.text(base);
out.site(subclass);
}
Some(out.out)
}
/// The facts a record describes, or `None` for anything that is not
/// exactly one whole record of this format.
///
/// Strict on purpose, in both directions: a field missing, a number that
/// does not parse, a kind this version has no name for, a count that
/// outruns the line, **or a field left over at the end** all mean the same
/// thing — this is not a record this version wrote, so nothing is taken
/// from it. A dropped record costs one file's parse; a half-read one would
/// cost correctness.
pub fn decode(line: &str) -> Option<FileFacts> {
let mut input = Reader::new(line);
let path = PathBuf::from(input.text()?);
let mut defines = Vec::new();
for _ in 0..input.tag("D")? {
defines.push(input.define()?);
}
let mut units = Vec::new();
for _ in 0..input.tag("U")? {
units.push(input.decl()?);
}
let mut members = Vec::new();
for _ in 0..input.tag("M")? {
members.push((input.text()?, input.decl()?));
}
let mut instantiations = Vec::new();
for _ in 0..input.tag("I")? {
let module = input.text()?;
let owner = input.site()?;
instantiations.push((module, SiteFact { owner, site_span: input.range()? }));
}
let mut subclasses = Vec::new();
for _ in 0..input.tag("S")? {
subclasses.push((input.text()?, input.site()?));
}
if !input.done() {
return None;
}
Some(FileFacts {
path,
defines: DefineTable::from_entries(defines),
units,
members,
instantiations,
subclasses,
})
}
}
/// The path a record is for, without decoding the rest of it.
///
/// A store keyed by path has to read this out of every record it holds, and
/// only ever decodes the handful it is asked for — so the cheap half of the
/// format is public separately from [`FileFacts::decode`]. `None` for a record
/// whose first field is not a readable path, which is a record that would not
/// decode either.
pub fn record_path(record: &str) -> Option<PathBuf> {
let field = record.split('\t').next()?;
Some(PathBuf::from(unescape(field)?))
}
/// A record under construction: fields pushed in order, separated by tabs.
#[derive(Default)]
struct Writer {
out: String,
/// Whether a field has been written yet, so the separator goes *between*
/// fields — asked of a flag rather than of `out.is_empty()`, which would
/// be wrong for a first field that is itself empty.
written: bool,
}
impl Writer {
/// One string field, escaped.
fn text(&mut self, text: &str) {
self.field();
for ch in text.chars() {
match ch {
'\\' => self.out.push_str("\\\\"),
'\t' => self.out.push_str("\\t"),
'\n' => self.out.push_str("\\n"),
'\r' => self.out.push_str("\\r"),
_ => self.out.push(ch),
}
}
}
/// One number field.
fn num(&mut self, n: u32) {
self.field();
self.out.push_str(&n.to_string());
}
/// A list's marker and its length — the length prefix that makes the
/// stream flat and still unambiguous.
fn tag(&mut self, tag: &str, len: usize) {
self.field();
self.out.push_str(tag);
self.num(len as u32);
}
fn range(&mut self, range: TextRange) {
self.num(range.start);
self.num(range.end);
}
fn decl(&mut self, decl: &Decl) {
self.text(&decl.name);
self.field();
self.out.push_str(kind_name(decl.kind));
self.range(decl.name_span);
}
fn site(&mut self, site: &DeclSite) {
self.text(&site.name);
self.range(site.name_span);
self.range(site.span);
}
fn define(&mut self, define: &Define) {
self.field();
self.out.push(match define.kind {
DefineKind::Define => 'd',
DefineKind::Undef => 'u',
});
self.text(&define.name);
match &define.params {
// A macro with no parameter list at all is not a macro with an
// empty one — `` `define A x`` against `` `define A() x`` — so the
// two cannot share a spelling.
None => {
self.field();
self.out.push('-');
}
Some(params) => {
self.num(params.len() as u32);
for param in params {
self.text(param);
}
}
}
self.text(&define.body);
self.range(define.span);
self.range(define.name_span);
}
/// The separator before every field but the first.
fn field(&mut self) {
if self.written {
self.out.push('\t');
}
self.written = true;
}
}
/// A record being read, one field at a time.
struct Reader<'a> {
fields: Vec<&'a str>,
at: usize,
}
impl<'a> Reader<'a> {
fn new(line: &'a str) -> Reader<'a> {
Reader { fields: line.split('\t').collect(), at: 0 }
}
fn next(&mut self) -> Option<&'a str> {
let field = self.fields.get(self.at)?;
self.at += 1;
Some(field)
}
/// Whether every field has been read — the check that makes a record with
/// something extra on the end invalid rather than merely surprising.
fn done(&self) -> bool {
self.at == self.fields.len()
}
fn text(&mut self) -> Option<String> {
unescape(self.next()?)
}
fn num(&mut self) -> Option<u32> {
self.next()?.parse().ok()
}
fn range(&mut self) -> Option<TextRange> {
Some(TextRange::new(self.num()?, self.num()?))
}
/// A list's length, once its marker has been confirmed. The marker is what
/// turns a misaligned read into a dropped record instead of a plausible
/// one.
fn tag(&mut self, tag: &str) -> Option<usize> {
if self.next()? != tag {
return None;
}
Some(self.num()? as usize)
}
fn decl(&mut self) -> Option<Decl> {
let name = self.text()?;
let kind = kind_of(self.next()?)?;
Some(Decl { name, name_span: self.range()?, kind })
}
fn site(&mut self) -> Option<DeclSite> {
Some(DeclSite { name: self.text()?, name_span: self.range()?, span: self.range()? })
}
fn define(&mut self) -> Option<Define> {
let kind = match self.next()? {
"d" => DefineKind::Define,
"u" => DefineKind::Undef,
_ => return None,
};
let name = self.text()?;
let params = match self.next()? {
"-" => None,
count => {
let count: u32 = count.parse().ok()?;
let mut params = Vec::new();
for _ in 0..count {
params.push(self.text()?);
}
Some(params)
}
};
Some(Define {
kind,
name,
params,
body: self.text()?,
span: self.range()?,
name_span: self.range()?,
})
}
}
/// One escaped string field, back as it was written. `None` for an escape
/// this format does not write, which is a record it did not write either.
fn unescape(field: &str) -> Option<String> {
let mut out = String::with_capacity(field.len());
let mut chars = field.chars();
while let Some(ch) = chars.next() {
if ch != '\\' {
out.push(ch);
continue;
}
out.push(match chars.next()? {
'\\' => '\\',
't' => '\t',
'n' => '\n',
'r' => '\r',
_ => return None,
});
}
Some(out)
}
/// A [`SymbolKind`]'s name in a record. Written out rather than numbered, so
/// a variant inserted in the middle of the enum cannot silently turn one kind
/// into another — and a name this version does not know drops the record.
fn kind_name(kind: SymbolKind) -> &'static str {
match kind {
SymbolKind::Module => "module",
SymbolKind::Package => "package",
SymbolKind::Port => "port",
SymbolKind::Net => "net",
SymbolKind::Var => "var",
SymbolKind::Param => "param",
SymbolKind::Genvar => "genvar",
SymbolKind::Typedef => "typedef",
SymbolKind::EnumVariant => "enumvariant",
SymbolKind::Function => "function",
SymbolKind::Task => "task",
SymbolKind::TfArg => "tfarg",
SymbolKind::Instance => "instance",
SymbolKind::Block => "block",
SymbolKind::StructMember => "structmember",
SymbolKind::Class => "class",
}
}
/// The inverse of [`kind_name`], total in the other direction: anything else
/// is not a kind this version writes.
fn kind_of(name: &str) -> Option<SymbolKind> {
Some(match name {
"module" => SymbolKind::Module,
"package" => SymbolKind::Package,
"port" => SymbolKind::Port,
"net" => SymbolKind::Net,
"var" => SymbolKind::Var,
"param" => SymbolKind::Param,
"genvar" => SymbolKind::Genvar,
"typedef" => SymbolKind::Typedef,
"enumvariant" => SymbolKind::EnumVariant,
"function" => SymbolKind::Function,
"task" => SymbolKind::Task,
"tfarg" => SymbolKind::TfArg,
"instance" => SymbolKind::Instance,
"block" => SymbolKind::Block,
"structmember" => SymbolKind::StructMember,
"class" => SymbolKind::Class,
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
/// Every kind round-trips, and the two directions are inverses. If a
/// variant is added to `SymbolKind` this fails to compile in `kind_name`
/// first, which is the point of writing both matches out.
#[test]
fn every_symbol_kind_has_a_name_and_only_its_own() {
let kinds = [
SymbolKind::Module,
SymbolKind::Package,
SymbolKind::Port,
SymbolKind::Net,
SymbolKind::Var,
SymbolKind::Param,
SymbolKind::Genvar,
SymbolKind::Typedef,
SymbolKind::EnumVariant,
SymbolKind::Function,
SymbolKind::Task,
SymbolKind::TfArg,
SymbolKind::Instance,
SymbolKind::Block,
SymbolKind::StructMember,
SymbolKind::Class,
];
let mut names: Vec<&str> = kinds.iter().map(|k| kind_name(*k)).collect();
for kind in kinds {
assert_eq!(kind_of(kind_name(kind)), Some(kind));
}
names.sort_unstable();
let before = names.len();
names.dedup();
assert_eq!(names.len(), before, "two kinds share a name: {names:?}");
assert_eq!(kind_of("Module"), None, "the names are exact");
assert_eq!(kind_of(""), None);
}
#[test]
fn every_escape_survives_a_round_trip() {
for text in ["", "plain", "a\tb", "a\nb", "a\\b", "a\\\\tb", "\r\n", "\\", "üñî"] {
let mut out = Writer::default();
out.text(text);
let field = out.out;
assert_eq!(unescape(&field).as_deref(), Some(text), "{text:?}");
assert!(!field.contains('\t'), "a field never holds a raw tab: {field:?}");
assert!(!field.contains('\n'), "nor a newline: {field:?}");
}
}
#[test]
fn an_escape_this_format_does_not_write_is_not_read() {
assert_eq!(unescape("a\\qb"), None);
assert_eq!(unescape("trailing\\"), None);
}
}
+4 -2
View File
@@ -18,20 +18,22 @@
mod bind;
pub mod classes;
mod facts;
pub mod instantiations;
mod model;
mod resolve;
mod scan;
mod workspace;
pub use facts::{record_path, FACTS_FORMAT};
pub use model::{
DocumentSymbol, Import, Reference, ReferenceId, Resolution, Scope, ScopeId, ScopeKind, Symbol,
SymbolId, SymbolKind,
};
pub use workspace::{
index_order, resolve_external, DeclSite, Def, Definition, ExternalResolutions, ExternalTarget,
FileId, IndexBuilder, IndexCounts, InheritanceEdge, InstantiationEdge, WorkspaceIndex,
WorkspaceSymbol,
FileFacts, FileId, IndexBuilder, IndexCounts, InheritanceEdge, InstantiationEdge,
WorkspaceIndex, WorkspaceSymbol,
};
use std::collections::HashMap;
+61 -19
View File
@@ -200,6 +200,17 @@ impl WorkspaceIndex {
self.subclasses.iter().map(|(name, edges)| (name.as_str(), edges.as_slice()))
}
/// What one file contributes to this index, by path.
///
/// The unmerged record — everything the file's parse found. Public so a
/// caller that persists those records can store the one an incremental
/// update just produced without parsing the file a second time
/// (`docs/features/index-persistence/README.md`).
pub fn facts_for(&self, path: &Path) -> Option<&FileFacts> {
let at = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)).ok()?;
self.facts.get(at)
}
/// The `` `define`` table of one file.
pub fn defines(&self, file: FileId) -> Option<&DefineTable> {
self.facts.get(file.0 as usize).map(|facts| &facts.defines)
@@ -493,11 +504,11 @@ impl Affected {
/// One declaration as a single file contributes it, before that file has a
/// [`FileId`]. The id depends on where the file's path sorts among all of
/// them, which is not known until [`IndexBuilder::finish`].
#[derive(Debug, Clone)]
struct Decl {
name: String,
name_span: TextRange,
kind: SymbolKind,
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Decl {
pub(crate) name: String,
pub(crate) name_span: TextRange,
pub(crate) kind: SymbolKind,
}
impl Decl {
@@ -512,10 +523,10 @@ impl Decl {
/// One instantiation site as a single file contributes it — an
/// [`InstantiationEdge`] without its [`FileId`].
#[derive(Debug, Clone)]
struct SiteFact {
owner: DeclSite,
site_span: TextRange,
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SiteFact {
pub(crate) owner: DeclSite,
pub(crate) site_span: TextRange,
}
/// Everything one file contributes to an index: read while the file is parsed,
@@ -523,22 +534,40 @@ struct SiteFact {
///
/// This is the same data the finished index holds, kept per file rather than
/// merged, which is what lets the merge happen in an order the caller does not
/// choose.
#[derive(Debug, Clone)]
struct FileFacts {
path: PathBuf,
defines: DefineTable,
/// choose — and, since it is *everything* one file contributes, the one thing
/// worth storing between two sessions. [`FileFacts::encode`] and
/// [`FileFacts::decode`] are that store's format; a decoded record put back
/// through [`IndexBuilder::add_facts`] gives the index the file's parse would
/// have, without the parse (`docs/features/index-persistence/README.md`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileFacts {
pub(crate) path: PathBuf,
pub(crate) defines: DefineTable,
/// File-scope declarations, in declaration order.
units: Vec<Decl>,
pub(crate) units: Vec<Decl>,
/// Members, each under the name of the unit that exports it, in the order
/// the scope tree yields them.
members: Vec<(String, Decl)>,
pub(crate) members: Vec<(String, Decl)>,
/// Instantiation sites, each under the name of the module instantiated, in
/// walk order.
instantiations: Vec<(String, SiteFact)>,
pub(crate) instantiations: Vec<(String, SiteFact)>,
/// Class declarations with a base, each under the base's name, in walk
/// order.
subclasses: Vec<(String, DeclSite)>,
pub(crate) subclasses: Vec<(String, DeclSite)>,
}
impl FileFacts {
/// Read off what one file contributes to an index — the parse
/// [`IndexBuilder::add_file`] does, exposed so a caller that stores the
/// result can do the parse itself exactly once.
pub fn of(path: PathBuf, src: &str) -> FileFacts {
facts_of(path, src)
}
/// The file these facts were read from.
pub fn path(&self) -> &Path {
&self.path
}
}
/// Parse one file and read off what it declares and what it points at.
@@ -690,7 +719,20 @@ impl IndexBuilder {
/// The parse happens here, not in `finish`, so a caller reporting progress
/// between calls is reporting work that has really been done.
pub fn add_file(&mut self, path: PathBuf, src: &str) {
self.files.push(facts_of(path, src));
self.add_facts(FileFacts::of(path, src));
}
/// Add one file whose facts are already known — restored from a cache
/// rather than read from the file's text.
///
/// Exactly [`IndexBuilder::add_file`] with the parse already done: the
/// record is what that parse produces, so an index built from records and
/// an index built from text are the same index. Whether the record really
/// describes the file is the caller's business, and the caller answers it
/// by keying its store on the file's content
/// (`docs/features/index-persistence/README.md`).
pub fn add_facts(&mut self, facts: FileFacts) {
self.files.push(facts);
}
/// The finished index: the files sorted by path, then merged.
+149 -2
View File
@@ -4,8 +4,8 @@
use std::path::{Path, PathBuf};
use vlog_parser::parse_source_tolerant;
use vlog_semantic::{
analyze, resolve_external, Def, Definition, ExternalTarget, FileId, Resolution, Semantics,
SymbolKind, WorkspaceIndex,
analyze, resolve_external, Def, Definition, ExternalTarget, FileFacts, FileId, Resolution,
Semantics, SymbolKind, WorkspaceIndex,
};
/// Build an index from `(path, source)` literals, as a server would from disk.
@@ -1455,3 +1455,150 @@ fn same_named_files_in_different_directories_updated_alternately_stay_correct()
"alternating back to the first file"
);
}
// ----------------------------------------------------------------------
// FileFacts as a record: the persistent index cache's format
// ----------------------------------------------------------------------
/// A fixture that exercises every field of a record at once: file-scope
/// units of three kinds, members (including a class nested in a package,
/// which is registered twice), instantiation edges, an inheritance edge,
/// and a `` `define`` table with both an object-like and a function-like
/// macro, an `` `undef``, and a body carrying the characters the format has
/// to escape.
const EVERY_FIELD: &str = concat!(
"`define PLAIN 8\n",
"`define ARGS(a, b = 8) {a, b}\t// a tab and a \\ backslash\n",
"`undef PLAIN\n",
"package p;\n",
" typedef logic [7:0] byte_t;\n",
" class base; endclass\n",
" class derived extends base;\n",
" function void f(); endfunction\n",
" endclass\n",
"endpackage\n",
"typedef int top_t;\n",
"module top;\n",
" sub u_sub ();\n",
" other u_other ();\n",
"endmodule\n",
);
#[test]
fn a_records_every_field_survives_the_round_trip() {
let facts = FileFacts::of(PathBuf::from("/w/every.sv"), EVERY_FIELD);
let line = facts.encode().expect("an ordinary path encodes");
assert!(!line.contains('\n'), "a record is one line: {line}");
let back = FileFacts::decode(&line).expect("what was written reads back");
// `FileFacts` compares every field it holds — path, defines (kind, name,
// params, body, both spans), units, members, instantiation edges,
// inheritance edges — so this is the whole record, not a summary of it.
assert_eq!(back, facts);
assert_eq!(back.encode(), Some(line), "and re-encodes byte for byte");
}
#[test]
fn an_index_built_from_records_is_the_index_the_parse_would_have_given() {
// The claim the cache rests on: facts through the record format and back
// give the same index as the files themselves. Checked over a workspace
// with duplicate names and cross-file edges, by fingerprint — ids,
// disambiguation order, member tables, both edge tables, define counts.
let sources = [
("/w/a.sv", EVERY_FIELD),
("/w/b.sv", "module sub; endmodule\nmodule dup; endmodule\n"),
("/w/c.sv", "`define X 1\nmodule dup;\n sub u ();\nendmodule\n"),
("/w/d.sv", "class late extends base; endclass\n"),
];
let fresh = index(&sources);
let mut builder = vlog_semantic::IndexBuilder::new();
for (path, src) in sources {
let line = FileFacts::of(PathBuf::from(path), src).encode().expect("encodes");
builder.add_facts(FileFacts::decode(&line).expect("decodes"));
}
let restored = builder.finish();
assert_eq!(restored.fingerprint(), fresh.fingerprint());
assert_eq!(restored.counts(), fresh.counts());
}
#[test]
fn a_record_that_is_not_exactly_a_record_decodes_to_nothing() {
let facts = FileFacts::of(PathBuf::from("/w/every.sv"), EVERY_FIELD);
let line = facts.encode().expect("encodes");
let fields: Vec<&str> = line.split('\t').collect();
// Truncation at *every* length, not just at one: a torn write can stop
// anywhere, and every stopping point must be a dropped record rather
// than a plausible one.
for cut in 0..fields.len() {
let truncated = fields[..cut].join("\t");
assert_eq!(
FileFacts::decode(&truncated),
None,
"a record cut to {cut} of {} fields is not a record",
fields.len()
);
}
// And anything left over on the end is not a record either.
assert_eq!(FileFacts::decode(&format!("{line}\textra")), None, "trailing field");
for garbage in [
"",
"garbage",
"\0\0\0",
"/w/a.sv\tD0\tU0\tM0\tI0", // a list marker missing
"/w/a.sv\tD0\tU1\tm\tmodule\t0\t1\tM0\tI0\tS0", // a count that outruns the line
"/w/a.sv\tD0\tU1\tm\tnosuchkind\t0\t1\tM0\tI0\tS0", // a kind no version writes
"/w/a.sv\tD0\tU1\tm\tmodule\tzero\t1\tM0\tI0\tS0", // a number that is not one
"/w/a.sv\tX0\tU0\tM0\tI0\tS0", // the wrong marker
"/w/a\\qb.sv\tD0\tU0\tM0\tI0\tS0", // an escape this format never writes
"/w/a.sv\tD1\td\tM\t-\tbody\t0\t1\t2\tM0\tI0\tS0", // a define's fields cut short
] {
assert_eq!(FileFacts::decode(garbage), None, "{garbage:?} is not a record");
}
}
#[test]
fn a_path_with_a_separator_in_it_is_escaped_like_any_other_string() {
// The path is a string field like the rest, so a tab or a newline in it
// is escaped rather than fatal — the same treatment a macro body gets,
// and it needs it (`EVERY_FIELD` has both).
for path in ["/w/a\tb.sv", "/w/a\nb.sv", "/w/a\\b.sv"] {
let facts = FileFacts::of(PathBuf::from(path), "module m; endmodule\n");
let line = facts.encode().expect("encodes");
assert!(!line.contains('\n'), "still one line: {line}");
assert_eq!(FileFacts::decode(&line).as_ref(), Some(&facts), "{path:?}");
}
}
#[cfg(unix)]
#[test]
fn a_path_that_is_not_utf_8_is_simply_never_cached() {
// The one path shape that has no record: it cannot be written as text at
// all. `None` rather than a lossy spelling — a record whose path is not
// the file's path would be a record that answers for the wrong file.
// Same answer `lucisv_core::cache` gives the same shape of path.
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let path = PathBuf::from(OsStr::from_bytes(b"/w/\xff\xfe.sv"));
assert_eq!(FileFacts::of(path, "module m; endmodule\n").encode(), None);
}
#[test]
fn a_degenerate_file_still_makes_a_record() {
// The shapes `an_update_survives_every_degenerate_file_there_is` covers,
// through the record format: an empty file, one that does not lex, one
// that is not Verilog at all. Each has a record, and each round-trips.
for src in [
"",
" \n\t\n",
"this is not verilog\n",
"module m;\n \"unterminated\n",
"// just a comment\n",
] {
let facts = FileFacts::of(PathBuf::from("/w/x.sv"), src);
let line = facts.encode().expect("encodes");
assert_eq!(FileFacts::decode(&line).as_ref(), Some(&facts), "{src:?}");
}
}
+10 -1
View File
@@ -52,7 +52,10 @@ lookups — 92 ms → 0.26 ms for a whole file's code lenses, 82 ms → 0.71 ms
- **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
`IndexBuilder::finish` and now lives in the index. (**Since
index-persistence, 2026-08-27** it also lives on *disk*: `FileFacts` is
public, encodable and decodable, and a record put back through
`IndexBuilder::add_facts` gives the index the file's parse would have.) 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.
@@ -169,6 +172,11 @@ pub struct InheritanceEdge { pub file: FileId, pub subclass: DeclSite }
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.
**Amended (index-persistence, 2026-08-27):** it also writes the file's new
record through to the on-disk index cache, using
`WorkspaceIndex::facts_for` to take back the record the update just made
rather than parsing anything twice. An hour of saves is an hour of work the
next session does not repeat.
- `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.
@@ -223,6 +231,7 @@ the remaining rows.
| `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 persistent index cache | this file's new record | written through, from the record `update_file` just made — no second parse (`docs/features/index-persistence/README.md`, 2026-08-27) |
| the diagnostics generation | — | bumped |
| the client's code lenses | the index | refresh requested |
File diff suppressed because it is too large. Load diff
+13
View File
@@ -166,6 +166,11 @@ pub fn build<'a>(files: …) -> WorkspaceIndex {
- `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`.
**Amended (index-persistence, 2026-08-27):** a third variant, `Cached {
done, total, path }` — the same three numbers, for a file the persistent
index cache answered for instead of a parse. A new variant rather than a
flag on `Parsing`, so that every consumer is asked by the compiler what it
wants to say about a file that was not parsed.
- `ClientSettings::max_file_size` is read in `collect_sources`; nothing else
in `state.rs` changed.
@@ -195,6 +200,14 @@ pub fn build<'a>(files: …) -> WorkspaceIndex {
callers, no duplicated send.
- `end_indexing` takes the skip count and says `"N files indexed, M skipped"`
when it is non-zero.
**Amended (index-persistence, 2026-08-27):** it takes the *cached* count as
well and names it first — `"860 files indexed, 858 from cache, 2 skipped"` —
because a scan that finished suspiciously fast should say why. Same rule as
the skip count: the number is in the end message whether or not the per-file
log is on. `IndexWatch` also grows an arm for `IndexEvent::Cached`, whose log
line reads `cached: <path>` where a parsed file's reads `indexing: <path>`,
and whose bar tick is identical — a cached file is a file of the work list,
and the bar flying through them is the point.
- `begin` still carries **no** percentage: the first honest one is the first
file's.
+22 -1
View File
@@ -236,6 +236,7 @@ reasoning and the measurements: `docs/features/cancel-request/README.md`.
| 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 — **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 |
| the **index cache** on disk | appended to as a whole rescan parses each file, rewritten when that rescan ends, and written through by every incremental one-file update | one `write` per parsed file. It is read at the start of every whole rescan and answers for every file whose content it already holds, which is what makes a reopened workspace cost the reads and not the parses (`docs/features/index-persistence/README.md`) |
**Per-file recompute on every keystroke** is the strategy TODO.md §6 states
("per-file recompute is fine at Verilog file sizes"); salsa is explicitly
@@ -275,6 +276,25 @@ also fed to the index builder **first**, so a long rescan's progress bar
completes them before anything else; the builder sorts by path internally, so
that ordering cannot change the index it produces.
**What a scan learned survives the session, since 2026-08-27**
(index-persistence). Every file a scan parses is written to a store — its
`FileFacts`, the whole of its contribution to the index, under the FNV-1a hash
of the bytes it was read from — and the next scan takes back every record
whose file still holds exactly those bytes instead of parsing it again. So
reopening a workspace, or reopening one whose first scan was interrupted, is a
rescan that costs the reads and not the parses: **181 ms warm against the
328 ms it cost cold** over the 860-file corpus in a release build, with the bar
saying `860 files indexed, 860 from cache` and the output log saying `cached:`
where it says `indexing:`. The store lives in
`initializationOptions.storagePath` (VS Code's per-workspace storage folder),
or wherever `lucisv.index.cachePath` says, or in this platform's cache
directory; `lucisv.index.persist: false` turns it off in both directions and
restores the pre-2026-08-27 behaviour exactly. **It is a performance artifact
and never a correctness input**: every record is verified against the file's
current content before it is used, and a stale, corrupt or foreign record
costs one parse and can change no answer. Rules, the record format and the
crash-safety argument: `docs/features/index-persistence/README.md`.
**Walked files over `lucisv.index.maxFileSize` (1 MiB by default) are not read
at all** — the size is taken from `fs::metadata` before the read, so a
generated netlist costs one `stat` rather than minutes of parsing. The cap is
@@ -294,7 +314,8 @@ which the override above keeps current. Rebuilding on every keystroke would
re-parse the whole workspace per character; rebuilding on save is the cheapest
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.
plus the file reads — **and about half that when the persistent index cache
answers for the files that have not changed** (index-persistence, below).
**Every *whole* rescan is visible since 2026-08-26**, for a client that
advertised `window.workDoneProgress`: the startup build and every whole
+12
View File
@@ -157,6 +157,18 @@ function activate(context) {
// `lucisv.indent` and `lucisv.exclude` from it and ignores the rest
// (docs/features/editor-settings/README.md).
synchronize: { configurationSection: 'lucisv' },
// Where the server may keep its index cache, so that reopening a
// workspace does not re-parse every file it already parsed last time
// (docs/features/index-persistence/README.md). `storageUri` is VS Code's
// own per-workspace folder for exactly this kind of state — it is
// cleaned up when the workspace is forgotten, which is what makes it a
// better answer than a directory the server would have to invent. It is
// `undefined` when no workspace is open, and then the global one stands
// in; the server falls back to this platform's cache directory if
// neither reaches it, and to no cache at all if it cannot work one out.
initializationOptions: {
storagePath: (context.storageUri || context.globalStorageUri || {}).fsPath,
},
};
client = new LanguageClient('lucisv', 'lucisv', serverOptions, clientOptions);
+11 -1
View File
@@ -260,7 +260,17 @@
"lucisv.index.logFiles": {
"type": "boolean",
"default": true,
"markdownDescription": "Name every file in the lucisv output channel as it is indexed, and every file the size cap skipped. Useful for finding out why a symbol is missing or why a scan is slow; turn it off if you would rather the channel stayed quiet. Files skipped by `#lucisv.index.maxFileSize#` are counted in the progress bar's final message either way."
"markdownDescription": "Name every file in the lucisv output channel as it is indexed, and every file the size cap skipped. Useful for finding out why a symbol is missing or why a scan is slow; turn it off if you would rather the channel stayed quiet. Files skipped by `#lucisv.index.maxFileSize#` are counted in the progress bar's final message either way. A file restored from the index cache is logged as `cached:` rather than `indexing:`."
},
"lucisv.index.persist": {
"type": "boolean",
"default": true,
"markdownDescription": "Remember what indexing a file found, so that reopening this workspace — or reopening it after a crash halfway through a scan — does not parse every unchanged file again. The store lives in this workspace's extension storage folder unless `#lucisv.index.cachePath#` says otherwise, and holds one entry per file **keyed by that file's exact contents**: an entry is used only for the bytes it was made from, so a stale or damaged one costs a re-parse and can never affect an answer. Turn it off to keep the index entirely in memory, as lucisv did before this setting existed; nothing is then read or written."
},
"lucisv.index.cachePath": {
"type": "string",
"default": "",
"markdownDescription": "Where to keep the index cache `#lucisv.index.persist#` writes — absolute, or relative to the first workspace folder. Empty (the default) means the extension's own per-workspace storage folder, which VS Code cleans up when the workspace is forgotten. Set this to share one cache between checkouts of the same tree, or to keep it somewhere faster. The directory is created on demand and marks itself ignored with a `.gitignore`. Takes effect on the next workspace scan."
}
}
}