Files
lucisv/crates/lucisv_server/src/state.rs
T
lucioandClaude Fable 5 bc606dd6bd
ci / checks (push) Successful in 45s
ci / corpus (push) Successful in 21s
Large-file fast path: 100 MB netlists open in 40 ms
Owner-requested round, the last of the large-workarea wave. Above
lucisv.largeFile.threshold (4 MiB default, 0 disables) a buffer opens
as a line index and nothing else — no lex, no parse, no semantics, and
its path removed from the index sources so nothing describes it by
stale disk bytes. Viewport highlighting lexes only the requested
window (snap to a line boundary, budget-bounded backward comment scan,
imperfection documented); semanticTokens/full answers the spec's
cancellation errors because the shipped VS Code binary marks tokens
complete on ANY non-error answer and never asks for ranges again —
settled by reading the bundle, verified independently by QA, pinned
with the client-library citations. Same-file definition/references
shipped on measurement (worst 37 ms vs the 150 ms budget); every
other handler answers as the empty file by construction; formatting
alone says why aloud. Two client facts recorded: VS Code never syncs
files over 50 MB, and above 20 MB our viewport tokens are the only
color.

QA rejected the first cut on the round's true shape — thousands of
tokens on one long line went quadratic through per-call UTF-16
conversion (7.86 s to color one 269 KB line). The fix adds a monotonic
PositionWalker to convert.rs (restart-on-backwards proven load-bearing
by the out-of-order tail-comment shape), adopted at three sites for
546x/759x on the probes — and it fixed ordinary files' semantic
tokens too (2.06 s to 232 ms on a one-line buffer), a cost the normal
path had always paid. Probes are now normally-running gates with 4.5x
margins, walker-vs-per-call equivalence swept over gnarly fixtures
and adversarial ping-pong.

51 tests added across both rounds (dev 43+5, QA 6+3, minus overlaps),
2 ignored probes. Completes the owner's large-workarea requests.

docs/features/large-file-mode/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 18:58:17 -07:00

2973 lines
134 KiB
Rust

//! What the server remembers: one analysis per open buffer, one index for the
//! workspace. The invalidation rules are in
//! `docs/features/lucisv-server/README.md`; the short version is that a buffer's
//! analysis is rebuilt on every change and the index only on save.
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use lsp_types::Uri;
use vlog_parser::ast::SourceFile;
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, FileFacts, IndexBuilder,
Semantics, WorkspaceIndex,
};
use lucisv_core::config::Discovery;
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;
/// How many `workspace/symbol` hits are returned. Each one costs a file read
/// to turn its byte span into a line, so an unbounded answer to the empty
/// query would read the whole workspace.
pub const WORKSPACE_SYMBOL_LIMIT: usize = 256;
/// One open buffer, fully analyzed. Every field is derived from `text`, so a
/// change throws the whole thing away and builds a new one.
pub struct Document {
/// The buffer's path, absent for a `untitled:` document.
pub path: Option<PathBuf>,
pub text: String,
pub line_index: LineIndex,
/// Empty when the file does not lex — the lexer is all-or-nothing.
pub tokens: Vec<Token>,
/// The tolerant parse of `text` — the tree `semantics` was analyzed from,
/// kept so the lint pass reads it instead of parsing the buffer again
/// ("one parse, two tools", `docs/features/one-parse/README.md`).
pub tree: SourceFile,
pub diagnostics: Vec<ParseDiagnostic>,
pub semantics: Semantics,
pub defines: DefineTable,
/// The workspace layer's answers for this file's external candidates.
pub external: ExternalResolutions,
/// Whether this buffer was opened on the **large-file fast path**: every
/// field above except `text` and `line_index` is the empty analysis of an
/// empty file, because nothing lexed it. Handlers that would scan the text
/// itself check this flag; the ones that read the analysis need not, since
/// there is nothing in it to find. See
/// `docs/features/large-file-mode/README.md`.
pub large: bool,
}
impl Document {
/// Analyze a buffer from scratch against the current workspace index.
pub fn new(path: Option<PathBuf>, text: String, index: &WorkspaceIndex) -> Document {
// One lex: the tree is built from a clone of the token stream instead
// of re-lexing the buffer (`parse_source_tolerant` is exactly
// `tokenize` + `parse_tolerant`, so the tree is identical). A buffer
// that does not lex keeps the old path, so its all-error tree and its
// lex diagnostic are byte-for-byte what they always were.
let (tokens, (tree, diagnostics)) = match tokenize(&text) {
Ok(tokens) => {
let parsed = parse_tolerant(tokens.clone(), &text);
(tokens, parsed)
}
Err(_) => (Vec::new(), parse_source_tolerant(&text)),
};
let defines = collect_defines(&tokens);
let semantics = analyze(&tree, &text);
let external = resolve_external(&semantics, index);
let line_index = LineIndex::new(&text);
let large = false;
Document {
path,
text,
line_index,
tokens,
tree,
diagnostics,
semantics,
defines,
external,
large,
}
}
/// Take a buffer on the **fast path**: index its lines and nothing else.
///
/// One newline scan is the whole cost of opening a 100 MB netlist. The
/// derived fields are the analysis of the *empty* file rather than of this
/// one — built by parsing `""`, which costs nothing and needs no new API
/// from `vlog_parser` — so every handler that reads the analysis finds
/// exactly nothing and answers empty without knowing this path exists.
pub fn large(path: Option<PathBuf>, text: String) -> Document {
let (tree, _) = parse_source_tolerant("");
let semantics = analyze(&tree, "");
let line_index = LineIndex::new(&text);
Document {
path,
text,
line_index,
tokens: Vec::new(),
tree,
diagnostics: Vec::new(),
semantics,
defines: DefineTable::default(),
external: ExternalResolutions::default(),
large: true,
}
}
/// This document's position converter.
pub fn positions(&self) -> Positions<'_> {
Positions::new(&self.text, &self.line_index)
}
/// Re-run only the workspace overlay, after the index was rebuilt. The
/// single-file analysis is unaffected by other files, by construction.
pub fn refresh_overlay(&mut self, index: &WorkspaceIndex) {
self.external = resolve_external(&self.semantics, index);
}
}
/// What the scope ladder decided: the files to index, the directories an
/// `` `include`` in them is looked for in, and what to tell the user.
#[derive(Default)]
struct Scope {
files: Vec<PathBuf>,
/// The filelist's `+incdir+`s, in filelist order. Empty for every rung
/// but the filelist — nothing else names an include path.
incdirs: Vec<PathBuf>,
warnings: Vec<String>,
}
/// A `Scope` with its files read: what one index rebuild works from.
struct Sources {
texts: Vec<(PathBuf, String)>,
incdirs: Vec<PathBuf>,
warnings: Vec<String>,
}
/// What an index rebuild reports about itself as it runs.
///
/// This module speaks no protocol, so an event carries numbers and paths and
/// nothing that reads like a message; `server.rs` turns them into a progress
/// report and a log line (`docs/features/indexing-ux/README.md`).
pub enum IndexEvent<'a> {
/// One file is about to be parsed into the index: how many were parsed
/// before it, how many there are in all, and which one it is. `done`
/// 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 },
}
/// The size of `path` when it is over `cap`, else `None` — the whole of the
/// `lucisv.index.maxFileSize` test.
///
/// Metadata only: the point of the cap is that a 200 MB netlist is never read
/// into memory, so asking the filesystem how big it is has to come first. A
/// `cap` of 0 is the client asking for no cap, and a file whose metadata
/// cannot be read is not skipped here — it simply fails the read below, as it
/// always did.
fn oversize(path: &Path, cap: u64) -> Option<u64> {
if cap == 0 {
return None;
}
let size = fs::metadata(path).ok()?.len();
(size > cap).then_some(size)
}
/// Every open buffer plus the workspace index they are resolved against.
#[derive(Default)]
pub struct Workspace {
docs: HashMap<Uri, Document>,
roots: Vec<PathBuf>,
index: WorkspaceIndex,
/// The project-wide completion tables, rebuilt with `index` and from the
/// same file list. Precomputed because completion fires per keystroke and
/// nothing that walks the workspace may.
candidates: Candidates,
/// What every in-scope file `` `include``s, and the `+incdir+`s an
/// include is looked for in. Rebuilt with `index`, from the same list.
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
/// index** — see `docs/features/index-scope/README.md`.
opened_dirs: Vec<PathBuf>,
}
impl Workspace {
/// Adopt the workspace roots and build the index for the first time.
/// Returns whatever the caller should tell the user about the scope.
///
/// The unwatched form. `server.rs` always watches (it has a progress bar
/// to move), so this is reachable from tests alone — of which there are
/// several dozen across this crate, and none of them has an opinion about
/// progress reporting.
#[cfg(test)]
pub fn open_roots(&mut self, roots: Vec<PathBuf>) -> Vec<String> {
self.open_roots_with(roots, &mut |_| {})
}
/// [`Workspace::open_roots`] with `lucisv.index.scope` set to
/// `"workspace"`: adopt the roots and index **all** of them, which is what
/// every session did before 2026-08-27.
///
/// Test-only, and used by the dozens of tests across this crate that are
/// about something other than scope — a hover, a rename, an inlay hint —
/// and want the whole fixture tree in the index without opening a buffer
/// in each of its directories first. Spelling it out at the call site is
/// what keeps "this test wants the wide scope" a statement rather than an
/// accident. The folder scope's own behaviour is tested by the tests named
/// in `docs/features/index-scope/README.md`.
#[cfg(test)]
pub fn open_whole_workspace(&mut self, roots: Vec<PathBuf>) -> Vec<String> {
self.open_whole_workspace_with(roots, &mut |_| {})
}
/// [`Workspace::open_whole_workspace`], watched. Test-only, for the two
/// tests that want the wide scope *and* the events.
#[cfg(test)]
pub fn open_whole_workspace_with(
&mut self,
roots: Vec<PathBuf>,
watch: &mut dyn FnMut(IndexEvent),
) -> Vec<String> {
self.client.index_scope = IndexScope::Workspace;
self.open_roots_with(roots, watch)
}
/// [`Workspace::open_roots`], watched — the startup build reports itself
/// exactly as every later rescan does.
pub fn open_roots_with(
&mut self,
roots: Vec<PathBuf>,
watch: &mut dyn FnMut(IndexEvent),
) -> Vec<String> {
self.roots = roots;
self.rebuild_index_with(watch)
}
/// Add and remove workspace roots mid-session, reporting whether the set
/// actually moved — which is whether the caller owes a rebuild.
///
/// Removals are applied before additions, so a folder named in both lists
/// (which the protocol does not forbid, and which is how some clients
/// spell "this folder moved") ends up present. Adding a root that is
/// already held and removing one that was never held are both no-ops, and
/// say so by leaving the set equal: `didChangeWorkspaceFolders` is a
/// notification, so there is nowhere to report a disagreement to and
/// nothing to gain from re-scanning for one.
pub fn change_roots(&mut self, added: Vec<PathBuf>, removed: &[PathBuf]) -> bool {
let before = self.roots.clone();
self.roots.retain(|root| !removed.contains(root));
for root in added {
if !self.roots.contains(&root) {
self.roots.push(root);
}
}
self.roots != before
}
pub fn index(&self) -> &WorkspaceIndex {
&self.index
}
/// The project-wide completion tables, as of the last index rebuild.
pub fn candidates(&self) -> &Candidates {
&self.candidates
}
/// The `` `include`` graph, as of the last index rebuild.
pub fn includes(&self) -> &IncludeGraph {
&self.includes
}
/// Whether the client opened a workspace at all.
///
/// Without one there is nothing to walk but the open buffers' own
/// directories, and nothing to clamp the folder scope's climb against.
///
/// Test-only since 2026-08-27: `didOpen` used to branch on it, and now
/// branches on whether the file widened the scope, which is the same
/// question asked of the rung that is actually in force.
#[cfg(test)]
pub fn has_roots(&self) -> bool {
!self.roots.is_empty()
}
/// The directories the folder scope walks: every directory a buffer has
/// been opened from this session, each raised `lucisv.index.scopeDepth`
/// levels. **Empty when the folder scope is not the active rung** — a
/// filelist and the whole-workspace walk are scopes an open buffer cannot
/// widen.
///
/// Public because `server.rs` compares it across a `didOpen` to decide
/// whether the file just opened widened the scope, which is the one thing
/// that makes a `didOpen` worth a rebuild.
pub fn scope_dirs(&self) -> Vec<PathBuf> {
if !self.folder_scoped() {
return Vec::new();
}
let mut dirs: Vec<PathBuf> = self.opened_dirs.iter().map(|dir| self.raised(dir)).collect();
dirs.sort();
dirs.dedup();
dirs
}
/// Whether rung 3 — the folder scope — is the one in force.
///
/// A filelist outranks it, and so does an explicit
/// `lucisv.index.scope: "workspace"` **when there is a workspace to
/// walk**: with no roots there is nothing that setting could name, so a
/// rootless session is folder-scoped whatever it says.
fn folder_scoped(&self) -> bool {
self.filelist_path().is_none() && !self.walks_the_workspace()
}
/// Whether rung 2 — the walk of every workspace folder — is in force.
fn walks_the_workspace(&self) -> bool {
self.client.index_scope == IndexScope::Workspace && !self.roots.is_empty()
}
/// `dir` raised `lucisv.index.scopeDepth` ancestor levels, clamped twice:
/// it never climbs above the workspace root that contains it — the deepest
/// one, for nested roots — and never above the filesystem root, which is
/// where a directory belonging to no root stops.
///
/// The root clamp is what keeps a `scopeDepth` of 5 in a two-deep project
/// from indexing the user's home directory.
fn raised(&self, dir: &Path) -> PathBuf {
let floor = self
.roots
.iter()
.filter(|root| dir.starts_with(root))
.max_by_key(|root| root.components().count());
let mut out = dir;
for _ in 0..self.client.index_scope_depth {
if Some(out) == floor.map(PathBuf::as_path) {
break;
}
let Some(parent) = out.parent() else { break };
out = parent;
}
out.to_path_buf()
}
/// The `lucisv.*` settings in force, for the resolution points in
/// `format.rs` to fold in.
pub fn client_settings(&self) -> &ClientSettings {
&self.client
}
/// Adopt the settings a client pushed.
///
/// Returns `true` when the caller must rebuild the index: `exclude`,
/// `filelist`, `index.maxFileSize`, `index.scope` and `index.scopeDepth`
/// are the five that change *which files exist* as far as this server is
/// concerned. `lineLength` and `indent` are read afresh by every
/// formatting request, so they need no invalidation at all — and neither
/// does `index.logFiles`, which changes only how loudly the *next* rescan
/// narrates itself.
///
/// `largeFile.threshold` asks for no rescan either, and deliberately: it
/// is consulted where a `Document` is *built*, so a change to it reaches
/// each open buffer at that buffer's next `didOpen`/`didChange` and not
/// before. A rescan now would index by the mode each buffer is still in,
/// which is the mode the index already reflects
/// (`docs/features/large-file-mode/README.md`).
pub fn set_client_settings(&mut self, settings: ClientSettings) -> bool {
let rescan = self.client.exclude != settings.exclude
|| self.client.filelist != settings.filelist
|| 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)
}
/// Replace a buffer's contents and re-analyze it.
///
/// Also the one place a directory enters the folder scope: a buffer with a
/// path puts its own directory on the list `scope_dirs` raises. An
/// `untitled:` buffer has no path and contributes none.
///
/// And the one place the **large-file fast path** is chosen: a text over
/// `lucisv.largeFile.threshold` is line-indexed and nothing more. Because
/// the decision lives here it is re-taken on every `didOpen`, `didChange`
/// and text-carrying `didSave`, which is what makes a buffer edited past
/// the threshold — or back under it — change mode at that moment and not
/// before (`docs/features/large-file-mode/README.md`).
pub fn set_document(&mut self, uri: Uri, text: String) {
let path = uri_to_path(&uri);
if let Some(dir) = path.as_deref().and_then(Path::parent) {
if !self.opened_dirs.iter().any(|seen| seen == dir) {
self.opened_dirs.push(dir.to_path_buf());
self.opened_dirs.sort();
}
}
let doc = match self.is_large(&text) {
true => Document::large(path, text),
false => Document::new(path, text, &self.index),
};
self.docs.insert(uri, doc);
}
/// Whether a buffer of this text takes the fast path. `0` disables it, and
/// the comparison is strict, so a buffer of exactly the threshold is still
/// analyzed in full.
fn is_large(&self, text: &str) -> bool {
let threshold = self.client.large_file_threshold;
threshold != 0 && text.len() as u64 > threshold
}
/// Whether any open buffer is on the large-file fast path.
///
/// The gate in `server.rs` runs before every request, and this is what
/// keeps that from costing a URI parse per request in the session where
/// nothing is large — which is every session but one.
pub fn has_large_documents(&self) -> bool {
self.docs.values().any(|doc| doc.large)
}
pub fn close_document(&mut self, uri: &Uri) {
self.docs.remove(uri);
}
/// Every open buffer's URI, for republishing diagnostics after a rebuild.
pub fn open_uris(&self) -> Vec<Uri> {
self.docs.keys().cloned().collect()
}
/// Re-scan the workspace and rebuild the index and the completion tables,
/// then refresh every open buffer's overlay. Called on `initialize` and on
/// every `didSave`.
///
/// Returns the warnings from resolving the scope — a filelist naming a
/// file that is gone, say. Rendering them is `server.rs`'s job; this
/// module speaks no protocol.
///
/// The unwatched form, reachable from tests alone for the same reason
/// `open_roots` is.
#[cfg(test)]
pub fn rebuild_index(&mut self) -> Vec<String> {
self.rebuild_index_with(&mut |_| {})
}
/// [`Workspace::rebuild_index`], watched: `watch` is called once for every
/// file the size cap skipped and once for every file about to be parsed,
/// in index order and before the parse, so a caller can report where the
/// rescan has got to.
///
/// The events cover the index build alone. The completion tables and the
/// include graph are built from the same list afterwards and are not
/// reported: they cost a small fraction of the parse, and a bar that went
/// to 100% and then sat there would be worse than one that ends.
pub fn rebuild_index_with(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Vec<String> {
let scope = self.collect_sources(watch);
let sources = scope.texts;
// The same list the index will be built from — asked of
// `vlog_semantic` rather than re-derived here, so the count reported
// is the count parsed — with the user's own open files moved to the
// front of it.
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() {
// 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);
// Same list again: an `` `include`` in a file the scope excluded is
// not an edge, and a file it excluded is not a hop away from anything.
self.includes = IncludeGraph::build(&sources, scope.incdirs);
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
scope.warnings
}
/// Rebuild the index for **one** file, leaving every other file's
/// contribution exactly as it is. Reports whether it could.
///
/// `false` means the caller must fall back to [`Workspace::rebuild_index`]:
/// the file is not one this index already holds, which is the one case the
/// cheap path cannot settle. A file appearing changes which *other* files
/// exist as far as the include graph is concerned (a `` `include`` that had
/// nothing to resolve to now has something), and answering that takes a
/// walk — so the rule is simply "a file the index already holds".
///
/// The four pieces of state a rebuild produces, and what happens to each:
///
/// * **the workspace index** — [`WorkspaceIndex::update_file`] /
/// [`WorkspaceIndex::remove_file`], which promise the index a whole
/// rebuild over the same file set would have produced;
/// * **the completion tables** — the two index-derived ones re-derived, the
/// word table patched by this file's words alone;
/// * **the include graph** — this file's edges re-scanned, the known-file
/// and folded-spelling tables re-learned from the index's list;
/// * **every open buffer's overlay** — refreshed, exactly as a rebuild
/// refreshes it, because any of them may resolve into the file that moved.
///
/// The text is chosen by `collect_sources`'s rules, for one path: an open
/// buffer beats disk and is never capped; a walked file over
/// `lucisv.index.maxFileSize`, one that has been deleted, and one that
/// cannot be read are all "this file is not in the index any more".
pub fn update_one(&mut self, path: &Path) -> bool {
if !self.index.files().iter().any(|held| held == path) {
return false;
}
match self.current_text(path) {
Some(text) => {
self.index.update_file(path.to_path_buf(), &text);
self.candidates.update_file(&self.index, path, &text);
self.includes.update_file(path, &text, self.index.files());
// 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);
self.candidates.remove_file(&self.index, path);
self.includes.remove_file(path, self.index.files());
}
}
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
true
}
/// [`Workspace::update_one`], then a whole rebuild over the same
/// workspace, asserting the two produced the same thing — the paranoid
/// form, for tests.
///
/// It is the incremental path's whole claim, checked rather than argued:
/// the index's fingerprint (ids, disambiguation order, member tables,
/// edges, define counts) and the completion word table, which is the one
/// piece of derived state that is patched rather than re-derived. The
/// workspace is left holding the *rebuilt* index, which is the same index,
/// so a test may keep using it.
#[cfg(test)]
pub fn update_one_checked(&mut self, path: &Path) -> bool {
if !self.update_one(path) {
return false;
}
let index = self.index.fingerprint();
let words = self.candidates.words("").to_vec();
self.rebuild_index();
assert_eq!(index, self.index.fingerprint(), "incremental index != rebuilt index");
assert_eq!(words, self.candidates.words(""), "incremental words != rebuilt words");
true
}
/// The text one in-scope file contributes right now, by `collect_sources`'s
/// rules — `None` when it contributes nothing at all.
fn current_text(&self, path: &Path) -> Option<String> {
if let Some(doc) = self.docs.values().find(|doc| doc.path.as_deref() == Some(path)) {
// A fast-path buffer contributes nothing, exactly as it does in
// `collect_sources` — indexing it is the parse the fast path
// exists to skip.
return (!doc.large).then(|| doc.text.clone());
}
if oversize(path, self.client.max_file_size).is_some() {
return None;
}
fs::read_to_string(path).ok()
}
/// The work list with the open buffers' own files at the front of it, each
/// group still in path order (`sort_by_key` is stable).
///
/// **A reporting nicety and nothing else.** `vlog_semantic::IndexBuilder`
/// sorts by path inside `finish` since 2026-08-27, so no insertion order
/// can reach the index: this changes which file the progress bar names
/// first — the user's own, which is the one they are waiting on — and
/// changes nothing about the result. Pinned both ends: the builder's own
/// `no_insertion_order_can_change_what_the_builder_produces`, and
/// `the_open_files_are_indexed_first_and_the_index_cannot_tell` here.
fn open_first<'a>(&self, mut files: Vec<(PathBuf, &'a str)>) -> Vec<(PathBuf, &'a str)> {
let open: Vec<&Path> = self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
files.sort_by_key(|(path, _)| !open.contains(&path.as_path()));
files
}
/// The in-scope files and their current text — what a refactoring reads.
///
/// The same list `rebuild_index` feeds the index, recomputed rather than
/// kept: a refactoring is a rare, user-initiated request, and a second
/// copy of the workspace in memory is a high price for saving one walk.
pub fn sources(&self) -> Vec<(PathBuf, String)> {
self.collect_sources(&mut |_| {}).texts
}
/// Read every in-scope file, with open buffers overriding disk.
///
/// This is where `lucisv.index.maxFileSize` applies, and it applies to the
/// **walked** files only: an open buffer is folded in below whatever its
/// size, because the user opened it deliberately and an editor that
/// refused to understand the file on screen would be absurd. The check is
/// a `metadata` call ahead of the read, so an oversized file is never read
/// at all — which is the whole saving.
///
/// A refactoring reads this same list through `sources()`, so a file the
/// cap keeps out of the index is also a file a workspace rename will not
/// rewrite. That is the consistent answer: the cap says which files exist
/// as far as this server is concerned.
fn collect_sources(&self, watch: &mut dyn FnMut(IndexEvent)) -> Sources {
let scope = self.source_files();
let cap = self.client.max_file_size;
let mut texts: Vec<(PathBuf, String)> = Vec::new();
for path in scope.files {
if let Some(size) = oversize(&path, cap) {
watch(IndexEvent::Skipped { path: &path, size, cap });
continue;
}
if let Ok(text) = fs::read_to_string(&path) {
texts.push((path, text));
}
}
// Open buffers override what is on disk, and contribute themselves
// when they are not on disk at all.
//
// Except a buffer on the large-file fast path, which overrides disk
// with *nothing*: indexing it means parsing the hundred megabytes the
// fast path exists not to parse. Removing the path rather than leaving
// the disk copy in is the honest half of that — the alternative would
// be an index describing a file the user is looking at by bytes it no
// longer has. See `docs/features/large-file-mode/README.md` for the
// interaction with `lucisv.index.maxFileSize`, whose "an open buffer is
// never capped" rule this is the one exception to.
for doc in self.docs.values() {
let Some(path) = doc.path.clone() else { continue };
texts.retain(|(p, _)| p != &path);
if !doc.large {
texts.push((path, doc.text.clone()));
}
}
Sources { texts, incdirs: scope.incdirs, warnings: scope.warnings }
}
/// The text of a workspace file: the open buffer if there is one, else
/// what is on disk. Same precedence the index rebuild uses, so a location
/// is never computed against text the index did not see.
pub fn text_of(&self, path: &Path) -> Option<String> {
let open = self.docs.values().find(|d| d.path.as_deref() == Some(path));
match open {
Some(doc) => Some(doc.text.clone()),
None => fs::read_to_string(path).ok(),
}
}
/// The files the index covers, and what the user should be told about how
/// they were chosen. The scope ladder, highest first:
///
/// 1. **A filelist** — `lucisv.filelist`, else a `filelist` key in the
/// config governing a workspace root. It names *exactly* the files to
/// index; the project said so, and guessing past it would defeat the
/// point of having one. This is the "project file", and it is the one
/// rung that is whole-project by definition.
/// 2. **The workspace-folder walk**, on `lucisv.index.scope:
/// "workspace"` — what every session did before 2026-08-27, now opt-in.
/// 3. **The folder scope**, the default: each opened buffer's own
/// directory raised `lucisv.index.scopeDepth` levels, walked. See
/// `docs/features/index-scope/README.md` for what that costs, which is
/// that a definition in another folder does not resolve until the
/// scope reaches that folder.
///
/// A configured filelist that cannot be read falls back to rung 2 (or 3)
/// with a warning. An editor that shows no symbols because of a typo in a
/// path is worse than one that quietly indexes what it can and says so.
///
/// Only rung 1 can carry `+incdir+` directories: a walked workspace names
/// none, so an `` `include`` there resolves against the including file's
/// own directory alone (`docs/features/include-nav/README.md`).
fn source_files(&self) -> Scope {
let Some(path) = self.filelist_path() else {
return Scope { files: self.default_files(), ..Default::default() };
};
match lucisv_core::filelist::read(&path) {
Ok(list) => Scope { files: list.files, incdirs: list.incdirs, warnings: list.warnings },
Err(problem) => Scope {
files: self.default_files(),
incdirs: Vec::new(),
warnings: vec![format!("{problem} — indexing the workspace instead")],
},
}
}
/// The filelist governing this workspace, if any: the client's setting
/// first (absolute, or relative to the first root), else the `filelist`
/// key of the config governing a root, in root order.
///
/// Public because the file watchers must name it: a `.f` edited outside
/// the editor changes the index's scope, and nothing else on disk would
/// tell us (`docs/features/file-watching/README.md`).
pub fn filelist_path(&self) -> Option<PathBuf> {
if let Some(setting) = &self.client.filelist {
let path = Path::new(setting);
return Some(match self.roots.first() {
Some(root) if path.is_relative() => root.join(path),
_ => path.to_path_buf(),
});
}
let mut discovery = Discovery::new(true);
// A broken `lucisv.toml` names no filelist, exactly as it contributes no
// excludes below: the user hears about it when they format.
self.roots.iter().find_map(|root| discovery.for_dir(root).ok()?.filelist)
}
/// Rungs 2 and 3 of the ladder: the whole-workspace walk when the client
/// asked for it, else the folder scope.
fn default_files(&self) -> Vec<PathBuf> {
if self.walks_the_workspace() {
return self.walked_files(&self.roots);
}
self.folder_files()
}
/// Rung 3: the folder scope — [`Workspace::scope_dirs`], walked with every
/// filter the workspace walk applies.
///
/// One exception, kept exactly as it was from before this rung became the
/// default: **a rootless session at depth 0 reads its directories flat**,
/// one level, no `.gitignore`. That is the "a file opened on its own"
/// case, where descending a tree the user never named would be a surprise
/// — and the moment the user raises `scopeDepth` they have named one, so
/// the walk is what they asked for.
fn folder_files(&self) -> Vec<PathBuf> {
let dirs = self.scope_dirs();
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
return sibling_files(&dirs);
}
self.walked_files(&dirs)
}
/// Every source file under `dirs`, found by the CLI's own walk: the same
/// extensions, the same `.gitignore` handling, and the `exclude` patterns
/// of the config governing each directory. What `lucisv` skips, the index
/// skips.
///
/// `dirs` is the workspace roots for rung 2 and the scope directories for
/// rung 3. The one honest difference between the two: `.gitignore` files
/// are read from the walk's own starting directory downwards, so a rule
/// written in a root's `.gitignore` does not apply to a rung-3 walk that
/// starts below it. The `exclude` patterns are matched against whole
/// paths and so behave identically either way.
fn walked_files(&self, dirs: &[PathBuf]) -> Vec<PathBuf> {
let mut discovery = Discovery::new(true);
let mut out = Vec::new();
for root in dirs {
// The walk names its inputs as strings; every directory here came
// from a `file:` URI, which cannot carry a non-UTF-8 path.
let Some(input) = root.to_str() else { continue };
// A broken `lucisv.toml` must not stop the server from indexing: an
// index that excludes nothing is a far better failure than a
// server that comes up empty. The error is reported when the user
// formats a file in this tree (`format::settings_for`).
let mut exclude =
discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default();
// The client's `lucisv.exclude` is *appended*, never substituted —
// the CLI appends a config's excludes to `--exclude` the same way,
// and a setting that silently dropped a checked-in exclude would
// put vendored code back in the index for one user only.
exclude.extend(self.client.exclude.iter().cloned());
// `.gitignore` is always honoured: it is the CLI's default, and an
// editor has no `--no-gitignore` to type. An unreadable directory
// is simply not indexed, exactly as before this walk was shared.
let _ = collect_files(input, &exclude, true, &mut out);
}
out.sort();
out.dedup();
out
}
}
/// The source files sitting in each of `dirs`, one directory deep. No walk, no
/// `.gitignore`: this is the rootless default, where descending a tree the
/// user never named would be a surprise.
fn sibling_files(dirs: &[PathBuf]) -> Vec<PathBuf> {
let mut out = Vec::new();
for dir in dirs {
let Ok(entries) = fs::read_dir(dir) else { continue };
for entry in entries.flatten() {
let path = entry.path();
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or_default();
if path.is_file() && EXTENSIONS.contains(&extension) {
out.push(path);
}
}
}
out.sort();
out.dedup();
out
}
#[cfg(test)]
mod tests {
use super::*;
use std::slice::from_ref;
use std::str::FromStr;
fn uri(s: &str) -> Uri {
Uri::from_str(s).expect("test uri parses")
}
#[test]
fn a_document_analyzes_a_clean_file() {
let mut ws = Workspace::default();
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire a;\nendmodule\n".into());
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
assert!(doc.diagnostics.is_empty());
assert_eq!(doc.path.as_deref(), Some(Path::new("/rtl/m.sv")));
assert!(doc.semantics.symbols().iter().any(|s| s.name == "m"));
assert!(!doc.tokens.is_empty());
}
#[test]
fn a_broken_file_still_analyzes() {
let mut ws = Workspace::default();
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire ;\nendmodule\n".into());
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
assert!(!doc.diagnostics.is_empty(), "a broken buffer must report");
assert!(doc.semantics.symbols().iter().any(|s| s.name == "m"), "and still bind");
}
#[test]
fn a_file_that_does_not_lex_has_no_tokens_but_has_a_diagnostic() {
let mut ws = Workspace::default();
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire a; /* unterminated\n".into());
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
assert!(doc.tokens.is_empty());
assert_eq!(doc.diagnostics.len(), 1);
}
#[test]
fn an_untitled_buffer_has_no_path() {
let mut ws = Workspace::default();
ws.set_document(uri("untitled:Untitled-1"), "module m;\nendmodule\n".into());
let doc = ws.document(&uri("untitled:Untitled-1")).expect("open");
assert_eq!(doc.path, None);
}
#[test]
fn an_open_buffer_overrides_disk_in_the_index() {
let dir = std::env::temp_dir().join(format!("lucisv_server_state_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("temp dir");
let path = dir.join("pkg.sv");
fs::write(&path, "package p;\n localparam ON_DISK = 1;\nendpackage\n").expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1);
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0);
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package p;\n localparam IN_BUFFER = 1;\nendpackage\n".into());
ws.rebuild_index();
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 1, "buffer must win");
assert_eq!(ws.index().member("p", "ON_DISK").len(), 0, "disk must lose");
let _ = fs::remove_dir_all(&dir);
}
// ------------------------------------------------------------------
// the large-file fast path
// ------------------------------------------------------------------
/// A workspace whose fast path starts at `threshold` bytes.
fn thresholded(threshold: u64) -> Workspace {
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings {
large_file_threshold: threshold,
..ClientSettings::default()
});
ws
}
/// A buffer of exactly `bytes` bytes that is also real Verilog.
fn filler(bytes: usize) -> String {
let mut text = String::from("module m;\n");
while text.len() + 9 <= bytes {
text.push_str(" wire a;\n");
}
while text.len() < bytes {
text.push(' ');
}
text
}
#[test]
fn the_threshold_is_strict_at_the_boundary() {
let sizes = [99, 100, 101];
let large: Vec<bool> = sizes
.iter()
.map(|&size| {
let mut ws = thresholded(100);
ws.set_document(uri("file:///rtl/big.v"), filler(size));
ws.document(&uri("file:///rtl/big.v")).expect("open").large
})
.collect();
assert_eq!(large, [false, false, true], "under, at, over");
}
#[test]
fn a_threshold_of_zero_turns_the_fast_path_off_entirely() {
let mut ws = thresholded(0);
ws.set_document(uri("file:///rtl/big.v"), filler(200_000));
let doc = ws.document(&uri("file:///rtl/big.v")).expect("open");
assert!(!doc.large);
assert!(!doc.tokens.is_empty(), "it really was lexed");
}
#[test]
fn a_fast_path_buffer_holds_the_analysis_of_an_empty_file() {
let mut ws = thresholded(100);
ws.set_document(uri("file:///rtl/big.v"), filler(500));
let doc = ws.document(&uri("file:///rtl/big.v")).expect("open");
assert!(doc.large);
assert!(doc.tokens.is_empty(), "nothing was lexed");
assert!(doc.diagnostics.is_empty(), "nothing was parsed");
assert!(doc.semantics.symbols().is_empty(), "nothing was analyzed");
assert!(doc.defines.entries().is_empty(), "no defines were collected");
// But the two things the fast path *does* build are real.
assert_eq!(doc.text.len(), 500);
assert!(doc.line_index.line_count() > 1);
}
#[test]
fn a_fast_path_buffer_contributes_nothing_to_the_index_and_leaves_no_disk_copy_behind() {
let tree = Tree::new("largefile");
tree.write("pkg.sv", "package p;\n localparam ON_DISK = 1;\nendpackage\n");
let path = tree.path.join("pkg.sv");
let mut ws = thresholded(100);
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "premise: disk was indexed");
// The same file, opened as a buffer the fast path takes.
let mut text = String::from("package p;\n localparam IN_BUFFER = 1;\nendpackage\n");
text.push_str(&" ".repeat(200));
ws.set_document(crate::uri::path_to_uri(&path).expect("uri"), text);
ws.rebuild_index();
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0, "the buffer was not parsed");
assert_eq!(
ws.index().member("p", "ON_DISK").len(),
0,
"and the disk copy the buffer supersedes is not indexed in its place"
);
}
#[test]
fn a_buffer_edited_past_the_threshold_changes_mode_and_back() {
let mut ws = thresholded(200);
let file = uri("file:///rtl/grow.v");
ws.set_document(file.clone(), "module m;\nendmodule\n".into());
assert!(!ws.document(&file).expect("open").large);
ws.set_document(file.clone(), filler(1_000));
assert!(ws.document(&file).expect("open").large, "grew past the threshold");
ws.set_document(file.clone(), "module m;\nendmodule\n".into());
let doc = ws.document(&file).expect("open");
assert!(!doc.large, "and shrank back under it");
assert!(!doc.tokens.is_empty(), "with a full analysis again");
}
/// A scratch workspace root. Removed on drop.
struct Tree {
path: PathBuf,
}
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("lucisv_server_scan_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
fn write(&self, rel: &str, text: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).expect("parent");
}
fs::write(&path, text).expect("write");
}
/// A package declaring one localparam, so the index can be asked
/// whether this file was scanned at all.
fn package(&self, rel: &str, name: &str) {
self.write(rel, &format!("package {name};\n localparam K = 1;\nendpackage\n"));
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
#[test]
fn a_root_added_mid_session_widens_the_scan_and_a_removed_one_narrows_it() {
let first = Tree::new("rootsfirst");
first.package("a.sv", "a");
let second = Tree::new("rootssecond");
second.package("b.sv", "b");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![first.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "premise: one folder");
assert!(ws.change_roots(vec![second.path.clone()], &[]), "a new folder moves the set");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"], "both folders are scanned");
assert!(ws.change_roots(Vec::new(), from_ref(&first.path)), "and so does dropping one");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["b"], "the dropped folder's files are gone");
}
#[test]
fn a_subdirectory_of_an_existing_root_added_as_its_own_root_is_not_double_indexed() {
// Overlap does not duplicate a file's registration: `walked_files`
// walks each root independently and `dedup`s the combined, sorted
// list by path, so a file both roots would reach lands in the index
// once, not twice (a second identical registration would show up as
// an *ambiguous* member — `indexed` below only counts a name found
// exactly once).
//
// It is NOT exclude-proof, though, and that half is a genuine
// consequence of "each root is governed by its own config"
// (documented on `walked_files`): a directory the parent root's
// `lucisv.toml` excludes is added *as a root in its own right* here,
// and nothing excludes a root from itself. QA (2026-08-27): flagged
// in the QA log as a finding, not a bug fix — this is consistent
// with the per-root config model, but it was unreachable before this
// round (roots used to be frozen at `initialize`), so it is worth a
// pin and a name.
let tree = Tree::new("subdirroot");
tree.write("lucisv.toml", "exclude = [\"sub\"]\n");
tree.package("kept.sv", "kept");
tree.package("sub/hidden.sv", "hidden_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["kept", "hidden_pkg"]), ["kept"], "excluded, as configured");
assert!(ws.change_roots(vec![tree.path.join("sub")], &[]));
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["kept", "hidden_pkg"]),
["kept", "hidden_pkg"],
"reachable once through the added root, and only once — not ambiguous"
);
}
#[test]
fn a_folder_change_that_changes_nothing_asks_for_no_rescan() {
// Every no-op shape a client can send. Each must leave the root set
// exactly as it was, and say so — a rescan here is pure cost.
let tree = Tree::new("rootsnoop");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert!(!ws.change_roots(Vec::new(), &[]), "an empty event");
assert!(!ws.change_roots(vec![tree.path.clone()], &[]), "a folder already held");
let never = tree.path.join("never-added");
assert!(!ws.change_roots(Vec::new(), from_ref(&never)), "a folder never held");
assert!(!ws.change_roots(vec![tree.path.clone()], from_ref(&never)), "and both at once");
assert!(ws.has_roots(), "the root survived every one of them");
}
#[test]
fn a_trailing_slash_in_the_removed_folder_still_matches_the_held_root() {
// `uri_to_path` decodes a URI verbatim, trailing slash and all, and
// `change_roots` compares by `PathBuf` equality — which compares
// components, not raw strings, so `/a/b/` and `/a/b` are already the
// same path as far as `retain`/`contains` are concerned. Pinned
// because the doc README calls this out as a boundary worth
// checking, not because the standard library needed help.
let tree = Tree::new("trailingslash");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
let mut with_slash = tree.path.clone().into_os_string();
with_slash.push("/");
assert!(
ws.change_roots(Vec::new(), from_ref(&PathBuf::from(with_slash))),
"the trailing slash must not hide the match"
);
assert!(!ws.has_roots());
}
#[test]
fn a_folder_named_in_both_halves_of_one_event_stays() {
// Removals run first, so "removed and added again" — which is how a
// moved folder reaches some clients — is not a way to lose a root.
let tree = Tree::new("rootsboth");
tree.package("a.sv", "a");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(!ws.change_roots(vec![tree.path.clone()], from_ref(&tree.path)), "no net change");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a"]), ["a"]);
}
#[test]
fn a_folder_added_twice_across_two_events_is_absent_after_one_removal() {
// The root set is a set, not a multiset: `change_roots` dedups on
// push (`if !self.roots.contains(&root)`), so a second add of the
// same path — even from a *later*, separate notification — never
// grows a reference count for it. One removal is therefore always
// enough, however many times a client (redundantly) added it.
// QA (2026-08-27): pinned per the review checklist's multiset-vs-set
// question.
let tree = Tree::new("addedtwice");
let extra = Tree::new("addedtwiceextra");
extra.package("x.sv", "x");
let mut ws = Workspace::default();
// Whole-workspace scope, so the indexed-content assertions below see
// the roots at all — under the default folder scope nothing is
// walked until a buffer opens, and the closing assertion was vacuous
// (QA finding, 2026-08-27, lead-fixed).
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(ws.change_roots(vec![extra.path.clone()], &[]), "the first add moves the set");
assert!(
!ws.change_roots(vec![extra.path.clone()], &[]),
"a second, separate add of the same path is a no-op"
);
ws.rebuild_index();
assert_eq!(indexed(&ws, &["x"]), vec!["x".to_string()], "present while added");
assert!(
ws.change_roots(Vec::new(), from_ref(&extra.path)),
"one removal is enough to take it out"
);
ws.rebuild_index();
assert_eq!(indexed(&ws, &["x"]), Vec::<String>::new(), "gone, not merely decremented");
}
#[test]
fn removing_the_last_root_falls_back_to_the_rootless_model() {
// Rung 3 of the ladder is not a startup-only state: a session that
// closes its last folder becomes the single-file case, and an open
// buffer must still resolve against the files beside it.
let tree = Tree::new("rootslast");
tree.package("rtl/open.sv", "open_pkg");
tree.package("rtl/sibling.sv", "sibling");
tree.package("elsewhere/far.sv", "far");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["open_pkg", "sibling", "far"]), ["open_pkg", "sibling", "far"]);
let path = tree.path.join("rtl/open.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package open_pkg;\n localparam K = 1;\nendpackage\n".into());
assert!(ws.change_roots(Vec::new(), from_ref(&tree.path)));
assert!(!ws.has_roots(), "the workspace is rootless now");
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["open_pkg", "sibling", "far"]),
["open_pkg", "sibling"],
"the buffer and its neighbours, as if the file had been opened on its own"
);
}
#[test]
fn removing_the_last_root_leaves_a_relative_filelist_unanchored() {
// `filelist_path` anchors a relative setting at `roots.first()`. With
// no roots left there is nothing to anchor it to, and the path comes
// back exactly as the client wrote it — not resolved against the
// folder that is now gone, and not resolved against anything else
// either. Nothing panics: `source_files` still falls back to the
// rootless walk with a warning when that bare path cannot be read
// (`a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so`
// covers that fallback). QA (2026-08-27): pinned because this is new
// reachable behaviour this round — losing the last root used to be
// impossible.
let tree = Tree::new("rootslastfilelist");
tree.package("rtl/open.sv", "open_pkg");
tree.write("files.f", "rtl/open.sv\n");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(
ws.filelist_path(),
Some(tree.path.join("files.f")),
"anchored at the root while it exists"
);
assert!(ws.change_roots(Vec::new(), from_ref(&tree.path)));
assert_eq!(
ws.filelist_path(),
Some(PathBuf::from("files.f")),
"with no roots left, the same setting comes back bare — anchored at nothing"
);
}
#[test]
fn the_scan_skips_what_a_gitignore_skips() {
let tree = Tree::new("gitignore");
tree.write(".gitignore", "generated/\n*_gen.sv\n");
tree.package("kept.sv", "kept");
tree.package("generated/netlist.sv", "generated_pkg");
tree.package("rtl/top_gen.sv", "gen_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(ws.index().member("kept", "K").len(), 1, "a plain file is indexed");
assert_eq!(ws.index().member("generated_pkg", "K").len(), 0, "an ignored directory");
assert_eq!(ws.index().member("gen_pkg", "K").len(), 0, "an ignored name, at depth");
}
#[test]
fn the_scan_honours_the_root_configs_excludes() {
let tree = Tree::new("excludes");
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
tree.package("kept.sv", "kept");
tree.package("vendor/ip.sv", "vendor_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(ws.index().member("kept", "K").len(), 1);
assert_eq!(ws.index().member("vendor_pkg", "K").len(), 0, "lucisv.toml excludes apply");
}
#[test]
fn a_broken_root_config_does_not_stop_the_scan() {
// Exit 2 is the CLI's answer to a broken config; a server that indexed
// nothing because of a typo would look simply broken instead.
let tree = Tree::new("brokencfg");
tree.write("lucisv.toml", "bogus = 1\n");
tree.package("kept.sv", "kept");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(ws.index().member("kept", "K").len(), 1);
}
/// `settings` with the pre-2026-08-27 whole-workspace scope asked for —
/// the push-door twin of [`Workspace::open_whole_workspace`], needed
/// wherever a test pushes settings *after* opening its roots, since a push
/// replaces every field including the scope.
fn wide(settings: ClientSettings) -> ClientSettings {
ClientSettings { index_scope: IndexScope::Workspace, ..settings }
}
/// `lucisv.exclude` as a client would push it.
fn excluding(patterns: &[&str]) -> ClientSettings {
ClientSettings {
exclude: patterns.iter().map(|p| p.to_string()).collect(),
..Default::default()
}
}
#[test]
fn a_pushed_exclude_hides_files_from_the_index() {
let tree = Tree::new("clientexclude");
tree.package("kept.sv", "kept");
tree.package("scratch/wip.sv", "scratch_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 1, "premise: indexed at first");
assert!(ws.set_client_settings(wide(excluding(&["scratch"]))), "an exclude change rescans");
ws.rebuild_index();
assert_eq!(ws.index().member("kept", "K").len(), 1, "an unmatched file stays");
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 0, "the excluded one is gone");
}
#[test]
fn a_pushed_exclude_is_appended_to_the_configs_and_does_not_replace_it() {
// The failure this guards: a user setting `lucisv.exclude` in their
// editor and thereby putting the project's vendored code — which the
// checked-in `lucisv.toml` excludes — back into the index for them only.
let tree = Tree::new("bothexcludes");
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
tree.package("kept.sv", "kept");
tree.package("vendor/ip.sv", "vendor_pkg");
tree.package("scratch/wip.sv", "scratch_pkg");
let mut ws = Workspace::default();
ws.set_client_settings(excluding(&["scratch"]));
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(ws.index().member("kept", "K").len(), 1, "an unmatched file stays");
assert_eq!(ws.index().member("vendor_pkg", "K").len(), 0, "the config's exclude holds");
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 0, "and the pushed one applies");
}
#[test]
fn only_an_exclude_change_asks_for_a_rescan() {
// `lineLength` and `indent` are read afresh by every formatting
// request, so re-walking the workspace for them would be pure cost.
let mut ws = Workspace::default();
assert!(!ws.set_client_settings(ClientSettings::default()), "nothing changed");
assert!(
!ws.set_client_settings(ClientSettings {
line_length: Some(120),
indent: Some(4),
..Default::default()
}),
"widths do not move files"
);
// QA (2026-08-26): `format_on_save` is read afresh by
// `will_save_wait_until` exactly as `indent`/`lineLength` are by
// `formatting` — it must not ask for a rescan either, or every
// `lucisv.formatOnSave` toggle would pay for a full re-walk (and, on
// a client that pulls, bump the diagnostics generation along with
// it).
assert!(
!ws.set_client_settings(ClientSettings { format_on_save: true, ..Default::default() }),
"turning the save hook on does not move files either"
);
// The file log changes how loudly a rescan narrates itself and nothing
// about which files exist, so it must not buy one.
assert!(
!ws.set_client_settings(ClientSettings { log_files: false, ..Default::default() }),
"turning the per-file log off does not move files either"
);
assert!(ws.set_client_settings(excluding(&["a"])), "a new exclude does");
// The cap does move files, so it does.
assert!(
ws.set_client_settings(ClientSettings {
exclude: vec!["a".to_string()],
max_file_size: 4096,
..Default::default()
}),
"a new cap rescans"
);
assert!(
!ws.set_client_settings(ClientSettings {
exclude: vec!["a".to_string()],
max_file_size: 4096,
log_files: false,
..Default::default()
}),
"the same cap with a different log setting does not"
);
assert!(
ws.set_client_settings(ClientSettings {
exclude: vec!["a".to_string()],
log_files: false,
..Default::default()
}),
"and going back to the default cap does"
);
ws.set_client_settings(excluding(&["a"]));
assert!(!ws.set_client_settings(excluding(&["a"])), "the same one again does not");
assert!(ws.set_client_settings(excluding(&["a", "b"])), "an added pattern does");
assert!(ws.set_client_settings(ClientSettings::default()), "and so does clearing it");
}
/// A `ClientSettings` with the size cap set to `bytes`.
fn capping(bytes: u64) -> ClientSettings {
ClientSettings { max_file_size: bytes, ..Default::default() }
}
/// A file of `bytes` bytes that would declare `name` if anything read it.
/// Padded with a trailing comment, so what makes it big is not what makes
/// it a package.
fn fat_package(tree: &Tree, rel: &str, name: &str, bytes: usize) {
let head = format!("package {name};\n localparam K = 1;\nendpackage\n// ");
let mut text = String::with_capacity(bytes + head.len());
text.push_str(&head);
while text.len() < bytes {
text.push('x');
}
text.push('\n');
tree.write(rel, &text);
}
#[test]
fn a_walked_file_over_the_cap_is_left_out_of_the_index() {
let tree = Tree::new("capskip");
tree.package("small.sv", "small_pkg");
fat_package(&tree, "netlist.sv", "netlist_pkg", 4096);
let mut ws = Workspace::default();
ws.set_client_settings(capping(1024));
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(
indexed(&ws, &["small_pkg", "netlist_pkg"]),
["small_pkg"],
"the big file is not in the index, and was never read"
);
}
#[test]
fn the_default_cap_is_a_mebibyte_and_zero_turns_it_off() {
// The shipped default, exercised against a file that really is over
// 1 MiB — the only way to prove the constant is the one in force.
let tree = Tree::new("capdefault");
tree.package("small.sv", "small_pkg");
fat_package(&tree, "huge.sv", "huge_pkg", 1024 * 1024 + 1);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["small_pkg", "huge_pkg"]), ["small_pkg"], "capped by default");
// `0` is the client asking for no cap, and must be exactly the
// behaviour that existed before there was one.
assert!(ws.set_client_settings(wide(capping(0))), "turning the cap off rescans");
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["small_pkg", "huge_pkg"]),
["small_pkg", "huge_pkg"],
"nothing capped"
);
}
#[test]
fn an_open_buffer_is_indexed_however_big_the_file_is() {
// The documented exemption: the cap is about files nobody asked for.
// A buffer the user opened is indexed and diagnosed whatever its size,
// or the editor would refuse to understand the file on screen.
let tree = Tree::new("capbuffer");
fat_package(&tree, "huge.sv", "huge_pkg", 4096);
let mut ws = Workspace::default();
ws.set_client_settings(capping(1024));
// Whole-workspace scope so the walked file is genuinely capped by the
// CAP, not merely unreachable by the folder scope (QA finding,
// 2026-08-27, lead-fixed: the premise held for the wrong reason).
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["huge_pkg"]), Vec::<String>::new(), "premise: capped on disk");
let uri = crate::uri::path_to_uri(&tree.path.join("huge.sv")).expect("uri");
let text = fs::read_to_string(tree.path.join("huge.sv")).expect("read");
ws.set_document(uri, text);
ws.rebuild_index();
assert_eq!(indexed(&ws, &["huge_pkg"]), ["huge_pkg"], "the open buffer is indexed in full");
}
#[test]
fn every_skipped_file_is_reported_with_its_size_and_the_cap() {
let tree = Tree::new("capevents");
tree.package("small.sv", "small_pkg");
fat_package(&tree, "netlist.sv", "netlist_pkg", 4096);
let mut ws = Workspace::default();
ws.set_client_settings(capping(1024));
let mut skipped: Vec<(PathBuf, u64, u64)> = Vec::new();
ws.open_whole_workspace_with(vec![tree.path.clone()], &mut |event| {
if let IndexEvent::Skipped { path, size, cap } = event {
skipped.push((path.to_path_buf(), size, cap));
}
});
assert_eq!(skipped.len(), 1, "{skipped:?}");
assert_eq!(skipped[0].0, tree.path.join("netlist.sv"));
assert!(skipped[0].1 >= 4096, "the file's real size: {skipped:?}");
assert_eq!(skipped[0].2, 1024, "and the cap it was measured against");
}
#[test]
fn the_watcher_sees_every_file_in_index_order_against_a_total_it_knew_first() {
// The denominator is the work list *after* the exclude and the cap:
// a bar counting towards a number that included files nobody was
// going to parse would stall short of the end every time.
let tree = Tree::new("capwatch");
tree.package("b.sv", "b");
tree.package("a.sv", "a");
tree.package("skipped/c.sv", "c");
fat_package(&tree, "d.sv", "d_pkg", 4096);
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings {
exclude: vec!["skipped".to_string()],
max_file_size: 1024,
..Default::default()
});
let mut seen: Vec<(usize, usize, PathBuf)> = Vec::new();
ws.open_whole_workspace_with(vec![tree.path.clone()], &mut |event| {
if let IndexEvent::Parsing { done, total, path } = event {
seen.push((done, total, path.to_path_buf()));
}
});
assert_eq!(
seen,
vec![(0, 2, tree.path.join("a.sv")), (1, 2, tree.path.join("b.sv")),],
"sorted, excluded and capped files absent, total known from the first event"
);
assert_eq!(ws.index().files().len(), 2, "and the index holds exactly those");
}
#[test]
fn the_default_cap_changes_nothing_about_the_real_corpus() {
// The cap ships on, so the burden is to show it costs an existing
// project nothing: the index the default cap builds over `corpus/`
// must be the one no cap at all builds. It is — the largest corpus
// file is 94 KB, eleven times under the cap — and this test is what
// notices if a future corpus, or a future default, changes that.
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut capped = Workspace::default();
capped.open_whole_workspace(vec![corpus.clone()]);
let mut uncapped = Workspace::default();
uncapped.set_client_settings(capping(0));
uncapped.open_whole_workspace(vec![corpus]);
assert_eq!(capped.index().files(), uncapped.index().files(), "the same files, in order");
assert_eq!(capped.index().counts(), uncapped.index().counts(), "and the same index");
assert!(capped.index().files().len() > 500, "premise: the corpus was really scanned");
}
#[test]
fn a_filelist_change_asks_for_a_rescan_too() {
// It changes which files exist as far as this server is concerned,
// which is the whole test for whether a rescan is owed.
let mut ws = Workspace::default();
assert!(ws.set_client_settings(using_filelist("files.f")), "a new filelist rescans");
assert!(!ws.set_client_settings(using_filelist("files.f")), "the same one does not");
assert!(ws.set_client_settings(using_filelist("other.f")), "a different one does");
assert!(ws.set_client_settings(ClientSettings::default()), "and so does clearing it");
}
#[test]
fn the_pushed_settings_are_readable_where_formatting_needs_them() {
let mut ws = Workspace::default();
assert_eq!(ws.client_settings(), &ClientSettings::default(), "default until pushed");
ws.set_client_settings(ClientSettings {
line_length: Some(120),
indent: Some(4),
..Default::default()
});
assert_eq!(ws.client_settings().indent, Some(4));
assert_eq!(ws.client_settings().line_length, Some(120));
}
/// `lucisv.filelist` as a client would push it.
fn using_filelist(path: &str) -> ClientSettings {
ClientSettings { filelist: Some(path.to_string()), ..Default::default() }
}
/// A tree with three packages, one of which a filelist deliberately omits.
fn filelist_tree(name: &str) -> Tree {
let tree = Tree::new(name);
tree.package("rtl/a.sv", "a");
tree.package("rtl/b.sv", "b");
tree.package("rtl/unlisted.sv", "unlisted");
tree.write("files.f", "// the project\nrtl/a.sv\nrtl/b.sv\n");
tree
}
/// What the index holds, as the names of the packages it found.
fn indexed(ws: &Workspace, names: &[&str]) -> Vec<String> {
names
.iter()
.filter(|n| ws.index().member(n, "K").len() == 1)
.map(|n| n.to_string())
.collect()
}
#[test]
fn a_configured_filelist_defines_the_index_exactly() {
// The point of a filelist: a file sitting in the tree that the project
// does not build is not indexed, however much the walk would find it.
let tree = filelist_tree("filelistkey");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut ws = Workspace::default();
let warnings = ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b"]);
assert!(warnings.is_empty(), "{warnings:?}");
}
#[test]
fn the_filelist_setting_beats_the_config_key_and_may_be_absolute() {
let tree = filelist_tree("filelistsetting");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
tree.write("other.f", "rtl/unlisted.sv\n");
// Relative: against the workspace root, not the current directory.
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("other.f"));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["unlisted"], "the setting wins");
// Absolute: taken as written.
let absolute = tree.path.join("other.f");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist(&absolute.display().to_string()));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["unlisted"]);
}
#[test]
fn a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so() {
// The failure that must never happen: an empty index and no
// explanation because a path in a settings UI has a typo.
let tree = filelist_tree("filelistgone");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("typo.f"));
let warnings = ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b", "unlisted"], "the walk ran");
assert_eq!(warnings.len(), 1);
assert!(warnings[0].contains("typo.f"), "{warnings:?}");
assert!(warnings[0].contains("indexing the workspace instead"), "{warnings:?}");
}
#[test]
fn a_filelists_own_warnings_reach_the_caller() {
let tree = filelist_tree("filelistwarn");
tree.write("files.f", "rtl/a.sv\nrtl/moved.sv\n-nonsense\n");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
let warnings = ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a"], "the rest is still indexed");
assert_eq!(warnings.len(), 2, "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("moved.sv")), "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("-nonsense")), "{warnings:?}");
}
#[test]
fn an_open_buffer_is_indexed_even_when_the_filelist_omits_it() {
// Open buffers overlay every rung of the ladder: a scratch file the
// project does not build still gets its own symbols.
let tree = filelist_tree("filelistbuffer");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
ws.open_roots(vec![tree.path.clone()]);
let path = tree.path.join("rtl/unlisted.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package unlisted;\n localparam K = 1;\nendpackage\n".into());
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b", "unlisted"]);
}
#[test]
fn with_no_workspace_root_the_open_files_own_directory_is_indexed() {
// The single-file case: no folder was opened, so the scope is what
// sits beside the buffer — and nothing below it.
let tree = Tree::new("noroot");
tree.package("rtl/open.sv", "open_pkg");
tree.package("rtl/sibling.sv", "sibling");
tree.package("rtl/deeper/below.sv", "below");
tree.package("elsewhere/far.sv", "far");
let mut ws = Workspace::default();
assert!(!ws.has_roots(), "the premise: no workspace folder");
let path = tree.path.join("rtl/open.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package open_pkg;\n localparam K = 1;\nendpackage\n".into());
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["open_pkg", "sibling", "below", "far"]),
["open_pkg", "sibling"],
"the buffer and its neighbours only"
);
}
#[test]
fn a_filelist_still_wins_when_there_is_no_workspace_root() {
let tree = filelist_tree("norootfilelist");
let mut ws = Workspace::default();
// With no root a relative setting cannot be anchored, so an absolute
// path is the only sensible way to name one — and it works.
ws.set_client_settings(using_filelist(&tree.path.join("files.f").display().to_string()));
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b"]);
}
/// Where `ws` would look for `` `include "<name>" `` written in `from`.
fn resolved_include(ws: &Workspace, from: &Path, name: &str) -> Option<PathBuf> {
let text = format!("`include \"{name}\"\n");
let include = crate::includes::scan(&text).into_iter().next().expect("one include");
ws.includes().resolve(Some(from), &include)
}
/// A tree whose filelist names one `+incdir+` and nests a filelist naming
/// another, with a header in each — plus one only the nested incdir holds.
fn incdir_tree(name: &str) -> Tree {
let tree = Tree::new(name);
tree.package("rtl/a.sv", "a");
tree.write("first/defs.svh", "`define W 1\n");
tree.write("ip/include/defs.svh", "`define W 2\n");
tree.write("ip/include/ip_only.svh", "`define X 1\n");
tree.write("ip/ip.f", "+incdir+include\n");
tree.write("files.f", "+incdir+first\n-f ip/ip.f\nrtl/a.sv\n");
tree
}
#[test]
fn a_filelists_incdirs_reach_the_include_graph_in_filelist_order() {
// M1 recorded `+incdir+` and used it for nothing; this is the wire
// that spends it. A nested `-f`'s incdirs come through flattened,
// *after* the ones named before the `-f` — which is the order an
// include is searched in, so it is worth pinning here and not only in
// the parser.
let tree = incdir_tree("incdirs");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
let warnings = ws.open_roots(vec![tree.path.clone()]);
assert!(warnings.is_empty(), "{warnings:?}");
let from = tree.path.join("rtl/a.sv");
assert_eq!(
resolved_include(&ws, &from, "defs.svh"),
Some(tree.path.join("first/defs.svh")),
"the root filelist's incdir is searched before the nested one's"
);
assert_eq!(
resolved_include(&ws, &from, "ip_only.svh"),
Some(tree.path.join("ip/include/ip_only.svh")),
"and the nested one is searched at all"
);
}
#[test]
fn without_a_filelist_there_are_no_incdirs_at_all() {
// Rungs 2 and 3 of the ladder name no include path, so an `` `include``
// there has only the including file's own directory to go on.
let tree = incdir_tree("noincdirs");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(resolved_include(&ws, &tree.path.join("rtl/a.sv"), "defs.svh"), None);
}
#[test]
fn a_broken_filelist_leaves_the_include_graph_without_incdirs() {
let tree = incdir_tree("badfilelistincdirs");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("typo.f"));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(
resolved_include(&ws, &tree.path.join("rtl/a.sv"), "defs.svh"),
None,
"the walk fallback names no include path"
);
}
#[test]
fn the_scan_takes_only_source_extensions() {
let tree = Tree::new("extensions");
tree.package("a.sv", "a");
tree.package("b.v", "b");
tree.package("c.svh", "c");
tree.package("d.vh", "d");
tree.package("e.txt", "e");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
for name in ["a", "b", "c", "d"] {
assert_eq!(ws.index().member(name, "K").len(), 1, "{name} is a source file");
}
assert_eq!(ws.index().member("e", "K").len(), 0, "a .txt is not");
}
// ------------------------------------------------------------------
// The folder scope (index-scope, 2026-08-27)
// ------------------------------------------------------------------
/// A project laid out the way the owner described it: the file being
/// worked on in `rtl/`, a header folder beside it, and a third folder that
/// has nothing to do with either.
fn two_folder_tree(name: &str) -> Tree {
let tree = Tree::new(name);
tree.package("rtl/open.sv", "open_pkg");
tree.package("rtl/beside.sv", "beside_pkg");
tree.package("rtl/deeper/below.sv", "below_pkg");
tree.package("include/defs.sv", "defs_pkg");
tree.package("elsewhere/far.sv", "far_pkg");
tree
}
/// Open `rel` in `ws` as the buffer it is on disk.
fn open(ws: &mut Workspace, tree: &Tree, rel: &str) {
let path = tree.path.join(rel);
let text = fs::read_to_string(&path).expect("the fixture is on disk");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, text);
}
/// The four fixture packages, as the ones that are in the index.
fn scoped(ws: &Workspace) -> Vec<String> {
indexed(ws, &["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"])
}
#[test]
fn the_default_scope_is_the_open_files_own_folder_and_everything_under_it() {
// The headline of this round: a workspace root is open, but the index
// covers the folder the user is working in, not the project.
let tree = two_folder_tree("scopedefault");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert!(scoped(&ws).is_empty(), "premise: nothing is open, so nothing is in scope");
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg"],
"the buffer's own folder and its subtree — and no sibling folder"
);
}
#[test]
fn a_scope_depth_of_one_reaches_the_folder_beside_it() {
// `rtl/` plus `../include`: the layout the setting exists for.
let tree = two_folder_tree("scopedepth");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 1, ..Default::default() });
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"],
"one level up is the whole tree here, sibling folders included"
);
}
#[test]
fn the_climb_stops_at_the_workspace_root() {
// The clamp that keeps a depth of 99 in a two-deep project from
// indexing the user's home directory. Asserted on the directories
// themselves rather than on an index, because the failure this guards
// against is a walk that should never be started.
let tree = two_folder_tree("scopeclamp");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 99, ..Default::default() });
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/deeper/below.sv");
assert_eq!(ws.scope_dirs(), vec![tree.path.clone()], "clamped at the root, not above it");
// The deepest containing root wins, so a nested root clamps tighter.
assert!(ws.change_roots(vec![tree.path.join("rtl")], &[]));
assert_eq!(ws.scope_dirs(), vec![tree.path.join("rtl")], "the deepest root is the floor");
}
#[test]
fn a_rootless_climb_stops_at_the_filesystem_root() {
// With no workspace folder there is nothing to clamp against, so the
// only floor left is `/` — the setting means exactly what it says, and
// the loop terminates there rather than spinning. Stated in the
// feature README as the reason to leave `scopeDepth` at 0 in a
// rootless session. No index is built here: the point is that the
// climb stops, and walking `/` is precisely what a test must not do.
let tree = two_folder_tree("scoperootless");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 99, ..Default::default() });
open(&mut ws, &tree, "rtl/open.sv");
assert!(!ws.has_roots(), "the premise: no workspace folder to clamp against");
assert_eq!(ws.scope_dirs(), vec![PathBuf::from("/")], "it climbs to the root and stops");
}
#[test]
fn a_rootless_session_that_raises_the_depth_walks_instead_of_reading_one_level() {
// The one exception in `folder_files`, from the other side: at depth 0
// a rootless session reads its directories flat (pinned by
// `with_no_workspace_root_the_open_files_own_directory_is_indexed`,
// unchanged this round), and the moment the user raises the depth they
// have named a tree, so it is walked.
let tree = two_folder_tree("scoperootlesswalk");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 1, ..Default::default() });
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"],
"raised one level and walked from there"
);
}
#[test]
fn the_workspace_scope_setting_restores_the_walk_of_every_root() {
// The migration line in the README, pinned: with `scope: "workspace"`
// the index is the whole tree with no buffer open at all — which is
// exactly what this fixture gave before this round.
let tree = two_folder_tree("scopewide");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings {
index_scope: IndexScope::Workspace,
..Default::default()
});
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"],
"every file under the root, no buffer needed"
);
// And the depth is not consulted at all on that rung.
let mut raised = Workspace::default();
raised.set_client_settings(ClientSettings {
index_scope: IndexScope::Workspace,
index_scope_depth: 3,
..Default::default()
});
raised.open_roots(vec![tree.path.clone()]);
assert_eq!(raised.index().files(), ws.index().files(), "the depth changes nothing here");
}
#[test]
fn a_filelist_still_defines_the_scope_exactly_whatever_the_folder_rung_would_say() {
// Rung 1 outranks rung 3 as it always outranked rung 2: the filelist
// is the project file, and it names files in folders no buffer has
// been opened from.
let tree = two_folder_tree("scopefilelist");
tree.write("files.f", "include/defs.sv\nelsewhere/far.sv\n");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "defs_pkg", "far_pkg"],
"the filelist, plus the open buffer that overlays every rung"
);
assert!(ws.scope_dirs().is_empty(), "and no `didOpen` can widen a filelist");
}
#[test]
fn closing_a_file_never_narrows_the_scope() {
// The decision, pinned: the scope only grows within a session. A
// rebuild after a close must not take away answers the user had a
// moment ago, and no `didClose` costs a rescan.
let tree = two_folder_tree("scopeclose");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() });
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
open(&mut ws, &tree, "include/defs.sv");
ws.rebuild_index();
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg", "defs_pkg"]);
let closed = crate::uri::path_to_uri(&tree.path.join("include/defs.sv")).expect("uri");
ws.close_document(&closed);
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg"],
"the closed file's folder is still indexed"
);
}
#[test]
fn the_folder_scope_honours_every_exclude_and_the_gitignores_below_it() {
// Rung 3 walks with the same function rung 2 walks with, so nothing a
// user excluded comes back because the scope narrowed — with **one
// honest exception**, pinned here rather than left to be discovered:
// `lucisv_core`'s walk reads `.gitignore` files from its own starting
// directory downwards, so a rule written at the workspace root does
// not reach a walk that starts below it. The `exclude` patterns are
// matched against whole paths and are unaffected either way. Stated in
// `walked_files` and in `docs/features/index-scope/README.md`.
let tree = Tree::new("scopefilters");
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
tree.write(".gitignore", "generated/\n");
tree.write("rtl/.gitignore", "dumps/\n");
tree.package("rtl/open.sv", "open_pkg");
tree.package("rtl/vendor/ip.sv", "vendor_pkg");
tree.package("rtl/dumps/net.sv", "dumps_pkg");
tree.package("rtl/generated/net.sv", "generated_pkg");
tree.package("rtl/scratch/wip.sv", "scratch_pkg");
let names = &["open_pkg", "vendor_pkg", "dumps_pkg", "generated_pkg", "scratch_pkg"];
let mut ws = Workspace::default();
ws.set_client_settings(excluding(&["scratch"]));
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
indexed(&ws, names),
["open_pkg", "generated_pkg"],
"both excludes and the .gitignore inside the scope applied; the one at the \
root, above where this walk starts, did not"
);
// ...and the wide scope, whose walk starts at the root, does apply it.
let mut wide = Workspace::default();
wide.set_client_settings(ClientSettings {
exclude: vec!["scratch".to_string()],
index_scope: IndexScope::Workspace,
..Default::default()
});
wide.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&wide, names), ["open_pkg"], "everything filtered, from the root");
}
#[test]
fn a_folder_added_mid_session_widens_nothing_until_a_file_in_it_is_opened() {
// The interaction between the two ways a scope can move. Under the
// folder rung a workspace folder is a *clamp*, not a work list, so
// adding one changes which files exist only once a buffer in it makes
// it a scope directory.
let first = Tree::new("scopefolderfirst");
first.package("a.sv", "a");
let second = Tree::new("scopefoldersecond");
second.package("b.sv", "b");
let mut ws = Workspace::default();
ws.open_roots(vec![first.path.clone()]);
open(&mut ws, &first, "a.sv");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "premise: the first folder's file");
assert!(ws.change_roots(vec![second.path.clone()], &[]), "the root set moved");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "but no buffer lives there yet");
open(&mut ws, &second, "b.sv");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"], "opening one widens the scope");
}
#[test]
fn a_scope_or_a_depth_change_asks_for_a_rescan() {
// Both change which files exist, so both join `exclude`, `filelist`
// and the size cap in the rescan test.
let mut ws = Workspace::default();
let wide = ClientSettings { index_scope: IndexScope::Workspace, ..Default::default() };
assert!(ws.set_client_settings(wide.clone()), "a new scope rescans");
assert!(!ws.set_client_settings(wide.clone()), "the same one does not");
assert!(ws.set_client_settings(ClientSettings::default()), "and going back does");
let deep = ClientSettings { index_scope_depth: 2, ..Default::default() };
assert!(ws.set_client_settings(deep.clone()), "a new depth rescans");
assert!(!ws.set_client_settings(deep), "the same one does not");
assert!(ws.set_client_settings(ClientSettings::default()), "and going back does");
}
#[test]
fn the_open_files_are_indexed_first_and_the_index_cannot_tell() {
// Two halves of one claim. First: the progress events name the open
// buffers before anything else, which is what makes a big rescan feel
// like it is working on the user's own files.
let tree = Tree::new("scopeorder");
tree.package("rtl/a_first.sv", "a_first");
tree.package("rtl/m_open.sv", "m_open");
tree.package("rtl/z_last.sv", "z_last");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/m_open.sv");
let mut seen: Vec<PathBuf> = Vec::new();
ws.rebuild_index_with(&mut |event| {
if let IndexEvent::Parsing { path, .. } = event {
seen.push(path.to_path_buf());
}
});
assert_eq!(
seen,
vec![
tree.path.join("rtl/m_open.sv"),
tree.path.join("rtl/a_first.sv"),
tree.path.join("rtl/z_last.sv"),
],
"the open buffer first, then the rest in path order"
);
// Second, and the reason the first is allowed to be true: the index
// is byte-identical to the one the plain path order builds. The
// builder sorts inside `finish`, so the order above is a reporting
// decision and nothing more (`vlog_semantic`'s
// `no_insertion_order_can_change_what_the_builder_produces` is the
// other end of this).
let mut plain = Workspace::default();
plain.set_client_settings(ClientSettings {
index_scope: IndexScope::Workspace,
..Default::default()
});
plain.open_roots(vec![tree.path.clone()]);
assert_eq!(ws.index().files(), plain.index().files(), "same files, same ids");
assert_eq!(ws.index().counts(), plain.index().counts(), "and the same index");
}
// ------------------------------------------------------------------
// The incremental path (incremental-index, 2026-08-27)
// ------------------------------------------------------------------
#[test]
fn only_a_file_the_index_already_holds_takes_the_incremental_path() {
// The whole gate, from both sides. A file the index holds is one the
// update can replace; anything else is a rebuild's business, because a
// file appearing changes what *other* files' includes resolve to.
let tree = Tree::new("incrgate");
tree.package("rtl/a.sv", "a_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(ws.update_one_checked(&tree.path.join("rtl/a.sv")), "a file the index holds");
assert!(!ws.update_one(&tree.path.join("rtl/new.sv")), "a file it does not");
assert!(!ws.update_one(&tree.path.join("rtl/a.txt")), "and a path it never would");
// A file that appears is exactly the "not held" case, and stays so
// until something rebuilds.
tree.package("rtl/new.sv", "new_pkg");
assert!(!ws.update_one(&tree.path.join("rtl/new.sv")), "still not held");
ws.rebuild_index();
assert!(ws.update_one_checked(&tree.path.join("rtl/new.sv")), "held now");
}
#[test]
fn one_files_edit_reaches_every_table_the_index_answers_from() {
// The four pieces of derived state a rebuild produces, checked one by
// one after an update that moves all four: a declaration, an
// instantiation edge, an inheritance edge, a completion word and an
// `` `include`` edge.
let tree = Tree::new("incrtables");
tree.write("rtl/defs.svh", "`define W 8\n");
tree.write("rtl/sub.sv", "module sub;\nendmodule\nclass base;\nendclass\n");
tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule top;\n sub u1 ();\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let top = tree.path.join("rtl/top.sv");
assert_eq!(ws.index().instantiations_of("sub").len(), 1, "premise: one site");
assert_eq!(
ws.includes().reachable(vec![top.clone()]).len(),
2,
"premise: top.sv reaches defs.svh"
);
assert_eq!(ws.candidates().words("u1").len(), 1, "premise: the instance name is a word");
fs::write(
&top,
"module top;\n logic renamed_wire;\nendmodule\nclass leaf extends base;\nendclass\n",
)
.expect("write");
assert!(ws.update_one_checked(&top));
assert!(ws.index().instantiations_of("sub").is_empty(), "the site went");
assert_eq!(ws.index().subclasses_of("base").len(), 1, "and an inheritance edge came");
assert!(ws.candidates().words("u1").is_empty(), "the old word was given back");
assert_eq!(ws.candidates().words("renamed_wire").len(), 1, "the new one taken");
assert_eq!(ws.includes().reachable(vec![top]).len(), 1, "the include edge went too");
}
#[test]
fn a_file_the_cap_or_the_disk_takes_away_leaves_the_index() {
let tree = Tree::new("incrremove");
tree.package("rtl/keep.sv", "keep_pkg");
tree.package("rtl/gone.sv", "gone_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["keep_pkg", "gone_pkg"]).len(), 2, "premise");
// Deleted on disk: the update is a removal.
let gone = tree.path.join("rtl/gone.sv");
fs::remove_file(&gone).expect("remove");
assert!(ws.update_one_checked(&gone), "a held file, even a vanished one");
assert_eq!(indexed(&ws, &["keep_pkg", "gone_pkg"]), ["keep_pkg"]);
// And a file that grew past the cap is the same answer for the same
// reason: it is not a file this server reads any more.
let mut ws = Workspace::default();
let tree = Tree::new("incrcap");
tree.package("rtl/keep.sv", "keep_pkg");
fat_package(&tree, "rtl/netlist.sv", "netlist_pkg", 4096);
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["keep_pkg", "netlist_pkg"]).len(), 2, "premise: under no cap");
ws.set_client_settings(wide(capping(1024)));
assert!(ws.update_one_checked(&tree.path.join("rtl/netlist.sv")));
assert_eq!(indexed(&ws, &["keep_pkg", "netlist_pkg"]), ["keep_pkg"], "the cap took it");
}
#[test]
fn an_open_buffer_beats_disk_on_the_incremental_path_too() {
let tree = Tree::new("incrbuffer");
tree.package("rtl/a.sv", "a_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let path = tree.path.join("rtl/a.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(
uri,
"package buffered_pkg;\n localparam K = 1;\nendpackage\n".to_string(),
);
assert!(ws.update_one_checked(&path));
assert_eq!(
indexed(&ws, &["a_pkg", "buffered_pkg"]),
["buffered_pkg"],
"the buffer's text, not the file's"
);
}
#[test]
fn the_incremental_update_agrees_with_a_whole_rebuild_over_the_real_corpus() {
// The paranoid sweep: take real files out of a real workspace, put a
// mutated version back through the incremental path, and check the
// result against a whole rebuild every time. `update_one_checked` is
// what does the checking; this test is the corpus it does it over.
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
// Copied into a scratch tree, because the sweep rewrites files. Every
// fifth file: `update_one_checked` rebuilds the whole workspace to
// check itself, so the sweep costs a full rebuild per mutation and a
// third of the corpus is still hundreds of real files.
let tree = Tree::new("incrcorpus");
let mut copied = 0;
let mut sample: Vec<PathBuf> = Vec::new();
for (n, source) in walk_sources(&corpus).into_iter().step_by(5).enumerate() {
let Ok(text) = fs::read_to_string(&source) else { continue };
let rel = format!("f{n:04}.sv");
tree.write(&rel, &text);
copied += 1;
if n % 31 == 0 {
sample.push(tree.path.join(&rel));
}
}
assert!(copied > 100, "premise: the corpus was really copied ({copied} files)");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(sample.len() > 5, "a sample worth sweeping: {}", sample.len());
for path in &sample {
let text = fs::read_to_string(path).expect("the copy is on disk");
// Four shapes of edit, each checked against a whole rebuild.
assert!(ws.update_one_checked(path), "unchanged");
fs::write(
path,
format!("{text}\nmodule qa_added_module;\n qa_added_sub u1 ();\nendmodule\n"),
)
.expect("write");
assert!(ws.update_one_checked(path), "a declaration and an edge added");
fs::write(path, "class qa_leaf extends qa_base;\nendclass\n").expect("write");
assert!(ws.update_one_checked(path), "replaced wholesale");
fs::write(path, "").expect("write");
assert!(ws.update_one_checked(path), "emptied");
fs::remove_file(path).expect("remove");
assert!(ws.update_one_checked(path), "removed");
}
eprintln!("paranoid sweep: {copied} files, {} of them mutated five ways", sample.len());
}
/// Every source file under `dir`, for the corpus sweep above.
fn walk_sources(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
let mut stack = vec![dir.to_path_buf()];
while let Some(next) = stack.pop() {
let Ok(entries) = fs::read_dir(&next) else { continue };
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
stack.push(path);
} else if matches!(
path.extension().and_then(|e| e.to_str()),
Some("sv" | "v" | "svh")
) {
out.push(path);
}
}
}
out.sort();
out
}
/// What one file's rescan costs on the incremental path, against the whole
/// rebuild it replaces, over the real corpus.
///
/// `#[ignore]`d like the crate's other measurement probes: it prints
/// numbers rather than asserting one. The numbers themselves are in
/// `docs/features/incremental-index/README.md`.
#[test]
#[ignore]
fn qa_perf_one_file_against_the_whole_rebuild() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus]);
let files = ws.index().files().len();
let one = ws.index().files().last().cloned().expect("a file");
let mut whole = std::time::Duration::MAX;
let mut single = std::time::Duration::MAX;
for _ in 0..3 {
let started = std::time::Instant::now();
ws.rebuild_index();
whole = whole.min(started.elapsed());
let started = std::time::Instant::now();
assert!(ws.update_one(&one));
single = single.min(started.elapsed());
}
eprintln!(
"reindex over {files} files: whole rebuild {whole:?}, one file {single:?} \
({:.0}x)",
whole.as_secs_f64() / single.as_secs_f64().max(f64::MIN_POSITIVE)
);
}
// ------------------------------------------------------------------
// Inherited obligations (index-scope Review, 2026-08-27)
// ------------------------------------------------------------------
#[test]
fn lowering_the_scope_depth_narrows_the_index_on_the_next_rescan() {
// The scope grows only along the *open* axis — a `didClose` never
// narrows it. A settings change is the other axis and moves both ways,
// because it is a deliberate statement about how much of this machine's
// time to spend. Verified by hand by the previous round's QA; pinned
// here.
let tree = two_folder_tree("depthdown");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 1, ..Default::default() });
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert!(scoped(&ws).contains(&"defs_pkg".to_string()), "premise: depth 1 reaches beside");
assert!(
ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() }),
"lowering the depth asks for a rescan"
);
ws.rebuild_index();
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg"], "narrowed, not kept");
}
#[test]
fn a_filelist_appearing_mid_session_flips_the_ladder_to_rung_one() {
// Not just "asks for a rescan" — that the index really becomes the
// filelist's files, from a folder scope that was covering something
// else entirely.
let tree = two_folder_tree("filelistmid");
tree.write("files.f", "elsewhere/far.sv\n");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg"],
"premise: the folder rung"
);
assert!(ws.set_client_settings(using_filelist("files.f")), "a rescan is owed");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "far_pkg"],
"rung 1 defines the scope exactly — plus the open buffer, which overlays every rung"
);
}
#[test]
fn a_buffer_opened_outside_every_root_rides_the_folder_rung_like_a_rootless_one() {
// `raised()`'s floor is the deepest root *containing* the directory, and
// there is none here — so the climb stops at `/`, exactly as it does
// with no root at all. Verified by hand by the previous round's QA;
// pinned here, on the directories rather than by walking one.
let inside = Tree::new("outsideroot_in");
inside.package("rtl/a.sv", "a_pkg");
let outside = Tree::new("outsideroot_out");
outside.package("other/b.sv", "b_pkg");
let mut ws = Workspace::default();
ws.open_roots(vec![inside.path.clone()]);
open(&mut ws, &outside, "other/b.sv");
assert_eq!(
ws.scope_dirs(),
vec![outside.path.join("other")],
"at depth 0 it is the buffer's own directory and nothing else"
);
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["a_pkg", "b_pkg"]),
["b_pkg"],
"the root's own tree is not in it"
);
ws.set_client_settings(ClientSettings { index_scope_depth: 99, ..Default::default() });
assert_eq!(
ws.scope_dirs(),
vec![PathBuf::from("/")],
"and with nothing to clamp against the climb stops at the filesystem root"
);
}
// ------------------------------------------------------------------
// 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());
}
}