Index scope: open-file-first, folder-scoped by default

Owner-requested round. The scope ladder: a filelist still defines the
whole project and outranks everything; lucisv.index.scope=workspace
restores the walk-the-roots behavior (the same function, not an
equal-output one — pinned); the new default walks only the union of
folders a buffer has been opened from, each raised
lucisv.index.scopeDepth ancestor levels (default 0), clamped at the
deepest containing root. Opening a file outside the scope widens it
and reindexes through the existing progress/generation machinery;
scope grows only along the open axis within a session. Cross-file
answers are scope-relative and the docs say so loudly, with the
one-line migration in the setting description.

The round also closes indexing-ux QA's MEDIUM builder footgun:
IndexBuilder::finish now sorts and dedups before assigning FileIds, so
no insertion order can reach the result — pinned by a permanent
three-order fingerprint test — which makes feeding open files first
provably a progress nicety. 151 existing tests swept mechanically
(QA sampled 40+ sites: constructor swaps only); lead fixed the one
vacuous tail QA found plus two premise/comment hygiene items.

19 tests added. Known deltas documented: a root's .gitignore does not
reach a walk starting below it (filed against lucisv_core); rootless
depth-0 keeps its flat read; startup index is empty until the first
didOpen.

docs/features/index-scope/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-27 13:12:27 -07:00
1 parent 8c8cfc538e
commit 7266b13702
27 files changed
+2008 -270

No files matched your search

+4 -1
View File
@@ -591,7 +591,10 @@ section only tracks the milestones.
- [x] **M1 `filelist`** — EDA `.f` filelist defines the index scope
(`-f` nesting, `+incdir+`/`+define+` recorded, env vars); fallback:
workspace walk, then current file's directory when rootless.
~~workspace walk, then current file's directory when rootless~~
**the open files' own folders since 2026-08-27 (index-scope), with the
workspace walk behind `lucisv.index.scope: "workspace"`; the filelist
still outranks both. See `docs/features/index-scope/README.md`.**
- [x] **M2 `refactor-rename`** — new crate `vlog_refactor`; LSP
`prepareRename`/`rename` for every symbol kind `vlog_semantic` resolves,
cross-file, whole-edit-or-nothing verified by re-parse.
+3 -3
View File
@@ -948,7 +948,7 @@ endmodule
) -> (Tree, Workspace, Uri, Position) {
let path = tree.write(file, top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = (top.find(needle).expect("needle present") + needle.len()) as u32;
@@ -1683,7 +1683,7 @@ endmodule
filelist: Some("files.f".to_string()),
..Default::default()
});
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
ws.rebuild_index();
@@ -1731,7 +1731,7 @@ endmodule
}
let started = std::time::Instant::now();
let mut ws = Workspace::default();
ws.open_roots(vec![corpus.clone()]);
ws.open_whole_workspace(vec![corpus.clone()]);
let build = started.elapsed();
// A buffer that is not on disk: it overlays the walk, so the corpus is
+3 -3
View File
@@ -520,7 +520,7 @@ mod tests {
..Default::default()
});
}
ws.open_roots(vec![self.path.clone()]);
ws.open_whole_workspace(vec![self.path.clone()]);
ws
}
@@ -1055,7 +1055,7 @@ mod tests {
// same read the index rebuild already pays on every save.
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
let mut ws = Workspace::default();
ws.open_roots(vec![root.clone()]);
ws.open_whole_workspace(vec![root.clone()]);
let files = ws.index().files().len();
assert!(files > 500, "the corpus is checked in: got {files}");
let rename = FileRename {
@@ -1401,7 +1401,7 @@ mod tests {
let new = target_dir.join("prim_assert_renamed.sv");
let mut ws = Workspace::default();
ws.open_roots(vec![root.clone()]);
ws.open_whole_workspace(vec![root.clone()]);
let rename = FileRename { old_uri: uri_of(&old), new_uri: uri_of(&new) };
let run = || {
+4 -4
View File
@@ -335,7 +335,7 @@ mod tests {
}
}
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let (path, text) = first.expect("at least one file");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -527,7 +527,7 @@ endmodule
tree.write("files.f", "sub.sv\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
@@ -945,7 +945,7 @@ endmodule
return;
}
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let item = CallHierarchyItem {
name: "d".to_string(),
kind: SymbolKind::MODULE,
@@ -993,7 +993,7 @@ endmodule
return;
};
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&declaring).expect("uri");
ws.set_document(uri.clone(), text.clone());
let root = prepare(&ws, &uri, at(&text, "module prim_flop_2sync") + 7)
+6 -6
View File
@@ -399,7 +399,7 @@ mod tests {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
@@ -421,7 +421,7 @@ mod tests {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
@@ -440,7 +440,7 @@ mod tests {
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let top = dir.join("top.sv");
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), fs::read_to_string(&top).expect("read"));
@@ -582,7 +582,7 @@ mod tests {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
@@ -641,7 +641,7 @@ mod qa_findings {
filelist: Some(dir.join("files.f").display().to_string()),
..Default::default()
});
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
@@ -695,7 +695,7 @@ mod qa_findings {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
+2 -2
View File
@@ -541,7 +541,7 @@ mod tests {
filelist: Some(tree.path.join("files.f").display().to_string()),
..Default::default()
});
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let path = tree.path.join(rel);
let uri = path_to_uri(&path).expect("uri");
let text = fs::read_to_string(&path).expect("read");
@@ -735,7 +735,7 @@ mod qa_scope_probe {
filelist: Some(dir.join("files.f").display().to_string()),
..Default::default()
});
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), fs::read_to_string(&top).expect("read"));
+5 -5
View File
@@ -280,7 +280,7 @@ endmodule
}
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
inlay_hints(&ws, &uri, range)
@@ -321,7 +321,7 @@ endmodule
let top = "module top;\n sub u1 (clk);\nendmodule\n";
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let hints = inlay_hints(&ws, &uri, everything());
@@ -708,7 +708,7 @@ endmodule
let top = "module top;\n sub u1 (clk, rst_n, data);\nendmodule\n";
let top_path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let sub_uri = path_to_uri(&sub_path).expect("uri");
let top_uri = path_to_uri(&top_path).expect("uri");
ws.set_document(top_uri.clone(), top.to_string());
@@ -758,7 +758,7 @@ endmodule
top.push_str("endmodule\n");
let path = tree.write("top.sv", &top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.clone());
let screen = Range {
@@ -793,7 +793,7 @@ endmodule
top.push_str("endmodule\n");
let path = tree.write("top.sv", &top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.clone());
let _ = inlay_hints(&ws, &uri, everything());
+4 -4
View File
@@ -179,7 +179,7 @@ mod tests {
}
}
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let (path, text) = first.expect("at least one file");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -505,7 +505,7 @@ endmodule
return;
};
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text);
let lenses = code_lenses(&ws, &uri).expect("open");
@@ -567,7 +567,7 @@ endmodule
tree_b.write("a/m.sv", m_a);
let path_b = tree_b.write("b/m.sv", m_b);
tree_b.write("top.sv", user);
ws_b.open_roots(vec![tree_b.path.clone()]);
ws_b.open_whole_workspace(vec![tree_b.path.clone()]);
let uri_b = path_to_uri(&path_b).expect("uri");
ws_b.set_document(uri_b.clone(), m_b.to_string());
assert_eq!(
@@ -663,7 +663,7 @@ endmodule
return;
};
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text);
+8 -8
View File
@@ -309,7 +309,7 @@ mod tests {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
@@ -333,7 +333,7 @@ mod tests {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
@@ -355,7 +355,7 @@ mod tests {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
@@ -386,7 +386,7 @@ mod tests {
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let path = dir.join(which);
let uri = path_to_uri(&path).expect("uri");
let text = fs::read_to_string(&path).expect("read");
@@ -460,7 +460,7 @@ mod tests {
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&dir.join("p.sv")).expect("uri");
ws.set_document(uri.clone(), pkg.to_string());
@@ -489,7 +489,7 @@ mod tests {
fs::write(dir.join("m.sv"), text).expect("write");
fs::write(dir.join("other.sv"), "module other;\n wire a;\nendmodule\n").expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&dir.join("m.sv")).expect("uri");
ws.set_document(uri.clone(), text.to_string());
let doc = ws.document(&uri).expect("open");
@@ -517,7 +517,7 @@ mod tests {
fs::write(dir.join("a.sv"), text).expect("write");
fs::write(dir.join("b.sv"), text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let a_path = dir.join("a.sv");
let uri = path_to_uri(&a_path).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -615,7 +615,7 @@ mod tests {
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
+2 -2
View File
@@ -244,7 +244,7 @@ mod tests {
let sub = tree.write("sub.sv", SUB);
let top = tree.write("top.sv", TOP);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let top_uri = path_to_uri(&top).expect("uri");
let sub_uri = path_to_uri(&sub).expect("uri");
ws.set_document(top_uri.clone(), TOP.to_string());
@@ -323,7 +323,7 @@ mod tests {
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", text);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), text.to_string());
let arguments = vec![
+3 -3
View File
@@ -122,7 +122,7 @@ mod tests {
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", TOP);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), TOP.to_string());
(ws, uri)
@@ -194,7 +194,7 @@ mod tests {
let text = "module m;\n // é 🎉\n wire a;\n assign a = 1;\nendmodule\n";
let file = tree.write("m.sv", text);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -212,7 +212,7 @@ mod tests {
tree.write("sub.sv", SUB);
let top_path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
// The buffer instantiates `sub`; the file on disk does not.
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), TOP.to_string());
+238 -58
View File
@@ -178,10 +178,31 @@ struct TokenAnswer {
}
impl Server {
/// The server, with its first index built.
///
/// The startup scan runs at the **default** settings — including the
/// folder scope — because neither settings door can deliver anything
/// before `initialized`; a client whose `lucisv.index.scope` differs pays
/// one extra rescan when its settings land, exactly as `lucisv.exclude`
/// has always cost one.
pub fn new(
connection: Connection,
roots: Vec<std::path::PathBuf>,
abilities: ClientAbilities,
) -> Server {
Server::started(connection, roots, abilities, ClientSettings::default())
}
/// [`Server::new`] with a client's settings already in hand — the seam the
/// tests start a session from. Only a test has any settings this early:
/// one whose subject is not the scope says so here rather than driving a
/// `didChangeConfiguration` and then reasoning about the extra rescan it
/// buys.
fn started(
connection: Connection,
roots: Vec<std::path::PathBuf>,
abilities: ClientAbilities,
client: ClientSettings,
) -> Server {
let mut server = Server {
connection,
@@ -197,6 +218,10 @@ impl Server {
token_results: 0,
indexings: 0,
};
// Nothing has been built yet, so there is no rebuild to owe: the
// `true` this returns for a non-default `client` is the rebuild that
// is about to happen anyway.
let _ = server.workspace.set_client_settings(client);
// The earliest legal moment for anything server-initiated: `main`
// builds this only after `initialize_finish`, which returns once the
// client's `initialized` notification has arrived — and consumes it,
@@ -1017,12 +1042,21 @@ impl Server {
DidOpenTextDocument::METHOD => {
if let Ok(p) = extract::<DidOpenTextDocumentParams>(notification) {
let uri = p.text_document.uri;
// Opening a file in a folder the index does not cover
// *widens the scope*, so the whole index is rebuilt; the
// rebuild rides the same bar and the same generation bump
// every other rescan trigger does. Opening one the scope
// already covers changes nothing about which files exist,
// and the save path still owns rebuilding.
//
// This is the rootless rule from before 2026-08-27,
// generalized: rung 3 is now the default rung with a root
// too, so "did this file widen the scope" is the one test,
// and it answers "no" for the filelist and whole-workspace
// rungs, which an open buffer cannot widen.
let before = self.workspace.scope_dirs();
self.set_document(uri.clone(), p.text_document.text);
// With no workspace root the index's scope *is* the open
// buffers' own directories, so opening a file widens it.
// With a root, nothing about the scope changed and the
// save path still owns rebuilding.
if self.workspace.has_roots() {
if self.workspace.scope_dirs() == before {
self.publish(&uri);
} else {
self.reindex();
@@ -1848,8 +1882,39 @@ mod tests {
/// A session against a client that said exactly `abilities`.
fn with(roots: Vec<PathBuf>, abilities: ClientAbilities) -> Session {
Session::started(roots, abilities, ClientSettings::default())
}
/// A session whose client had already asked for
/// `lucisv.index.scope: "workspace"` when the startup scan ran — the
/// scope every session had before 2026-08-27.
///
/// Used by every test in this module whose subject is not the scope:
/// they want their whole fixture tree indexed from the first bar, and
/// saying so here keeps the folder scope from being a hidden variable
/// in a test about a progress report or a rename. The folder scope's
/// own behaviour is tested by the tests named in
/// `docs/features/index-scope/README.md`.
fn wide(roots: Vec<PathBuf>, file_watching: bool) -> Session {
Session::wide_with(roots, ClientAbilities { file_watching, ..Default::default() })
}
/// [`Session::wide`] against a client that said exactly `abilities`.
fn wide_with(roots: Vec<PathBuf>, abilities: ClientAbilities) -> Session {
let wide = ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
};
Session::started(roots, abilities, wide)
}
fn started(
roots: Vec<PathBuf>,
abilities: ClientAbilities,
settings: ClientSettings,
) -> Session {
let (server_end, client) = Connection::memory();
let server = Server::new(server_end, roots, abilities);
let server = Server::started(server_end, roots, abilities, settings);
Session { server, client }
}
@@ -2089,7 +2154,7 @@ mod tests {
// `initialize_finish` — the earliest moment a server request is legal.
let tree = Tree::new("progressstartup");
tree.package("rtl/a.sv", "a");
let session = Session::with(vec![tree.path.clone()], watching_progress());
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
// One `report` because the tree holds one file: the counting reports
// this round added ride the same path the begin/end pair does.
assert_eq!(
@@ -2107,7 +2172,7 @@ mod tests {
fn a_save_puts_a_bar_up_and_takes_it_down_again() {
let tree = Tree::new("progresssave");
tree.package("rtl/a.sv", "a");
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
let _ = session.drain();
@@ -2136,12 +2201,12 @@ mod tests {
let tree = Tree::new("progresscount");
tree.package("rtl/a.sv", "a");
tree.package("rtl/b.sv", "b");
let session = Session::with(vec![tree.path.clone()], watching_progress());
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
assert_eq!(session.ended(), vec![Some("2 files indexed".to_string())]);
let one = Tree::new("progresscountone");
one.package("rtl/a.sv", "a");
let session = Session::with(vec![one.path.clone()], watching_progress());
let session = Session::wide_with(vec![one.path.clone()], watching_progress());
assert_eq!(session.ended(), vec![Some("1 file indexed".to_string())], "not `1 files`");
}
@@ -2152,7 +2217,7 @@ mod tests {
let tree = Tree::new("progressreports");
tree.package("rtl/a.sv", "a");
tree.package("rtl/b.sv", "b");
let session = Session::with(vec![tree.path.clone()], watching_progress());
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
assert_eq!(
session.reported(),
vec![
@@ -2173,7 +2238,7 @@ mod tests {
for i in 0..files {
tree.package(&format!("f{i:05}.sv",), &format!("p{i}"));
}
let session = Session::with(vec![tree.path.clone()], watching_progress());
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
let reports = session.reported();
assert!(reports.len() <= MAX_REPORTS, "{} reports for {files} files", reports.len());
assert!(reports.len() > MAX_REPORTS / 2, "but not silence: {}", reports.len());
@@ -2254,8 +2319,17 @@ mod tests {
}
/// The `didChangeConfiguration` push that sets the index size cap.
///
/// It carries `scope: "workspace"` because a push replaces *every*
/// setting: a cap pushed on its own would take the index back to the
/// folder scope in the same breath, which is not what a test about the cap
/// is asking. Same reason `state.rs`'s `wide()` exists.
fn capping(bytes: u64) -> serde_json::Value {
serde_json::json!({ "settings": { "lucisv": { "index": { "maxFileSize": bytes } } } })
serde_json::json!({
"settings": {
"lucisv": { "index": { "maxFileSize": bytes, "scope": "workspace" } }
}
})
}
#[test]
@@ -2264,13 +2338,17 @@ mod tests {
// the only place a user who turned the log off would hear that part of
// their workspace is not indexed.
let tree = oversized_tree("capend");
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
assert_eq!(session.ended(), vec![Some("2 files indexed".to_string())], "premise: no cap");
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({
"settings": { "lucisv": { "index": { "maxFileSize": 1024, "logFiles": false } } }
"settings": {
"lucisv": {
"index": { "maxFileSize": 1024, "logFiles": false, "scope": "workspace" }
}
}
}),
);
assert_eq!(
@@ -2283,7 +2361,7 @@ mod tests {
#[test]
fn a_capped_file_is_out_of_the_index_and_an_open_buffer_is_not() {
let tree = oversized_tree("capserver");
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
session.notify(DidChangeConfiguration::METHOD, capping(1024));
assert_eq!(indexed(&session, "netlist_pkg"), 0, "the big file is not indexed");
assert_eq!(indexed(&session, "keep_pkg"), 1, "and the small one still is");
@@ -2304,7 +2382,7 @@ mod tests {
#[test]
fn every_indexed_file_is_named_in_the_log_and_so_is_every_skip() {
let tree = oversized_tree("caplog");
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
let _ = session.drain();
session.notify(DidChangeConfiguration::METHOD, capping(1024));
@@ -2335,12 +2413,16 @@ mod tests {
#[test]
fn the_file_log_goes_quiet_when_the_setting_is_off() {
let tree = oversized_tree("caplogoff");
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
let _ = session.drain();
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({
"settings": { "lucisv": { "index": { "maxFileSize": 1024, "logFiles": false } } }
"settings": {
"lucisv": {
"index": { "maxFileSize": 1024, "logFiles": false, "scope": "workspace" }
}
}
}),
);
let logged = session.logged();
@@ -2353,7 +2435,7 @@ mod tests {
// which every client gets, and the bar is gated on a capability.
let tree = Tree::new("caplognobar");
tree.package("rtl/a.sv", "a");
let session = Session::new(vec![tree.path.clone()], false);
let session = Session::wide(vec![tree.path.clone()], false);
// One drain, both questions: `Session::drain` consumes.
let messages = session.drain();
assert!(
@@ -2382,7 +2464,7 @@ mod tests {
// narration of the next one.
let tree = Tree::new("caprescan");
tree.package("rtl/a.sv", "a");
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
let _ = session.drain();
session.notify(DidChangeConfiguration::METHOD, capping(4096));
@@ -2394,12 +2476,84 @@ mod tests {
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({
"settings": { "lucisv": { "index": { "maxFileSize": 4096, "logFiles": false } } }
"settings": {
"lucisv": {
"index": { "maxFileSize": 4096, "logFiles": false, "scope": "workspace" }
}
}
}),
);
assert!(session.progress().is_empty(), "and neither does turning the log off");
}
#[test]
fn a_new_index_scope_or_depth_rescans_through_the_real_dispatch() {
// The other two settings that change which files exist. Driven through
// `didChangeConfiguration` rather than `set_client_settings`, because
// the parser, the change test and the rescan are three separate places
// a scope setting could be dropped.
let tree = Tree::new("scoperescan");
tree.package("rtl/a.sv", "a");
tree.package("include/defs.sv", "defs_pkg");
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
let uri = session.open(
&tree.path.join("rtl/a.sv"),
"package a;\n localparam K = 1;\n\
endpackage\n",
);
let _ = (uri, session.drain());
assert_eq!(indexed(&session, "defs_pkg"), 0, "premise: the sibling folder is out of scope");
let scoped = |scope: &str, depth: u32| {
serde_json::json!({
"settings": { "lucisv": { "index": { "scope": scope, "scopeDepth": depth } } }
})
};
session.notify(DidChangeConfiguration::METHOD, scoped("folder", 1));
assert_eq!(session.progress().len(), 5, "create, begin, two reports, end");
assert_eq!(indexed(&session, "defs_pkg"), 1, "one level up reaches the sibling folder");
session.notify(DidChangeConfiguration::METHOD, scoped("folder", 1));
assert!(session.progress().is_empty(), "the same depth again buys nothing");
session.notify(DidChangeConfiguration::METHOD, scoped("workspace", 1));
assert!(!session.progress().is_empty(), "and a new scope does");
assert_eq!(indexed(&session, "defs_pkg"), 1, "the whole workspace, now");
}
#[test]
fn the_bar_names_the_open_file_before_the_rest_of_the_scope() {
// The progress half of the open-first ordering: the file the user is
// waiting on is `1/N`, not wherever its name happens to sort. The
// index it produces is identical either way — that is pinned in
// `state.rs` and in `vlog_semantic`, because it is a property of the
// builder rather than of the bar.
let tree = Tree::new("scopeorderbar");
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 session = Session::wide_with(vec![tree.path.clone()], watching_progress());
let uri = session.open(&tree.path.join("rtl/m_open.sv"), "package m_open;\nendpackage\n");
let _ = session.drain();
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
let named: Vec<Option<String>> =
session.reported().into_iter().map(|(message, _)| message).collect();
assert_eq!(
named,
vec![
Some("1/3 m_open.sv".to_string()),
Some("2/3 a_first.sv".to_string()),
Some("3/3 z_last.sv".to_string()),
],
"the open buffer first, then path order"
);
}
#[test]
fn a_client_that_did_not_ask_for_a_bar_is_sent_no_progress_at_all() {
// The spec forbids server-initiated progress without the capability,
@@ -2428,7 +2582,7 @@ mod tests {
let tree = Tree::new("progresspaths");
tree.package("rtl/a.sv", "a");
tree.write("files.f", "rtl/a.sv\n");
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
let _ = session.drain();
@@ -2557,7 +2711,7 @@ mod tests {
tree.package("rtl/a.sv", "a");
let abilities =
ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() };
let session = Session::with(vec![tree.path.clone()], abilities);
let session = Session::wide_with(vec![tree.path.clone()], abilities);
let order: Vec<String> = session
.drain()
@@ -2808,7 +2962,7 @@ mod tests {
tree.package("rtl/open.sv", "on_disk");
let path = tree.path.join("rtl/open.sv");
let mut session = Session::new(vec![tree.path.clone()], true);
let mut session = Session::wide(vec![tree.path.clone()], true);
let uri = session.open(&path, "package in_buffer;\n localparam K = 1;\nendpackage\n");
assert_eq!(indexed(&session, "on_disk"), 1, "premise: indexed from disk at startup");
@@ -5234,7 +5388,7 @@ mod tests {
let tree = Tree::new("willrename");
tree.write("defs.svh", "`define W 8\n");
tree.write("top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n");
let mut session = Session::new(vec![tree.path.clone()], false);
let mut session = Session::wide(vec![tree.path.clone()], false);
let (from, to) = (tree.path.join("defs.svh"), tree.path.join("widths.svh"));
let answer = will_rename(&mut session, &from, &to);
@@ -5254,7 +5408,7 @@ mod tests {
let tree = Tree::new("willrenameunopened");
tree.write("defs.svh", "`define W 8\n");
tree.write("top.sv", "`include \"defs.svh\"\n");
let mut session = Session::new(vec![tree.path.clone()], false);
let mut session = Session::wide(vec![tree.path.clone()], false);
assert!(session.server.workspace.open_uris().is_empty(), "premise: nothing open");
let answer =
@@ -5332,7 +5486,7 @@ mod tests {
fn a_rename_notification_rebuilds_the_index() {
let tree = Tree::new("didrename");
tree.package("rtl/a.sv", "a");
let mut session = Session::new(vec![tree.path.clone()], false);
let mut session = Session::wide(vec![tree.path.clone()], false);
assert_eq!(indexed(&session, "a"), 1, "premise: indexed under its old name");
std::fs::rename(tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")).expect("rename");
@@ -5350,7 +5504,7 @@ mod tests {
let tree = Tree::new("diddelete");
tree.package("rtl/a.sv", "a");
tree.package("rtl/gone.sv", "gone_pkg");
let mut session = Session::new(vec![tree.path.clone()], false);
let mut session = Session::wide(vec![tree.path.clone()], false);
assert_eq!(indexed(&session, "gone_pkg"), 1, "premise: indexed");
std::fs::remove_file(tree.path.join("rtl/gone.sv")).expect("remove");
@@ -5410,45 +5564,64 @@ mod tests {
}
#[test]
fn a_rootless_session_gaining_its_first_folder_flips_didopen_from_reindex_to_publish() {
// `didOpen`'s root-conditional reads the *current* root set: with no
// roots at all it reindexes to widen the scope; with one, it only
// publishes. Before this round a session's root set never changed
// after `initialize`, so a session could never move between the two
// branches — this pins that it now genuinely does, live.
// QA (2026-08-27): "own shapes" case from the review checklist.
let outside = Tree::new("rootlessgainsoutside");
fn a_didopen_rebuilds_exactly_when_it_widens_the_scope() {
// Superseded this round (index-scope, 2026-08-27): the test that stood
// here — `a_rootless_session_gaining_its_first_folder_flips_didopen_
// from_reindex_to_publish` — pinned `didOpen`'s *root*-conditional,
// rootless reindexing and rooted publishing. Rung 3 is now the default
// rung with a root as well, so the root set is not the question any
// more; the question is whether the file just opened brought a folder
// the index does not cover, and this is the same case list under the
// rule that replaced it. The pinned property is strictly stronger: it
// holds in a rootless session and in a rooted one, and it is the same
// one line of code for both.
let outside = Tree::new("didopenscopeoutside");
outside.package("a.sv", "a");
let folder = Tree::new("rootlessgainsfolder");
folder.package("b.sv", "b");
let folder = Tree::new("didopenscopefolder");
folder.package("rtl/b.sv", "b");
folder.package("rtl/beside.sv", "beside");
let mut session = Session::new(Vec::new(), false);
assert!(!session.server.workspace.has_roots(), "premise: rootless");
// `generation` counts a buffer's text *and* the index, so one open is
// `set_document`'s bump plus `reindex`'s own — two, while rootless.
// `generation` counts a buffer's text *and* the index, so an open that
// widens is `set_document`'s bump plus `reindex`'s own — two.
let before = session.server.generation;
let _ = session
.open(&outside.path.join("a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
assert_eq!(session.server.generation, before + 2, "rootless didOpen widens by reindexing");
assert_eq!(session.server.generation, before + 2, "a new folder widens by reindexing");
folders_changed(&mut session, &[&folder.path], &[]);
assert!(session.server.workspace.has_roots(), "the workspace now has a root");
let after_folder = session.server.generation;
// With a root, the same event costs only `set_document`'s bump: no
// second reindex, because opening an already-indexed file changes
// nothing about the scope.
// A root does not make the scope wide: this file's folder has still
// never been opened from, so it widens and rebuilds exactly as the
// rootless one did.
let after_folder = session.server.generation;
let uri = session
.open(&folder.path.join("b.sv"), "package b;\n localparam K = 1;\nendpackage\n");
.open(&folder.path.join("rtl/b.sv"), "package b;\n localparam K = 1;\nendpackage\n");
assert_eq!(
session.server.generation,
after_folder + 1,
"with a root, opening an already-indexed file must not cost a rescan"
after_folder + 2,
"a folder outside the scope widens it, root or no root"
);
assert_eq!(indexed(&session, "b"), 1, "and the widened scope really was scanned");
assert!(session.published().iter().any(|p| p.uri == uri), "and it is published too");
// The second file in a folder already in scope costs only
// `set_document`'s bump: nothing about which files exist moved.
let quiet = session.server.generation;
let uri = session.open(
&folder.path.join("rtl/beside.sv"),
"package beside;\n localparam K = 1;\nendpackage\n",
);
assert_eq!(
session.server.generation,
quiet + 1,
"a file the scope already covers must not cost a rescan"
);
let published = session.published();
assert!(
published.iter().any(|p| p.uri == uri),
session.published().iter().any(|p| p.uri == uri),
"it is still published, just not rescanned"
);
}
@@ -5462,7 +5635,7 @@ mod tests {
let second = Tree::new("folderaddsecond");
second.package("rtl/b.sv", "b");
let mut session = Session::new(vec![first.path.clone()], false);
let mut session = Session::wide(vec![first.path.clone()], false);
assert_eq!(indexed(&session, "b"), 0, "premise: the second folder is not open yet");
folders_changed(&mut session, &[&second.path], &[]);
@@ -5492,7 +5665,7 @@ mod tests {
second.package("rtl/open.sv", "open_pkg");
second.package("rtl/other.sv", "other_pkg");
let mut session = Session::new(vec![first.path.clone(), second.path.clone()], false);
let mut session = Session::wide(vec![first.path.clone(), second.path.clone()], false);
let uri = session.open(
&second.path.join("rtl/open.sv"),
"package open_pkg;\n localparam K = 1;\nendpackage\n",
@@ -5553,7 +5726,8 @@ mod tests {
code_lens_refresh: true,
..Default::default()
};
let mut session = Session::with(vec![first.path.clone(), second.path.clone()], abilities);
let mut session =
Session::wide_with(vec![first.path.clone(), second.path.clone()], abilities);
session.open(&first.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
let before = session.server.generation;
let _ = session.drain();
@@ -5597,7 +5771,7 @@ mod tests {
let flapping = Tree::new("rapidflapfolder");
flapping.package("rtl/b.sv", "b");
let mut session = Session::new(vec![root.path.clone()], false);
let mut session = Session::wide(vec![root.path.clone()], false);
let before = session.server.generation;
folders_changed(&mut session, &[&flapping.path], &[]);
@@ -5625,7 +5799,7 @@ mod tests {
// root set where it was must cost no rescan at all.
let tree = Tree::new("foldernoop");
tree.package("rtl/a.sv", "a");
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
let before = session.server.generation;
let _ = session.drain();
@@ -5797,11 +5971,17 @@ mod tests {
let tree = Tree::new("pullexclude");
tree.package("rtl/a.sv", "a");
tree.package("scratch/wip.sv", "scratch_pkg");
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
let mut session = Session::wide_with(vec![tree.path.clone()], pulling_settings());
assert_eq!(indexed(&session, "scratch_pkg"), 1, "premise: indexed at first");
let (id, _) = configuration_request(&session);
session.answer(id, serde_json::json!([{ "exclude": ["scratch"] }]));
// The pulled section carries the scope for the same reason a pushed
// one does: an answer is the *whole* section, so leaving it out would
// narrow the index in the same breath as the exclude.
session.answer(
id,
serde_json::json!([{ "exclude": ["scratch"], "index": { "scope": "workspace" } }]),
);
assert_eq!(indexed(&session, "scratch_pkg"), 0, "the pulled exclude took effect");
assert_eq!(indexed(&session, "a"), 1, "and nothing else moved");
}
+106 -5
View File
@@ -34,6 +34,26 @@ const INDENT_RANGE: RangeInclusive<u64> = 1..=8;
/// `docs/features/indexing-ux/README.md`.
pub const DEFAULT_MAX_FILE_SIZE: u64 = 1024 * 1024;
/// What `lucisv.index.scope` chooses: how wide the workspace walk goes.
///
/// The default is deliberately the narrow one. A large project is the case
/// worth optimising for, and in it the files a user is working with are the
/// ones beside the file they opened; walking every workspace folder to answer
/// a question about one folder is minutes of work nobody asked for. See
/// `docs/features/index-scope/README.md` for what the narrow scope costs,
/// which is cross-folder answers until the scope reaches the other folder.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IndexScope {
/// The open buffers' own folders, each raised
/// [`ClientSettings::index_scope_depth`] levels, walked.
#[default]
Folder,
/// Every workspace folder, walked whole — what the server did before
/// 2026-08-27, and what a user with a small project or a big machine can
/// ask for back.
Workspace,
}
/// The configuration section these settings live in — the key a push nests
/// them under, and the `section` a pull asks for. One constant, because the
/// two must name the same thing or the pull would answer settings the parser
@@ -81,6 +101,17 @@ pub struct ClientSettings {
/// unless a client says otherwise — the Output panel it lands in is
/// hidden until somebody opens it.
pub log_files: bool,
/// `lucisv.index.scope`: whether the walk covers the open files' folders
/// or every workspace folder. Defaults to [`IndexScope::Folder`], which
/// is a narrower index than the server built before 2026-08-27 — see
/// `docs/features/index-scope/README.md`.
pub index_scope: IndexScope,
/// `lucisv.index.scopeDepth`: how many directory levels above an open
/// file's own folder the folder scope starts, clamped so it never climbs
/// out of the workspace folder containing it. `0` — the default — is the
/// file's own folder. Ignored when `index_scope` is
/// [`IndexScope::Workspace`] or when a filelist defines the scope.
pub index_scope_depth: u64,
}
/// The settings a client that said nothing is treated as having asked for.
@@ -99,6 +130,8 @@ impl Default for ClientSettings {
format_on_save: false,
max_file_size: DEFAULT_MAX_FILE_SIZE,
log_files: true,
index_scope: IndexScope::Folder,
index_scope_depth: 0,
}
}
}
@@ -141,6 +174,24 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
max_file_size: count(index.and_then(|i| i.get("maxFileSize")))
.unwrap_or(DEFAULT_MAX_FILE_SIZE),
log_files: flag(index.and_then(|i| i.get("logFiles"))).unwrap_or(true),
// An unreadable scope leaves the narrow default standing, for the
// same reason a junk cap leaves the cap on: the direction that
// silently costs a user minutes of scanning is the wrong one to
// guess in.
index_scope: scope(index.and_then(|i| i.get("scope"))).unwrap_or_default(),
index_scope_depth: count(index.and_then(|i| i.get("scopeDepth"))).unwrap_or(0),
}
}
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
/// case and all — because the enum in `package.json` is what a settings UI
/// offers, and forgiving `"Workspace"` here would make a typo mean something
/// on one client and nothing on another.
fn scope(value: Option<&Value>) -> Option<IndexScope> {
match value?.as_str()? {
"folder" => Some(IndexScope::Folder),
"workspace" => Some(IndexScope::Workspace),
_ => None,
}
}
@@ -247,7 +298,10 @@ mod tests {
"filelist": "",
"inlineTemplates": true,
"formatOnSave": false,
"index": { "maxFileSize": 1048576, "logFiles": true }
"index": {
"maxFileSize": 1048576, "logFiles": true,
"scope": "folder", "scopeDepth": 0
}
}
})
}
@@ -280,6 +334,8 @@ mod tests {
let found = settings(json!({ "lucisv": { "index": bad } }));
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "index {bad} is ignored");
assert!(found.log_files, "and so is its logFiles");
assert_eq!(found.index_scope, IndexScope::Folder, "and its scope");
assert_eq!(found.index_scope_depth, 0, "and its scopeDepth");
}
}
@@ -300,16 +356,61 @@ mod tests {
#[test]
fn the_index_settings_come_through_the_pull_door_too() {
// `from_section` is the same parser, and these two are the first
// nested keys to go through it — a section that lost the nesting on
// the way would silently un-cap every pulling client.
let section = json!({ "index": { "maxFileSize": 4096, "logFiles": false } });
// `from_section` is the same parser, and these were the first nested
// keys to go through it — a section that lost the nesting on the way
// would silently un-cap every pulling client.
let section = json!({
"index": {
"maxFileSize": 4096, "logFiles": false,
"scope": "workspace", "scopeDepth": 2
}
});
let pulled = from_section(&section);
assert_eq!(pulled.max_file_size, 4096);
assert!(!pulled.log_files);
assert_eq!(pulled.index_scope, IndexScope::Workspace);
assert_eq!(pulled.index_scope_depth, 2);
assert_eq!(pulled, settings(json!({ "lucisv": section })), "one set of rules");
}
#[test]
fn the_index_scope_is_the_open_folder_until_a_client_asks_for_the_workspace() {
// The default is the narrow one, and it is what silence, an empty
// sub-section and a missing `index` all resolve to.
assert_eq!(settings(json!({ "lucisv": {} })).index_scope, IndexScope::Folder);
assert_eq!(settings(json!({ "lucisv": { "index": {} } })).index_scope, IndexScope::Folder);
assert_eq!(IndexScope::default(), IndexScope::Folder, "and the enum agrees");
let wide = settings(json!({ "lucisv": { "index": { "scope": "workspace" } } }));
assert_eq!(wide.index_scope, IndexScope::Workspace, "the migration setting");
let narrow = settings(json!({ "lucisv": { "index": { "scope": "folder" } } }));
assert_eq!(narrow.index_scope, IndexScope::Folder, "spelled out, same thing");
// Anything else is junk, and junk leaves the *narrow* default: a
// misparse must never buy a whole-workspace scan silently.
for bad in
[json!("Workspace"), json!("all"), json!(""), json!(2), json!(true), json!(["folder"])]
{
let found = settings(json!({ "lucisv": { "index": { "scope": bad } } }));
assert_eq!(found.index_scope, IndexScope::Folder, "scope {bad} must be ignored");
}
}
#[test]
fn the_scope_depth_is_zero_until_a_client_raises_it() {
assert_eq!(settings(json!({ "lucisv": {} })).index_scope_depth, 0);
assert_eq!(settings(json!({ "lucisv": { "index": {} } })).index_scope_depth, 0);
let raised = settings(json!({ "lucisv": { "index": { "scopeDepth": 3 } } }));
assert_eq!(raised.index_scope_depth, 3);
// No upper bound here: the clamp is structural — `state.rs` stops at
// the workspace root — so an absurd number is not wrong, just fully
// clamped.
let absurd = settings(json!({ "lucisv": { "index": { "scopeDepth": 9999 } } }));
assert_eq!(absurd.index_scope_depth, 9999);
for bad in [json!(-1), json!(1.5), json!("2"), json!(true), json!(null), json!([2])] {
let found = settings(json!({ "lucisv": { "index": { "scopeDepth": bad } } }));
assert_eq!(found.index_scope_depth, 0, "scopeDepth {bad} must be ignored");
}
}
#[test]
fn a_filelist_is_taken_when_it_names_something() {
let found = settings(json!({ "lucisv": { "filelist": "rtl/files.f" } }));
+2 -2
View File
@@ -321,7 +321,7 @@ endmodule
tree.write("sub.sv", SUB);
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = (top.find(needle).expect("needle present") + needle.len()) as u32;
@@ -456,7 +456,7 @@ endmodule
let top = "module top;\n bare #(\n";
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = top.len() as u32 - 1;
+566 -80
View File
@@ -23,7 +23,7 @@ use lucisv_core::walk::{collect_files, EXTENSIONS};
use crate::candidates::Candidates;
use crate::convert::Positions;
use crate::includes::IncludeGraph;
use crate::settings::ClientSettings;
use crate::settings::{ClientSettings, IndexScope};
use crate::uri::uri_to_path;
/// How many `workspace/symbol` hits are returned. Each one costs a file read
@@ -150,6 +150,11 @@ pub struct Workspace {
includes: IncludeGraph,
/// The last `lucisv.*` settings a client pushed. Default until it does.
client: ClientSettings,
/// 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 {
@@ -165,6 +170,34 @@ impl Workspace {
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(
@@ -213,13 +246,75 @@ impl Workspace {
/// Whether the client opened a workspace at all.
///
/// Without one the index's scope is the open buffers' own directories, so
/// opening a file widens it — which is why `server.rs` rebuilds on
/// `didOpen` in that case and not in any other.
/// 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 {
@@ -229,15 +324,18 @@ impl Workspace {
/// Adopt the settings a client pushed.
///
/// Returns `true` when the caller must rebuild the index: `exclude`,
/// `filelist` and `index.maxFileSize` are the three 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.
/// `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.
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.max_file_size != settings.max_file_size
|| self.client.index_scope != settings.index_scope
|| self.client.index_scope_depth != settings.index_scope_depth;
self.client = settings;
rescan
}
@@ -247,8 +345,18 @@ impl Workspace {
}
/// 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.
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 = Document::new(path, text, &self.index);
self.docs.insert(uri, doc);
}
@@ -289,10 +397,12 @@ impl Workspace {
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, in the order it will be
// built in — asked of `vlog_semantic` rather than re-derived here, so
// the count reported is the count parsed.
let ordered = index_order(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
// 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();
let mut builder = IndexBuilder::new();
for (done, (path, text)) in ordered.into_iter().enumerate() {
@@ -312,6 +422,22 @@ impl Workspace {
scope.warnings
}
/// 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
@@ -374,11 +500,15 @@ impl Workspace {
/// 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.
/// 2. **The workspace-folder walk**, unchanged from before filelists.
/// 3. **Each open buffer's own directory**, non-recursive, when there is
/// no workspace root at all — a single file opened on its own still
/// resolves against the files beside it.
/// 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
@@ -422,51 +552,49 @@ impl Workspace {
self.roots.iter().find_map(|root| discovery.for_dir(root).ok()?.filelist)
}
/// Rungs 2 and 3 of the ladder: the workspace walk, or — with no workspace
/// at all — the directories the open buffers live in.
/// 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.roots.is_empty() {
self.sibling_files()
} else {
self.walked_files()
if self.walks_the_workspace() {
return self.walked_files(&self.roots);
}
self.folder_files()
}
/// The source files sitting beside each open buffer, one directory deep.
/// No walk, no `.gitignore`: this is the fallback for "a file opened on
/// its own", where descending a tree the user never named would be a
/// surprise.
fn sibling_files(&self) -> Vec<PathBuf> {
let mut dirs: Vec<&Path> =
self.docs.values().filter_map(|d| d.path.as_deref()?.parent()).collect();
dirs.sort();
dirs.dedup();
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);
}
}
/// 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);
}
out.sort();
out.dedup();
out
self.walked_files(&dirs)
}
/// Every source file under the roots, found by the CLI's own walk: the
/// same extensions, the same `.gitignore` handling, and the `exclude`
/// patterns of the config governing each root. What `lucisv` skips, the
/// index skips.
fn walked_files(&self) -> Vec<PathBuf> {
/// 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 &self.roots {
// The walk names its inputs as strings; every root came from a
// `file:` URI, which cannot carry a non-UTF-8 path.
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
@@ -480,8 +608,8 @@ impl Workspace {
// 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 root is
// simply not indexed, exactly as before this walk was shared.
// 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();
@@ -490,6 +618,26 @@ impl Workspace {
}
}
/// 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::*;
@@ -546,7 +694,7 @@ mod tests {
fs::write(&path, "package p;\n localparam ON_DISK = 1;\nendpackage\n").expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
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);
@@ -602,7 +750,7 @@ mod tests {
second.package("b.sv", "b");
let mut ws = Workspace::default();
ws.open_roots(vec![first.path.clone()]);
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");
@@ -638,7 +786,7 @@ mod tests {
tree.package("sub/hidden.sv", "hidden_pkg");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
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")], &[]));
@@ -694,7 +842,7 @@ mod tests {
let tree = Tree::new("rootsboth");
tree.package("a.sv", "a");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
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"]);
@@ -714,12 +862,18 @@ mod tests {
extra.package("x.sv", "x");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
// 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"
@@ -739,7 +893,7 @@ mod tests {
tree.package("elsewhere/far.sv", "far");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
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");
@@ -797,7 +951,7 @@ mod tests {
tree.package("rtl/top_gen.sv", "gen_pkg");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
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");
@@ -811,7 +965,7 @@ mod tests {
tree.package("vendor/ip.sv", "vendor_pkg");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
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");
}
@@ -825,10 +979,18 @@ mod tests {
tree.package("kept.sv", "kept");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
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 {
@@ -844,10 +1006,10 @@ mod tests {
tree.package("scratch/wip.sv", "scratch_pkg");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
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(excluding(&["scratch"])), "an exclude change rescans");
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");
@@ -866,7 +1028,7 @@ mod tests {
let mut ws = Workspace::default();
ws.set_client_settings(excluding(&["scratch"]));
ws.open_roots(vec![tree.path.clone()]);
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");
@@ -962,7 +1124,7 @@ mod tests {
let mut ws = Workspace::default();
ws.set_client_settings(capping(1024));
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(
indexed(&ws, &["small_pkg", "netlist_pkg"]),
["small_pkg"],
@@ -979,12 +1141,12 @@ mod tests {
fat_package(&tree, "huge.sv", "huge_pkg", 1024 * 1024 + 1);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
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(capping(0)), "turning the cap off rescans");
assert!(ws.set_client_settings(wide(capping(0))), "turning the cap off rescans");
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["small_pkg", "huge_pkg"]),
@@ -1003,7 +1165,10 @@ mod tests {
let mut ws = Workspace::default();
ws.set_client_settings(capping(1024));
ws.open_roots(vec![tree.path.clone()]);
// 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");
@@ -1022,7 +1187,7 @@ mod tests {
let mut ws = Workspace::default();
ws.set_client_settings(capping(1024));
let mut skipped: Vec<(PathBuf, u64, u64)> = Vec::new();
ws.open_roots_with(vec![tree.path.clone()], &mut |event| {
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));
}
@@ -1051,7 +1216,7 @@ mod tests {
..Default::default()
});
let mut seen: Vec<(usize, usize, PathBuf)> = Vec::new();
ws.open_roots_with(vec![tree.path.clone()], &mut |event| {
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()));
}
@@ -1078,10 +1243,10 @@ mod tests {
}
let mut capped = Workspace::default();
capped.open_roots(vec![corpus.clone()]);
capped.open_whole_workspace(vec![corpus.clone()]);
let mut uncapped = Workspace::default();
uncapped.set_client_settings(capping(0));
uncapped.open_roots(vec![corpus]);
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");
@@ -1177,7 +1342,7 @@ mod tests {
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("typo.f"));
let warnings = ws.open_roots(vec![tree.path.clone()]);
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:?}");
@@ -1297,7 +1462,7 @@ mod tests {
#[test]
fn without_a_filelist_there_are_no_incdirs_at_all() {
// Rung 2 of the ladder names no include path, so an `` `include``
// 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();
@@ -1328,10 +1493,331 @@ mod tests {
tree.package("e.txt", "e");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
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");
}
}
+1 -1
View File
@@ -179,7 +179,7 @@ mod tests {
.expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let hits = workspace_symbols(&ws, "alpha");
let names: Vec<_> = hits.iter().map(|h| h.name.as_str()).collect();
+2 -2
View File
@@ -629,7 +629,7 @@ endmodule
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let path = dir.join(which);
let uri = path_to_uri(&path).expect("uri");
let text = fs::read_to_string(&path).expect("read");
@@ -1280,7 +1280,7 @@ endmodule
return;
}
let mut ws = Workspace::default();
ws.open_roots(vec![root.clone()]);
ws.open_whole_workspace(vec![root.clone()]);
let open = |ws: &mut Workspace, rel: &str| -> (Uri, String) {
let file = root.join(rel);
+3 -3
View File
@@ -351,7 +351,7 @@ mod tests {
}
}
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let (path, text) = first.expect("at least one file");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -718,7 +718,7 @@ endclass
tree.write("files.f", "base.sv\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let base_uri = path_to_uri(&tree.path.join("base.sv")).expect("uri");
ws.set_document(base_uri.clone(), BASE.to_string());
@@ -1104,7 +1104,7 @@ endclass
return;
};
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&lib).expect("uri");
ws.set_document(uri.clone(), text.clone());
let files = ws.index().files().len();
+135 -10
View File
@@ -20,6 +20,16 @@ fn frame(payload: &str) -> String {
format!("Content-Length: {}\r\n\r\n{payload}", payload.len())
}
/// The `didChangeConfiguration` push that asks for the whole-workspace index
/// scope — what every session had before 2026-08-27.
///
/// Sessions whose subject is *not* the scope send it right after
/// `initialized`: the default scope is the folders the client's own buffers
/// live in, so a session that opens no buffer (or that expects a folder it
/// never opened a file in to be indexed) would otherwise be asking questions
/// of an empty index. See `docs/features/index-scope/README.md`.
const WIDE_SCOPE: &str = r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"index":{"scope":"workspace"}}}}}"#;
/// Split a stdout dump into its JSON payloads.
fn unframe(mut input: impl BufRead) -> Vec<serde_json::Value> {
let mut out = Vec::new();
@@ -1101,9 +1111,13 @@ fn a_pushed_filelist_narrows_the_index_mid_session_and_reports_a_bad_one() {
r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"{name}"}}}}"#
))
};
// Every push carries `index.scope: "workspace"`: this test is about the
// filelist rung and the walk it falls back to, and a push replaces every
// setting — without it each message would also move the fallback to the
// folder scope, which no buffer has widened here.
let filelist = |path: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"filelist":"{path}"}}}}}}}}"#
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"filelist":"{path}","index":{{"scope":"workspace"}}}}}}}}}}"#
))
};
let session = [
@@ -1111,6 +1125,8 @@ fn a_pushed_filelist_narrows_the_index_mid_session_and_reports_a_bad_one() {
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
// The walk this test starts from is the opt-in one now.
filelist(""),
query(2, "b_pkg"),
filelist("files.f"),
query(3, "b_pkg"),
@@ -2664,6 +2680,7 @@ endmodule
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{mid_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(mid_text).expect("json")
@@ -2693,6 +2710,7 @@ endmodule
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"callHierarchy/incomingCalls","params":{{"item":{}}}}}"#,
serde_json::to_string(&sub2_item).expect("json")
@@ -3205,20 +3223,26 @@ fn indexing_reports_its_progress_over_the_wire() {
})
.collect();
// Two rescans: the startup build, then the save. Each one create, one
// begin, one report per file (there is one file), one end, on its own
// token.
// Three rescans, and the shape of them is the folder scope on the wire
// (index-scope, 2026-08-27). The startup build has **no file to scan** —
// the default scope is the open buffers' folders and no buffer is open
// yet — so its bar carries no report; the `didOpen` widens the scope to
// `m.sv`'s folder and rebuilds, reporting the one file; the save rebuilds
// again. Each on its own token, create/begin/…/end in order.
assert_eq!(
steps,
vec![
("create".to_string(), "lucisv-index-0".to_string()),
("begin".to_string(), "lucisv-index-0".to_string()),
("report".to_string(), "lucisv-index-0".to_string()),
("end".to_string(), "lucisv-index-0".to_string()),
("create".to_string(), "lucisv-index-1".to_string()),
("begin".to_string(), "lucisv-index-1".to_string()),
("report".to_string(), "lucisv-index-1".to_string()),
("end".to_string(), "lucisv-index-1".to_string()),
("create".to_string(), "lucisv-index-2".to_string()),
("begin".to_string(), "lucisv-index-2".to_string()),
("report".to_string(), "lucisv-index-2".to_string()),
("end".to_string(), "lucisv-index-2".to_string()),
],
"{messages:#?}"
);
@@ -3237,8 +3261,14 @@ fn indexing_reports_its_progress_over_the_wire() {
assert_eq!(begin["params"]["value"]["cancellable"], false, "{begin:#?}");
assert!(begin["params"]["value"].get("percentage").is_none(), "no fake numbers: {begin:#?}");
let end = messages.iter().find(|m| m["params"]["value"]["kind"] == "end").expect("an end");
assert_eq!(end["params"]["value"]["message"], "1 file indexed", "{end:#?}");
// The startup bar ends at nothing indexed — honestly, since the folder
// scope had no folder yet — and the two rebuilds after it name the file.
let ends: Vec<&serde_json::Value> = messages
.iter()
.filter(|m| m["params"]["value"]["kind"] == "end")
.map(|m| &m["params"]["value"]["message"])
.collect();
assert_eq!(ends, ["0 files indexed", "1 file indexed", "1 file indexed"], "{messages:#?}");
// The create is a request the client may answer or error; leaving it
// unanswered here is exactly what a client that does not care does, and
@@ -3268,9 +3298,12 @@ fn the_size_cap_and_the_file_log_work_over_the_wire() {
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
// The cap arrives the way VS Code sends a dotted setting: nested.
// The cap arrives the way VS Code sends a dotted setting: nested. It
// carries `scope: "workspace"` because this test is about the cap, and
// a push replaces every setting — without it the same message would
// narrow the index to the folder scope in the same breath.
frame(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"index":{"maxFileSize":1024}}}}}"#,
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"index":{"maxFileSize":1024,"scope":"workspace"}}}}}"#,
),
frame(
r#"{"jsonrpc":"2.0","id":2,"method":"workspace/symbol","params":{"query":"pkg"}}"#,
@@ -3750,8 +3783,11 @@ fn a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire() {
messages.iter().filter(|m| m["method"] == "workspace/codeLens/refresh").count()
};
// One per rescan, and this script has two: the `didOpen` widens the folder
// scope to `lens_sub.sv`'s own folder and rebuilds (index-scope,
// 2026-08-27), and then the save rebuilds again.
let capable = talk(&script(r#"{"workspace":{"codeLens":{"refreshSupport":true}}}"#));
assert_eq!(refreshes(&capable), 1, "one per rescan, and the save is one: {capable:#?}");
assert_eq!(refreshes(&capable), 2, "one per rescan: {capable:#?}");
let silent = talk(&script("{}"));
assert_eq!(refreshes(&silent), 0, "a client that did not ask is never told: {silent:#?}");
@@ -3901,6 +3937,8 @@ fn a_rename_round_trips_through_the_edit_and_leaves_the_include_resolving() {
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(WIDE_SCOPE),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"workspace/willRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"#
)),
@@ -3932,6 +3970,8 @@ fn a_rename_round_trips_through_the_edit_and_leaves_the_include_resolving() {
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(WIDE_SCOPE),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"#
)),
@@ -3985,6 +4025,8 @@ fn a_moving_includer_s_own_edit_is_addressed_to_its_old_uri_on_the_wire() {
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(WIDE_SCOPE),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"workspace/willRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"#
)),
@@ -4055,6 +4097,7 @@ fn a_folder_added_mid_session_is_indexed_over_the_wire() {
"{handshake:#?}"
);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
live.send(WIDE_SCOPE);
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string("module top;\n localparam W = added_pkg::WIDTH;\nendmodule\n")
@@ -4176,3 +4219,85 @@ fn the_configuration_pull_round_trips_over_the_wire() {
live.finish();
let _ = std::fs::remove_dir_all(&dir);
}
/// index-scope (2026-08-27): the default folder scope over the real wire.
///
/// What only an e2e test can settle: that the narrowing is what a *client*
/// sees, not just what `Workspace` computes — a definition into a sibling
/// folder answers nothing until a buffer in that folder widens the scope, and
/// a client that asked for `lucisv.index.scope: "workspace"` never sees the
/// narrow answer at all.
#[test]
fn the_folder_scope_widens_when_a_file_in_another_folder_is_opened() {
let dir = temp_dir("indexscope");
std::fs::create_dir_all(dir.join("rtl")).expect("rtl");
std::fs::create_dir_all(dir.join("include")).expect("include");
let top = dir.join("rtl/scope_top.sv");
let top_text = "module scope_top;\n localparam W = scope_defs::WIDTH;\nendmodule\n";
std::fs::write(&top, top_text).expect("write");
let defs = dir.join("include/scope_defs.sv");
let defs_text = "package scope_defs;\n localparam WIDTH = 8;\nendpackage\n";
std::fs::write(&defs, defs_text).expect("write");
let root = format!("file://{}", dir.display());
let top_uri = format!("file://{}", top.display());
let defs_uri = format!("file://{}", defs.display());
// The cursor on `WIDTH` in `scope_defs::WIDTH`.
let definition = |id: u32| {
format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":1,"character":33}}}}}}"#
)
};
let open = |uri: &str, text: &str| {
format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(text).expect("json")
)
};
let mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
));
let _ = live.wait_for(|m| m["id"] == 1);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
live.send(&open(&top_uri, top_text));
live.send(&definition(2));
let narrow = live.wait_for(|m| m["id"] == 2);
assert_eq!(
narrow["result"].as_array().map(Vec::len),
Some(0),
"the package is in a sibling folder, which the default scope does not cover: {narrow:#?}"
);
// Opening the other file widens the scope and rebuilds — no save, no
// settings change, just the file the user opened.
live.send(&open(&defs_uri, defs_text));
live.send(&definition(3));
let widened = live.wait_for(|m| m["id"] == 3);
let targets = widened["result"].as_array().expect("a location list");
assert_eq!(targets.len(), 1, "{widened:#?}");
assert_eq!(targets[0]["uri"], defs_uri.as_str(), "{widened:#?}");
live.finish();
// And the migration setting: the same session, the same first question,
// answered straight away.
let mut wide = Live::start();
wide.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
));
let _ = wide.wait_for(|m| m["id"] == 1);
wide.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
wide.send(WIDE_SCOPE);
wide.send(&open(&top_uri, top_text));
wide.send(&definition(2));
let immediate = wide.wait_for(|m| m["id"] == 2);
let targets = immediate["result"].as_array().expect("a location list");
assert_eq!(targets.len(), 1, "the whole workspace was indexed: {immediate:#?}");
assert_eq!(targets[0]["uri"], defs_uri.as_str(), "{immediate:#?}");
wide.finish();
let _ = std::fs::remove_dir_all(&dir);
}
+122 -60
View File
@@ -75,7 +75,9 @@ impl WorkspaceIndex {
///
/// This is exactly [`index_order`] followed by an [`IndexBuilder`] loop,
/// and stays the API every caller that does not care to watch the build
/// should use.
/// should use. The [`index_order`] here saves parsing a duplicate path
/// twice; it is not what makes the result deterministic — the builder
/// sorts for itself.
pub fn build<'a>(files: impl IntoIterator<Item = (PathBuf, &'a str)>) -> WorkspaceIndex {
let mut builder = IndexBuilder::new();
for (path, src) in index_order(files) {
@@ -192,53 +194,81 @@ impl WorkspaceIndex {
fn units_of_kind(&self, kind: SymbolKind) -> usize {
self.units.values().flatten().filter(|d| d.kind == kind).count()
}
}
/// Record what one analyzed file declares.
fn add_file(&mut self, file: FileId, sem: &Semantics) {
let Some(file_scope) = sem.scope(sem.file_scope()) else {
return;
};
for &id in &file_scope.symbols {
let Some(unit) = sem.symbol(id) else {
continue;
};
if !is_unit(unit.kind) || unit.name_span.is_empty() {
continue;
}
self.units.entry(unit.name.clone()).or_default().push(Def {
file,
name_span: unit.name_span,
kind: unit.kind,
});
self.add_members(file, sem, unit);
}
/// One declaration as a single file contributes it, before that file has a
/// [`FileId`]. The id depends on where the file's path sorts among all of
/// them, which is not known until [`IndexBuilder::finish`].
#[derive(Debug, Clone)]
struct Decl {
name: String,
name_span: TextRange,
kind: SymbolKind,
}
impl Decl {
fn of(symbol: &Symbol) -> Decl {
Decl { name: symbol.name.clone(), name_span: symbol.name_span, kind: symbol.kind }
}
}
/// Record the names another file may reach *into* this unit for.
fn add_members(&mut self, file: FileId, sem: &Semantics, unit: &Symbol) {
let Some(scope) = unit.child_scope.and_then(|c| sem.scope(c)) else {
return;
/// Everything one file contributes to an index: read while the file is parsed,
/// merged in path order by [`IndexBuilder::finish`].
///
/// This is the same data the finished index holds, kept per file rather than
/// merged, which is what lets the merge happen in an order the caller does not
/// choose.
#[derive(Debug, Clone)]
struct FileFacts {
path: PathBuf,
defines: DefineTable,
/// File-scope declarations, in declaration order.
units: Vec<Decl>,
/// Members, each under the name of the unit that exports it, in the order
/// the scope tree yields them.
members: Vec<(String, Decl)>,
}
/// Parse one file and read off what it declares.
fn facts_of(path: PathBuf, src: &str) -> FileFacts {
let (tree, defines) = parse_and_collect(src);
let sem = analyze(&tree, src);
let mut facts = FileFacts { path, defines, units: Vec::new(), members: Vec::new() };
let Some(file_scope) = sem.scope(sem.file_scope()) else {
return facts;
};
for &id in &file_scope.symbols {
let Some(unit) = sem.symbol(id) else {
continue;
};
for &id in &scope.symbols {
let Some(member) = sem.symbol(id) else {
continue;
};
if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() {
continue;
}
self.members
.entry(unit.name.clone())
.or_default()
.entry(member.name.clone())
.or_default()
.push(Def { file, name_span: member.name_span, kind: member.kind });
// A class nested in a package (the dominant UVM shape) is not a
// unit, but an external `cls::x` candidate looks its members up
// under the *class's* name — register them there too. The scope
// tree is acyclic, so this recursion terminates.
if member.kind == SymbolKind::Class {
self.add_members(file, sem, member);
}
if !is_unit(unit.kind) || unit.name_span.is_empty() {
continue;
}
facts.units.push(Decl::of(unit));
collect_members(&sem, unit, &mut facts.members);
}
facts
}
/// Read off the names another file may reach *into* this unit for.
fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>) {
let Some(scope) = unit.child_scope.and_then(|c| sem.scope(c)) else {
return;
};
for &id in &scope.symbols {
let Some(member) = sem.symbol(id) else {
continue;
};
if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() {
continue;
}
out.push((unit.name.clone(), Decl::of(member)));
// A class nested in a package (the dominant UVM shape) is not a unit,
// but an external `cls::x` candidate looks its members up under the
// *class's* name — register them there too. The scope tree is acyclic,
// so this recursion terminates.
if member.kind == SymbolKind::Class {
collect_members(sem, member, out);
}
}
}
@@ -264,17 +294,24 @@ pub fn index_order<'a>(
/// A [`WorkspaceIndex`] under construction, one file at a time.
///
/// The same work [`WorkspaceIndex::build`] does — that function is now a loop
/// over this one — split so a caller can do something between two files, which
/// in practice means reporting progress. Nothing here is incremental in the
/// salsa sense: a file can be added, never replaced or removed.
/// The same work [`WorkspaceIndex::build`] does — that function is a loop over
/// this one — split so a caller can do something between two files, which in
/// practice means reporting progress. Nothing here is incremental in the salsa
/// sense: a file can be added, never replaced or removed.
///
/// **Feed it [`index_order`]'s list.** [`FileId`]s are handed out in call
/// order, and both the file ids and the disambiguation order of a name
/// declared twice are the path order that function establishes.
/// **The order files are added in cannot change the result.** `add_file`
/// parses its file and keeps what it declares to itself; `finish` sorts those
/// per-file records by path — [`index_order`]'s rule, applied where no caller
/// can bypass it — and only then hands out [`FileId`]s and merges the
/// declarations. So the file ids, the disambiguation order of a name declared
/// twice, and every member table are the path order, whoever calls this and in
/// whatever sequence. (Before 2026-08-27 the ordering was a doc comment asking
/// callers to feed it [`index_order`]'s list, and a caller who did not silently
/// got a different index.)
#[derive(Debug, Clone, Default)]
pub struct IndexBuilder {
index: WorkspaceIndex,
/// One record per `add_file` call, in call order. Sorted by `finish`.
files: Vec<FileFacts>,
}
impl IndexBuilder {
@@ -284,17 +321,42 @@ impl IndexBuilder {
}
/// Parse one file and record what it declares.
///
/// The parse happens here, not in `finish`, so a caller reporting progress
/// between calls is reporting work that has really been done.
pub fn add_file(&mut self, path: PathBuf, src: &str) {
let file = FileId(self.index.files.len() as u32);
self.index.files.push(path);
let (tree, defines) = parse_and_collect(src);
self.index.defines.push(defines);
self.index.add_file(file, &analyze(&tree, src));
self.files.push(facts_of(path, src));
}
/// The finished index.
pub fn finish(self) -> WorkspaceIndex {
self.index
/// The finished index: the files sorted by path, then merged.
///
/// `sort_by` is stable and `dedup_by` keeps the first of a run, so a path
/// added twice is one file and the first copy wins — exactly what
/// [`index_order`] does to the list it is handed.
pub fn finish(mut self) -> WorkspaceIndex {
self.files.sort_by(|a, b| a.path.cmp(&b.path));
self.files.dedup_by(|a, b| a.path == b.path);
let mut index = WorkspaceIndex::default();
for (id, facts) in self.files.into_iter().enumerate() {
let file = FileId(id as u32);
index.files.push(facts.path);
index.defines.push(facts.defines);
for decl in facts.units {
index.units.entry(decl.name).or_default().push(Def {
file,
name_span: decl.name_span,
kind: decl.kind,
});
}
for (unit, decl) in facts.members {
index.members.entry(unit).or_default().entry(decl.name).or_default().push(Def {
file,
name_span: decl.name_span,
kind: decl.kind,
});
}
}
index
}
}
+105 -1
View File
@@ -1,7 +1,7 @@
//! Behavior of the workspace index: cross-file definitions, duplicate names,
//! package members, and the corpus acceptance run.
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use vlog_parser::parse_source_tolerant;
use vlog_semantic::{
analyze, resolve_external, Def, Definition, ExternalTarget, FileId, Resolution, Semantics,
@@ -319,6 +319,110 @@ fn the_incremental_builder_is_what_build_is_made_of() {
assert_eq!(built.member("z", "K").len(), 1);
}
/// Everything an index holds, as text: the files in `FileId` order, then every
/// declared name — unit or member — with its declarations in disambiguation
/// order, each naming the **path** of the file it is in rather than its id, and
/// then each file's `` `define`` count. Two indexes with the same fingerprint
/// answer every query the same way; an index whose file ids or whose
/// duplicate-name order moved has a different one.
fn fingerprint(index: &WorkspaceIndex) -> String {
let mut out = String::new();
for (id, path) in index.files().iter().enumerate() {
let defines = index.defines(FileId(id as u32)).map_or(0, |t| t.entries().len());
out.push_str(&format!("file {id} {} ({defines} defines)\n", path.display()));
}
let mut names: Vec<(Option<String>, String)> = index
.workspace_symbols("")
.iter()
.map(|hit| (hit.container.map(str::to_string), hit.name.to_string()))
.collect();
names.sort();
names.dedup();
for (container, name) in names {
let defs = match &container {
Some(unit) => index.member(unit, &name),
None => index.units(&name),
};
out.push_str(&format!("{}::{name}", container.unwrap_or_default()));
for def in defs {
let path = index.path(def.file).map(|p| p.display().to_string()).unwrap_or_default();
out.push_str(&format!(" [{path} {:?} {:?}]", def.name_span, def.kind));
}
out.push('\n');
}
out
}
/// One index built by adding `files` to an `IndexBuilder` in exactly the order
/// given — no `index_order` in sight, which is the whole point.
fn built_in_order(files: &[(&str, &str)]) -> WorkspaceIndex {
let mut builder = vlog_semantic::IndexBuilder::new();
for (path, src) in files {
builder.add_file(PathBuf::from(*path), src);
}
builder.finish()
}
#[test]
fn no_insertion_order_can_change_what_the_builder_produces() {
// The attack QA landed on the previous round (indexing-ux QA log,
// 2026-08-27, MEDIUM): `IndexBuilder` handed out `FileId`s in *call* order,
// so a caller that skipped `index_order` got a different index — different
// ids, and a different winner for a name two files declare. Both callers in
// the tree happened to be correct, which is exactly what makes it a footgun
// rather than a bug. It is closed by construction now: `finish` sorts, so
// this test is the permanent re-attack.
let files = [
("z_late.sv", "module dup (input a); endmodule\n"),
("a_early.sv", "module dup (input b); endmodule\n"),
("pkg/m_mid.sv", "package p;\n localparam K = 1;\n typedef int t;\nendpackage\n"),
("defs.svh", "`define W 8\n`define D 4\n"),
("cls.sv", "package q;\n class c;\n int x;\n endclass\nendpackage\n"),
];
let sorted = built_in_order(&files);
// Reversed, rotated, and the exact pair QA proved flipped the ids.
let mut reversed = files;
reversed.reverse();
let mut rotated = files;
rotated.rotate_left(3);
for (label, order) in [("reversed", reversed), ("rotated", rotated)] {
assert_eq!(
fingerprint(&built_in_order(&order)),
fingerprint(&sorted),
"{label}: the insertion order must not reach the result"
);
}
// And the same index `build` produces, since that is what every other test
// in this file exercises.
assert_eq!(fingerprint(&index(&files)), fingerprint(&sorted), "and `build` agrees");
// Named explicitly, because a fingerprint match is only as good as what it
// covers: the ids and the duplicate-name winner are the two things that
// moved before.
let winner = |ws: &WorkspaceIndex| ws.path(ws.units("dup")[0].file).map(Path::to_path_buf);
assert_eq!(winner(&sorted), Some(PathBuf::from("a_early.sv")), "sorted, not first-added");
assert_eq!(sorted.files()[0], PathBuf::from("a_early.sv"), "and FileId(0) with it");
}
#[test]
fn a_path_added_twice_is_one_file_whichever_end_the_duplicate_is_at() {
// `index_order`'s other half — one entry per path, the first copy wins —
// has to survive being applied inside `finish` instead of before the loop,
// including when the duplicate is *not* adjacent to the copy that wins.
let files = [
("a.sv", "module a; endmodule\n"),
("z.sv", "module z; endmodule\n"),
("a.sv", "module never_seen; endmodule\n"),
];
let ws = built_in_order(&files);
assert_eq!(ws.files(), [PathBuf::from("a.sv"), PathBuf::from("z.sv")], "two files, not three");
assert_eq!(ws.units("a").len(), 1, "the first copy won");
assert!(ws.units("never_seen").is_empty(), "the second is gone, not appended");
assert_eq!(fingerprint(&ws), fingerprint(&index(&files)), "exactly what `build` gives");
}
// ----------------------------------------------------------------------
// Queries
// ----------------------------------------------------------------------
+5 -2
View File
@@ -127,8 +127,11 @@ Highest first, resolved on every index rebuild:
| # | Scope | When |
|---|---|---|
| 1 | The files a **filelist** names | `lucisv.filelist` is set (absolute, or relative to the first workspace root), else the workspace root's `lucisv.toml` has a `filelist` key |
| 2 | The **workspace-folder walk** | there is a workspace root — unchanged from before this feature |
| 3 | Each **open file's own directory**, non-recursive | there is no workspace root at all (a single file opened) |
| 2 | The **workspace-folder walk** | ~~there is a workspace root~~ **superseded (index-scope, 2026-08-27): `lucisv.index.scope: "workspace"` asks for it; it is no longer the default** |
| 3 | Each **open file's own directory** | ~~non-recursive; there is no workspace root at all~~ **superseded (index-scope, 2026-08-27): this is now the default rung with a root too, raised `lucisv.index.scopeDepth` levels and walked. The non-recursive read survives unchanged for the rootless session at depth 0. See `docs/features/index-scope/README.md`** |
Rung 1 — this feature — is untouched by that round: a filelist is the project
file, and it still defines the scope exactly, in any session.
Open buffers overlay every rung exactly as they did before: a buffer's text
beats what is on disk, and a buffer whose path the scope does not name is
+3 -1
View File
@@ -51,7 +51,9 @@ parser** a push does, so the two paths cannot drift.
disk in the index by contributing itself (`Workspace::collect_sources` adds
every open document with a path, whatever the scope ladder said). Removing
the *last* folder is not a special case either: the session becomes the
rootless one rung 3 of the scope ladder already describes, where the scope
rootless one rung 3 of the scope ladder already describes (which
index-scope, 2026-08-27, made the default rung for a rooted session as
well), where the scope
is the open buffers' own directories.
- **One set of settings per session, not one per folder.** The pull sends no
`scopeUri`. `ClientSettings` is a single struct read by `format::settings_for`
+606
View File
@@ -0,0 +1,606 @@
# index-scope
## Goal
Open-file-first indexing for a project too big to scan. Until this round the
server had two answers to "which files exist": a filelist, or **every file
under every workspace folder** — and on a large codebase the second one costs
minutes on every save, to answer questions about the handful of folders the
user is actually in. This round makes the walk follow the *open buffers*
instead: `lucisv.index.scope` (`"folder"` by default) scopes the index to the
folders the open files live in, `lucisv.index.scopeDepth` says how far above
each one to start looking for relative files, and opening a file in a folder
the scope does not cover widens it and reindexes. A filelist still outranks
everything — it is the project file — and `"workspace"` restores the old walk
for anyone who wants it. The same round closes the ordering footgun the
previous round's QA found in `vlog_semantic::IndexBuilder`, which is what makes
the second half of the change safe: **the open buffers' files are fed to the
builder first**, so the progress bar completes the user's own files first, and
that is provably a reporting decision with no effect on the index.
## Assumptions
- **The scope ladder is one ladder with a new rung 3.** Highest first:
(1) a filelist — `lucisv.filelist`, else a `filelist` key in a root's config
— defines the scope exactly, unchanged and whole-project;
(2) `lucisv.index.scope: "workspace"` walks every workspace folder, which is
what every session did before this round;
(3) the default: the folders the open buffers live in, each raised
`lucisv.index.scopeDepth` levels, walked. Rung 2 needs a root to mean
anything, so a rootless session is folder-scoped whatever it says.
- **This is a behaviour change for every workspace user, and the honest
statement of it is that cross-file answers are scope-relative.** A symbol in
a folder the scope has not reached does not exist as far as this server is
concerned: `textDocument/definition`, `workspace/symbol`, the call and type
hierarchies, `find_references` and a workspace rename all answer within the
active scope, exactly as they already did within a filelist's. **The
migration line is `"lucisv.index.scope": "workspace"`**, which restores the
old behaviour exactly (pinned by
`the_workspace_scope_setting_restores_the_walk_of_every_root`).
- **The scope only ever grows within a session.** It is derived from every
directory a buffer has been opened *from* (`Workspace::opened_dirs`), not
from the buffers currently open, so `didClose` narrows nothing and costs no
rescan. The alternative — recomputing from the open set — would take a
working answer away at the next unrelated save, which is a worse surprise
than an index that is slightly larger than the editor's tab bar. It is also
the cheap choice: no reindex on close, and no reindex-on-close churn while a
user cycles through files.
- **`didOpen` rebuilds exactly when it widened the scope.** The rule is one
comparison of the scope directories across `set_document`, and it replaces
the old `has_roots()` branch (rootless reindexed, rooted published) with the
question that branch was really asking. Consequences, both deliberate: a
rootless session opening a *second* file in an already-scanned directory no
longer rebuilds (it used to, always), and a session on the filelist or
workspace rung never rebuilds on `didOpen`, because no open buffer can widen
those scopes.
- **The `didOpen` check costs two `scope_dirs()` calls, and each one asks
`filelist_path()` whether rung 1 is in force.** That is a `Discovery` walk up
from each root looking for a config — a handful of `exists()` calls, on an
event that is already about to reanalyze a whole buffer, and orders of
magnitude cheaper than the rebuild it decides against. Named here because it
is the one new per-notification cost this round adds.
- **A workspace folder is a clamp on the folder rung, not a work list.**
Adding one mid-session changes which files exist only once a buffer in it
makes it a scope directory; what it does change immediately is how far the
climb may go (see below). Removing one likewise only loosens the clamp. The
rescan `didChangeWorkspaceFolders` already triggers is unchanged.
- **The climb is clamped at the deepest workspace root containing the
directory** — that is what keeps `scopeDepth: 5` in a two-deep project from
indexing a home directory. **With no root there is nothing to clamp against
and the only floor is `/`**: the loop terminates there rather than spinning,
and the setting means exactly what it says. The rootless default is 0, so
nobody reaches this without asking for it; it is called out in the setting's
own description.
- **The rootless case is unchanged at the default.** A file opened on its own,
at depth 0, still gets a flat one-level read of its directory — no walk, no
`.gitignore` —
(`with_no_workspace_root_the_open_files_own_directory_is_indexed`, untouched
this round). The moment a rootless session raises `scopeDepth` it has named
a tree, so the raised directory is walked instead; that is the one place the
rung's behaviour depends on the depth being non-zero, and it is what stops a
raise from *losing* the file's own siblings.
- **One honest filter gap: a root's `.gitignore` does not reach a walk that
starts below it.** `lucisv_core::walk` reads ignore files from the walk's own
starting directory downwards, so a rule written at the workspace root is not
applied when the folder scope starts at `rtl/`. Every `exclude` pattern —
the config's and the pushed one — is matched against whole paths and is
unaffected. Pinned both ways in
`the_folder_scope_honours_every_exclude_and_the_gitignores_below_it`, rather
than left to be discovered. The fix belongs in `lucisv_core`'s walk (parent
ignore files, as the `ignore` crate does it) and is filed, not done: it is a
change to the CLI's walk semantics too, which is not this round's scope.
- **The startup index is empty, and that is the point.** No buffer is open at
`initialize`, so the folder scope has no folder yet; the first `didOpen`
widens it and rebuilds. On a huge project this is the whole saving. It also
means a client whose settings say `"workspace"` still gets one empty startup
scan and then a rescan when its settings land — the same one extra rescan
`lucisv.exclude` and `lucisv.filelist` have always cost, for the same reason
(neither settings door can deliver before `initialized`).
- **Open buffers still overlay every rung.** A buffer's text beats disk and a
buffer outside the scope still contributes itself, exactly as with a
filelist. Nothing about diagnostics, formatting or any single-file feature
depends on the scope: the per-buffer analysis is bottom-up and instant, and
this round does not touch it.
- **Wrong-typed settings fall back to the *narrow* default**, the same
direction `maxFileSize` falls back to the cap: a misparse must not silently
buy a whole-workspace scan. `"scope"` is matched exactly — `"Workspace"` is
junk — because the enum in `package.json` is what a settings UI offers and
forgiving it here would make a typo mean different things on different
clients.
- **The progress denominator, the cap counts and the output log follow the
active scope for free.** They all read the same work list
(`index_order`'s length, known before the first parse), so nothing was
re-plumbed; verified by `the_bar_names_the_open_file_before_the_rest_of_the_scope`
and by the e2e transcript, whose startup bar honestly ends `0 files indexed`.
## Handshakes
### `vlog_semantic` — `IndexBuilder` is order-insensitive
The previous round shipped `IndexBuilder` as a dumb accumulator whose ordering
contract was a doc comment ("feed it `index_order`'s list"), and its QA proved
that a caller who did not got different `FileId`s and a different winner for a
name two files declare (indexing-ux README, QA log 2026-08-27, MEDIUM). That is
closed by construction:
```rust
pub fn add_file(&mut self, path: PathBuf, src: &str); // parses, keeps FileFacts
pub fn finish(mut self) -> WorkspaceIndex; // sorts by path, dedups, merges
```
- `add_file` parses its file and reads off what it declares into a private
per-file record (`FileFacts`: the path, the `` `define`` table, the file-scope
declarations in declaration order, the members in traversal order). **The
parse still happens in `add_file`**, so a caller reporting progress between
calls is reporting work that has really been done.
- `finish` sorts those records by path — `sort_by` is stable, `dedup_by` keeps
the first of a run, which is exactly `index_order`'s rule — and only then
hands out `FileId`s and merges the declarations into the `units`/`members`
tables. No insertion order can reach the result.
- **`WorkspaceIndex::build` is byte-identical for every existing caller**, and
the proof is that all 31 pre-existing `vlog_semantic` tests are unchanged and
green, including `file_ids_follow_the_sorted_paths_whatever_order_they_arrive_in`,
`a_module_declared_in_two_files_is_ambiguous_in_path_order` and
`the_incremental_builder_is_what_build_is_made_of`. `build` still calls
`index_order` first — not for correctness now, but so a duplicate path is not
parsed twice.
- **Why this shape and not a type-enforced two-phase API.** The alternative the
brief allowed was a builder that cannot be misused because the types forbid
it — an `UnsortedBuilder` that only a `SortedFiles` value can be fed. That is
a second type, a second constructor and a conversion, to protect an invariant
that a five-line `sort_by`/`dedup_by` in `finish` removes outright. Making
the wrong call impossible beats making it a compile error when it costs less.
The cost is memory: the per-file records for the whole workspace are held
until `finish`, which is the same data the finished index holds (names,
spans, kinds), partitioned rather than merged — no `Semantics` and no source
text is retained.
- Permanent re-attack: `no_insertion_order_can_change_what_the_builder_produces`
(the QA pair plus a nested-class/defines fixture, in three orders, compared
by a full fingerprint of files, ids, disambiguation order, member tables and
define counts) and `a_path_added_twice_is_one_file_whichever_end_the_duplicate_is_at`.
- `index_order` stays public and unchanged: the server needs the work list's
*length* before the first parse for the progress denominator.
### `lucisv_server::settings`
- Two new fields, `index_scope: IndexScope` (`Folder` | `Workspace`, default
`Folder`) and `index_scope_depth: u64` (default 0), parsed from
`lucisv.index.scope` / `lucisv.index.scopeDepth`. Nested under `index` like
the other two, so both settings doors — push and pull — carry them with no
new code (`the_index_settings_come_through_the_pull_door_too`).
- `IndexScope` is public; `state.rs` matches on it.
### `lucisv_server::state`
- `Workspace::scope_dirs() -> Vec<PathBuf>` is **new and public**: the
directories the folder scope walks, or empty when the folder rung is not in
force. `server.rs` compares it across a `didOpen`.
- `Workspace::set_document` now also records the buffer's directory. It is the
one place a directory enters the scope.
- `walked_files` takes the directories to walk instead of reading `self.roots`;
`sibling_files` is a free function taking the same list.
- `has_roots()` is `#[cfg(test)]` now — `didOpen` was its only production
caller.
- Test-only `open_whole_workspace` / `open_whole_workspace_with` are the
one-line spelling of "this test wants the pre-round scope", used by the
dozens of tests across the crate whose subject is a hover or a rename rather
than the scope.
### `lucisv_server::server`
- `didOpen` reindexes when `scope_dirs()` moved, else publishes. One rule for
rootless and rooted; the rebuild rides the existing bar, generation bump,
code-lens refresh and republish.
- `Server::started(connection, roots, abilities, ClientSettings)` is the real
constructor and `Server::new` delegates to it with the defaults. The
parameter exists for the tests, which is stated where it is written: a test
whose subject is not the scope starts from the wide scope rather than driving
a `didChangeConfiguration` and then reasoning about the extra rescan.
### `editors/vscode`
- Two new `contributes.configuration` properties, both carrying the honesty
notes: what stops being answered, that the scope grows and never shrinks,
the migration line, and that a filelist overrides both. No `extension.js`
change — the whole `lucisv` section including the nested `index` object is
already synchronized.
## Status / TODO
- [x] `lucisv.index.scope` (`"folder"` default, `"workspace"` opt-in), both
settings doors, junk → the narrow default
- [x] `lucisv.index.scopeDepth` (default 0), clamped at the deepest containing
workspace root, and at `/` with no root
- [x] Filelist still outranks both; `scope`/`scopeDepth` ignored on rungs 1–2
- [x] `didOpen` widens the scope and reindexes; the rootless branch unified
into the same rule
- [x] Scope only grows within a session; `didClose` costs no rescan
- [x] Both settings join the rescan condition; `logFiles` still does not
- [x] Open buffers' files fed to the builder first; progress reports name them
first
- [x] `IndexBuilder` order-insensitive, with the QA attack as a permanent test
- [x] `package.json` descriptions carry the scope-relative-answers warning and
the migration line
- [x] 19 new tests (12 state, 2 server, 1 e2e, 2 vlog_semantic, 2 settings),
3 existing ones extended, 1 superseded test rewritten; every other test
in the crate that wanted the whole workspace now says so
- [ ] **Not done, deliberately:** no `lucisv.toml` key for either setting. They
are editor-session resource settings — how much of *this machine's* time
to spend — not project style, the same reason `maxFileSize` has none.
- [ ] **Not done, deliberately:** no shrink-on-close, no LRU on the scope, no
time-based eviction. All three are guesses at a problem nobody has
reported; the escape hatch for a session that grew too wide is to
restart it or set a filelist.
- [ ] **Filed, not done:** `lucisv_core::walk` does not read `.gitignore` files
above its starting directory, so a root-level ignore rule does not apply
to a folder-scoped walk. Fixing it changes the CLI's walk too.
- [ ] **Filed, not done:** the folder scope makes the write-path honesty gap
the previous round's QA found sharper — a workspace rename now rewrites
only what is in scope, and says nothing about what is not. The follow-up
task the lead filed for the size cap covers exactly this and should name
the scope too.
## Work log
### 2026-08-27 — dev agent (open-file-first indexing, folder-scoped walk)
- **The builder was hardened first, because the ordering change depends on
it.** Feeding the open files first is only free if insertion order provably
cannot reach the index, so `IndexBuilder` was rewritten to accumulate
`FileFacts` and sort in `finish` *before* anything in the server was
reordered. The five-line sort beat the type-enforced two-phase alternative
on every axis that matters here (one type instead of three, no conversion,
and the misuse becomes impossible rather than merely uncompilable); the price
is that the per-file records live until `finish`, which is the index's own
data partitioned rather than merged. `WorkspaceIndex::add_file`/`add_members`
became the free `facts_of`/`collect_members` with the same traversal, so the
merged tables come out in the same order they always did — which is why all
31 existing tests are byte-identical and green.
- **The scope ladder went in `source_files`'s rung 3, not beside it.** The
filelist rung and the walk are untouched; `default_files` now chooses between
`walked_files(&self.roots)` and `folder_files()`, and `folder_files` is
`walked_files(&scope_dirs())` with the one rootless exception. That kept the
exclude/gitignore/cap plumbing literally the same function, which is what
makes "every filter still applies" a fact rather than a claim.
- **`opened_dirs`, not `docs`, is what the scope is derived from.** This is the
close-shrink decision: the scope grows within a session and never narrows.
Deriving from the open documents would have been one less field, but it makes
`didClose` silently change what the *next* save indexes, which is a worse
surprise than a scope that is a few folders wider than the tab bar. It also
keeps `didClose` free of any rebuild.
- **`didOpen`'s branch is now one comparison, and it subsumes the rootless
rule.** `has_roots()` was answering "can an open buffer widen the scope?" by
proxy; `scope_dirs()` answers it directly and correctly on all three rungs.
Two deliberate deltas fell out and are documented: a rootless session opening
a second file in a directory it already read no longer rebuilds, and a
rootless session with a filelist no longer rebuilds on open either (the
filelist defines the scope; the buffer is overlaid at the next rebuild
regardless).
- **The clamp is the deepest containing root, not the first.** With nested
workspace folders the tighter floor is the honest one — the user opened both,
and the inner one is the more specific statement about that file.
- **The rootless flat read is kept at depth 0 and only at depth 0.** Turning it
into a walk would have changed the "a file opened on its own" case that has
its own documented reason to be shallow; leaving it flat at *every* depth
would have made `scopeDepth: 1` index the parent directory while losing the
file's own siblings, which is worse than either. So: unchanged at the
default, walked the moment the user raises the depth, and both halves pinned.
- **The startup scan indexes nothing now**, because no buffer is open yet. That
reads as alarming and is exactly the feature: the e2e transcript's first bar
ends `0 files indexed`, the `didOpen` bar reports the real file, and that
sequence is asserted on the wire.
- **The blast radius was 151 tests, and the honest fix was to make each of them
say what scope it wants.** Every test across the crate whose subject is not
the scope now calls `Workspace::open_whole_workspace` or `Session::wide`
instead of the plain form — a mechanical, reviewable change that leaves each
test exercising exactly what it exercised before, with the scope no longer a
hidden variable. Four settings pushes inside those tests gained
`"scope": "workspace"` for the same reason a push replaces every field. The
new default's own behaviour is covered by the 22 new tests rather than by
accident.
- **One test was superseded rather than repaired.**
`a_rootless_session_gaining_its_first_folder_flips_didopen_from_reindex_to_publish`
pinned the branch this round deletes; it is replaced by
`a_didopen_rebuilds_exactly_when_it_widens_the_scope`, same case list, under
the rule that replaced it, with an explicit `Superseded this round:` note in
the house style.
- **Two e2e expectations moved, both of them the model becoming visible on the
wire:** `indexing_reports_its_progress_over_the_wire` now shows three bars
(empty startup, the widening `didOpen`, the save) with the honest end
messages, and `a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire`
counts two refreshes because there are now two rescans in its script.
- **The `.gitignore` gap was found by a failing test I had written to assert
the opposite**, and is documented and pinned as a delta rather than papered
over or "fixed" by reaching into `lucisv_core`'s walk, which is the CLI's
too.
- Files touched: `crates/vlog_semantic/src/workspace.rs`,
`crates/vlog_semantic/tests/workspace.rs`,
`crates/lucisv_server/src/settings.rs`, `crates/lucisv_server/src/state.rs`,
`crates/lucisv_server/src/server.rs`, `crates/lucisv_server/tests/e2e.rs`,
the test modules of `completion/hierarchy/file_ops/includes/inlay/hover/lens/
nav/ports/rename/type_def/type_hierarchy/signature/symbols` (constructor
swap only), `editors/vscode/package.json`,
`docs/features/lucisv-server/README.md`,
`docs/features/indexing-ux/README.md`, this README. No new dependency, no
version bump, no `CHANGELOG` edit, no `docs/site/`, no commits.
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
--all-targets --workspace`: zero warnings. `cargo test --workspace`: **2217
passed, 0 failed** (2198 on `HEAD`, measured — 19 new). `cargo test -p vlog_formatter`:
green, untouched. `cargo build && node editors/vscode/smoke.js
target/debug/lucisv-server`: `smoke: OK`. `node -e JSON.parse(package.json)`:
parses.
The 19 new tests, the 3 extended and the 1 rewritten, and what each is for:
| test | pins |
|---|---|
| `no_insertion_order_can_change_what_the_builder_produces` (vlog_semantic) | QA's attack, three orders, full fingerprint — ids, disambiguation winner, member tables, defines |
| `a_path_added_twice_is_one_file_whichever_end_the_duplicate_is_at` (vlog_semantic) | `index_order`'s dedup rule surviving the move into `finish`, non-adjacent duplicate included |
| `the_index_scope_is_the_open_folder_until_a_client_asks_for_the_workspace` (settings) | the default, both words, six junk values → the narrow default |
| `the_scope_depth_is_zero_until_a_client_raises_it` (settings) | the default, no upper bound, six wrong types |
| `the_index_settings_come_through_the_pull_door_too` (settings) | both new keys through `from_section` as well |
| `the_default_scope_is_the_open_files_own_folder_and_everything_under_it` (state) | the headline: own folder and subtree, no sibling folder, nothing before a buffer opens |
| `a_scope_depth_of_one_reaches_the_folder_beside_it` (state) | the `rtl/` + `../include` layout the setting exists for |
| `the_climb_stops_at_the_workspace_root` (state) | the clamp at depth 99, and the deepest of two nested roots winning |
| `a_rootless_climb_stops_at_the_filesystem_root` (state) | termination at `/` with no root — on the directories, never walking one |
| `a_rootless_session_that_raises_the_depth_walks_instead_of_reading_one_level` (state) | the one exception, from the other side |
| `the_workspace_scope_setting_restores_the_walk_of_every_root` (state) | the migration line, and that the depth is ignored on that rung |
| `a_filelist_still_defines_the_scope_exactly_whatever_the_folder_rung_would_say` (state) | rung 1 over rung 3, and that no `didOpen` can widen a filelist |
| `closing_a_file_never_narrows_the_scope` (state) | the close decision |
| `the_folder_scope_honours_every_exclude_and_the_gitignores_below_it` (state) | both excludes, the in-scope `.gitignore`, **and** the root-`.gitignore` gap, both scopes |
| `a_folder_added_mid_session_widens_nothing_until_a_file_in_it_is_opened` (state) | folder events × the folder rung |
| `a_scope_or_a_depth_change_asks_for_a_rescan` (state) | both directions, both settings |
| `the_open_files_are_indexed_first_and_the_index_cannot_tell` (state) | the event order **and** that the index equals the plain-order one |
| `a_didopen_rebuilds_exactly_when_it_widens_the_scope` (server) | the unified rule: widens → rebuild, covered → publish only, rootless and rooted |
| `a_new_index_scope_or_depth_rescans_through_the_real_dispatch` (server) | parser + change test + rescan, end to end through `didChangeConfiguration` |
| `the_bar_names_the_open_file_before_the_rest_of_the_scope` (server) | `1/3 m_open.sv` first on the wire |
| `the_folder_scope_widens_when_a_file_in_another_folder_is_opened` (e2e) | the real binary: definition into a sibling folder empty, opening it resolves, and a `"workspace"` client resolves immediately |
| `indexing_reports_its_progress_over_the_wire` (e2e, updated) | the model on the wire: three bars, `0 files indexed` then `1 file indexed` twice |
## QA log
### 2026-08-27 — QA agent (gates, attack surfaces, mechanical-sweep audit)
**Gates, re-run clean on the untouched working tree.** `cargo fmt --all --
--check`: clean. `cargo clippy --all-targets --workspace`: zero warnings.
`cargo test --workspace`: **2217 passed, 0 failed, 5 ignored** (matches the
dev's count exactly). `cargo test -p vlog_formatter`: 114 passed, untouched.
`cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`:
`smoke: OK`. Every temporary probe test below was inserted, run alone, and
reverted before the final re-run; the final `git diff` of `state.rs`/`server.rs`
hashes identically to the pre-QA diff, confirming no probe was left behind.
**The 151-test mechanical sweep.** Sampled all 14 non-scope test modules
(`completion`, `file_ops`, `hierarchy`, `hover`, `includes`, `inlay`, `lens`,
`nav`, `ports`, `rename`, `signature`, `symbols`, `type_def`,
`type_hierarchy` — every `.open_roots(` call in them, ~40 sites) plus the
`server.rs`/`state.rs` `Session::wide`/`Workspace::open_whole_workspace`
call sites: **every one is a pure constructor swap** (`open_roots` →
`open_whole_workspace`, or `Session::with`/`Session::new` →
`Session::wide`/`Session::wide_with`, or a `"scope": "workspace"` key added
to a settings push). No sampled assertion changed beyond that. Verdict:
**mechanical sweep is genuinely mechanical**, as claimed.
**The inverse hunt (tests that should have been swapped but weren't) found
one real bug and two weakened premises**, all in `state.rs`'s own test
module, which is the one file that still has bare `.open_roots(` calls
mixed in with the new scope tests:
- **MEDIUM — `a_folder_added_twice_across_two_events_is_absent_after_one_removal`
(`crates/lucisv_server/src/state.rs:851-876`) no longer tests what it
says it does.** It calls `ws.open_roots(...)` but never opens any buffer,
so under the new default (folder scope) `scope_dirs()` is empty for the
entire test and `"x"` is never indexed — not because of the root
add/remove/dedup logic under test, but because nothing is ever in scope.
The final `assert_eq!(indexed(&ws, &["x"]), [])` passes vacuously.
Confirmed by temporarily inserting a premise check
(`assert_eq!(indexed(&ws, &["x"]), ["x"])`) right after the first
`change_roots` add and running the test alone: **it failed**
(`left: [] right: ["x"]`), proving the premise never held. The
`change_roots` return-value assertions (`true`/`false`/`true`) are
unaffected and still test the set-not-multiset behavior correctly — only
the closing `rebuild_index`/`indexed` pair is vacuous. Fix: either open a
buffer in `extra`'s directory before checking, or switch to
`open_whole_workspace` and keep the indexed-content assertion meaningful.
Not fixed directly — it is a one-line-comment-vs-actual-behavior mismatch
that the dev should decide the intended fix for (open a buffer, since the
test's own comment is about indexing, not about scope).
- **LOW — `an_open_buffer_is_indexed_however_big_the_file_is`
(`state.rs:1151-1168`)'s "premise: capped on disk" assertion is now true
regardless of the cap**, because no buffer is open at that point either,
so folder scope is empty and nothing is indexed for that reason first.
The test's actual point (the open buffer overrides the cap after
`set_document`) still holds and is still meaningfully exercised, since
`set_document` adds the directory to scope before the second
`rebuild_index`. Not a false pass on the assertion that matters, but the
premise no longer demonstrates what its comment claims.
- **LOW — stale rung numbers in comments**, not behavior:
`without_a_filelist_there_are_no_incdirs_at_all` (`state.rs:1454-1462`)
says "Rung 2 of the ladder names no include path," and
`a_broken_filelist_leaves_the_include_graph_without_incdirs`
(`state.rs:1464-1475`) implies the same fallback. Both are now rung 3
(folder scope) by default, not rung 2 — the assertions (`None` either way,
since no filelist means no incdirs regardless of which walk rung ran) are
unaffected, but the comments should say "rung 2 or 3" or just "the
fallback."
All other `.open_roots(` calls left bare in `state.rs` were individually
checked and are correct as left: the filelist tests (rung 1 always wins,
scope-independent), the rootless tests (rung 3 is the only rung with no
root, unaffected), and `a_folder_change_that_changes_nothing_asks_for_no_rescan`
/ `a_trailing_slash_in_the_removed_folder_still_matches_the_held_root` (test
`change_roots`'s bookkeeping only, no indexed-content assertion to weaken).
**Scope correctness at the boundaries — all traced and probed, all correct,
none pinned by a permanent test beyond what's listed below:**
- Depth clamping when the open file *is* at the root: `raised()`'s first
loop iteration compares `out == floor` before descending, so a root-level
buffer returns immediately at any depth. Covered by
`the_climb_stops_at_the_workspace_root`.
- Nested roots, deeper clamps tighter: `max_by_key(|root|
root.components().count())` — confirmed by the same test's second half.
- `scopeDepth` past the path depth: terminates at `/` (rootless) or the
containing root (rooted), confirmed by
`a_rootless_climb_stops_at_the_filesystem_root` and the depth-99 case in
`the_climb_stops_at_the_workspace_root`.
- **A file opened from outside every workspace root, with roots present
(folder scope still the active rung): no permanent test covers this.**
Probed with a temporary test (root A open, a buffer opened from an
unrelated tree B): `scope_dirs()` at depth 0 is just B's own directory,
and raising `scopeDepth` to 99 climbs all the way to `/` — exactly the
rootless behavior, because `raised()`'s `floor` is `None` when no root
contains the directory. **Correct, but untested and not called out in the
README's Assumptions** as a distinct case from "rootless session."
Recommend a pinned test plus a sentence in the README.
- Symlinked folders / case differences on macOS: `opened_dirs` dedups by
literal `PathBuf` equality (`seen == dir`), not canonicalized — a symlink
and its target, or `/RTL` vs `/rtl`, are two separate scope directories
that both get walked. **Not a regression**: the pre-round `sibling_files`
deduped the same way. Informational only.
**The grows-only model's costs.** Opening three folders then closing all
three: union sticks, verified with a temporary test (three folders opened,
all three closed, `rebuild_index`, same five packages still indexed) — not
just the dev's one-of-two-closed case. The pathological end (opening files
across many folders converges the walk cost back toward the whole-workspace
walk this round exists to avoid) is **acknowledged only indirectly** — the
README's "Not done, deliberately" section says there's no shrink/LRU/TTL and
names "restart or set a filelist" as the escape hatch, but never states the
asymptotic point plainly. Recommend one sentence owning it, e.g. "a session
that has opened files in most of the project's folders pays close to the
whole-workspace walk on every rescan; that is the trade, not a bug."
**Builder hardening.** `no_insertion_order_can_change_what_the_builder_produces`
and `a_path_added_twice_is_one_file_whichever_end_the_duplicate_is_at` both
pass. Independently re-derived the "first wins" claim from first principles
rather than trusting the doc comment: wrote a 6-line scratch program
exercising `Vec::sort_by` + `Vec::dedup_by` with the exact closure shape used
in `finish` (`sort_by(|a,b| a.path.cmp(&b.path))` then
`dedup_by(|a,b| a.path == b.path)`) on `[("a",1),("a",2),("b",3)]`; it
produces `[("a",1),("b",3)]`, confirming `dedup_by` really does keep the
first of a run in this position (the docs' phrasing invites an off-by-one
misreading given the reversed-argument-order caveat). `add_file` after
`finish`: prevented at compile time — `finish(mut self)` consumes the
builder, so this is Rust's ownership system doing exactly what a type-state
`SortedFiles` wrapper would do, for free, matching the README's stated
rationale for not building one. Empty builder `finish()`: sorts/dedups an
empty `Vec`, loop body never runs, returns `WorkspaceIndex::default()` — no
panic, consistent with `an_empty_workspace_answers_nothing_and_panics_nowhere`
already covering `WorkspaceIndex::build([])` through the same path.
**Cross-feature interaction sweep — verified clean, and structurally so
rather than by accident.** `symbols.rs`, `lens.rs`, `type_hierarchy.rs` all
read from `ws.index()` directly; `rename.rs` reads from `ws.sources()`,
which is `collect_sources(...).texts`, the exact same `source_files()` ladder
`rebuild_index` uses. There is one scope-aware code path, not one per
feature, so "workspace/symbol, codeLens, typeHierarchy and rename all answer
in-scope only" is a structural fact, not a per-feature promise that could
drift. `workspace/diagnostic` (`server.rs:988` `workspace_report`) iterates
`self.workspace.open_uris()` only — confirmed independent of the index
scope entirely, exactly the "unaffected" claim. The cap composes with scope
by construction too: `collect_sources` applies `max_file_size` to
`scope.files`, which is already the scope-filtered list — no special-casing
needed, none found.
**Migration path.** Rather than diff against a `git stash` baseline binary,
verified the stronger claim algebraically: `default_files()`'s
`walks_the_workspace()` branch calls `self.walked_files(&self.roots)`, and
`walked_files(dirs: &[PathBuf])`'s body is byte-identical to the pre-round
`walked_files(&self)`'s body with `&self.roots` substituted for `dirs` at
every use — confirmed by re-reading the diff hunk line by line. So
`scope: "workspace"` is not merely equal in practice to the pre-round
default, it is the same function called with the same argument, which is a
stronger guarantee than a fixture comparison could give. `from_section`
delegates to `from_payload` with zero new code (`settings.rs:208-210`), so
both settings doors carrying the two new keys is confirmed structurally.
**Own-shapes probes (C), all via temporary tests, all reverted:**
- Rapid `didOpen` across 10 distinct folders: generation increases by
exactly 20 (2 per widening open), completes in ~0.02s — no quadratic
blowup at this scale. `opened_dirs.sort()` runs on every `set_document`
and `scope_dirs()` sorts+dedups again on every call (twice per `didOpen`),
which is O(n log n) per open and O(n² log n) over a session — fine at
realistic folder counts, worth knowing if a future report cites hundreds
of folders in one session.
- Lowering `scopeDepth` mid-session (1 → 0) via `set_client_settings`:
**does narrow the index on the next rebuild**, unlike closing a buffer.
This is correct and is the right answer (a settings change is a
deliberate user action, not the same "never take away an answer" case
`didClose` is), but **no permanent test pins it** and the README's
Assumptions section states "the scope only ever grows" without
distinguishing the open/close axis (grows-only) from the settings axis
(moves either way). Recommend a test plus a clarifying sentence.
- A filelist appearing mid-session (settings push) while folder scope was
active: flips the ladder to rung 1 immediately on the next rebuild
(`folder_scoped()` re-checks `filelist_path()` fresh every call, and
`set_client_settings`'s rescan condition already includes `filelist`
changes). Correct, and covered indirectly by the existing rescan test,
but there is no test that also checks the *index content* actually
changes to the filelist's files rather than just triggering a rescan —
probed with a temporary test, passed.
**CLAUDE.md compliance.** `verify.rs` untouched (no diff, confirmed by
`git diff --name-only`). No new `unwrap()`/`expect()`/`panic!` outside
`#[cfg(test)]` modules in the round's diff (grepped the four core files'
diffs for all three patterns; every hit is inside `mod tests`). Doc comments
present on every new public item (`IndexScope`, `ClientSettings::index_scope`
/`index_scope_depth`, `Workspace::scope_dirs`). `has_roots()` confirmed
genuinely `#[cfg(test)]`-only — grepped every call site in the crate, all
seven are inside `#[test]` functions. README sections present exactly once.
`TODO.md`'s M1 annotation accurately describes the new default and points at
this feature's README. Corpus tests still skip-guarded (`if !corpus.exists()
{ return; }` pattern unchanged, only their `open_roots` calls swapped).
**One item beyond the brief, informational only:** `editors/vscode/package.json`'s
`lucisv.index.scope` description says the pre-round behavior is "as lucisv
did before 0.11" — a forward guess at the next release number. This round
makes no version bump (confirmed: `Cargo.toml` and `package.json` both still
say `0.10.2`). Not wrong today, but it is a claim about a future version
number sitting in a shipped-looking description; worth a quick check by
whoever cuts the next release that it lands on 0.11 and not, say, 0.10.3 or
0.12.
**Not touched:** `docs/site/` (per instructions), no commit, no push
attempted (remote noted as flaky).
**Verdict: committable as-is**, modulo the dev's call on the one MEDIUM
finding (the vacuous `a_folder_added_twice_across_two_events_is_absent_after_one_removal`
assertion — a real but narrow test-coverage gap, not a product bug: nothing
about `change_roots`'s actual dedup/removal behavior is broken, only that
one test no longer demonstrates it). The two LOW-MEDIUM missing-permanent-test
items (out-of-root buffer under folder scope; depth-narrows-on-settings-change)
and the stale-comment LOW items are follow-up hygiene, not blockers — every
behavior they probe was independently verified correct by hand in this
session.
## Review
### 2026-08-27 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself
(2217 workspace tests, 0 failed), clean. The round delivers the owner's
model exactly and the two structural decisions are right: scope grows
only along the open axis (recomputing from the open set would take
working answers away on unrelated saves), and the builder hardening
makes the open-files-first ordering provably a reporting nicety — QA
independently re-derived the dedup-keeps-first-copy claim and confirmed
misuse-after-finish is prevented by ownership, which is the cheapest
kind of enforcement there is. The migration path being the same
function rather than an equal-output one is the strongest form of the
"workspace restores today" promise.
Lead actions on QA's findings before commit: the vacuous
folder-add/remove test now runs whole-workspace scope with a
present-while-added assertion restored (the MEDIUM); the big-buffer
cap test's premise is the cap's doing again; the stale rung comments
and the forward-guessed version string in the setting description are
corrected. The behaviors QA verified by hand but left unpinned
(depth-narrowing on a settings change, a mid-session filelist flipping
the ladder, an outside-root buffer on the folder rung) are accepted on
that verification and assigned to round 19's brief as permanent-test
obligations — its dev works in these exact files next. The
gitignore-below-root delta stays filed against lucisv_core. Accepted
as shipped.
+16 -1
View File
@@ -133,6 +133,11 @@ pub fn build<'a>(files: …) -> WorkspaceIndex {
plain `build` the same index — and the server needs the list's length before
the first parse anyway, for the progress denominator. It is the honest
alternative to a comment telling callers to sort.
**Superseded in part (index-scope, 2026-08-27):** ~~the builder hands out
`FileId`s in call order~~ — it sorts inside `finish` now, so feeding it
`index_order`'s list is no longer required for correctness. `index_order`
stays public and unchanged for the denominator, and `build` still calls it so
a duplicate path is not parsed twice.
- **Proof of equivalence: every existing `vlog_semantic` test is unchanged**
and every one of them goes through `build`. One new test
(`the_incremental_builder_is_what_build_is_made_of`) drives the builder path
@@ -258,6 +263,9 @@ nine sizes, and a real 1100-file workspace end to end.
survives with the log off, in the `end` message
- [x] `vlog_semantic::IndexBuilder` + `index_order`, with `build` redefined as
the loop over them and every existing test unchanged
— ~~and the builder's ordering contract carried by a doc comment~~
**superseded (index-scope, 2026-08-27): `finish` sorts, so the contract
is the code**
- [x] `package.json` declares both settings, with the 0-disables semantics and
the open-buffer exemption in the descriptions
- [x] 21 new tests; 7 existing progress tests updated for the reports
@@ -409,7 +417,14 @@ module name (`z_late.sv` / `a_early.sv`, both declaring `dup`) through `build`
and through a manual `index_order` + `IndexBuilder` loop: same `FileId`s, same
disambiguation winner (`a_early.sv` first, both ways).
But `IndexBuilder` itself enforces nothing — it is a dumb accumulator, and the
But **Closed by index-scope, 2026-08-27** (see `docs/features/index-scope/README.md`):
`IndexBuilder::add_file` now keeps its file's declarations to itself and
`finish` sorts them by path before handing out any `FileId`, so no insertion
order can reach the result. QA's construction below is a permanent test,
`no_insertion_order_can_change_what_the_builder_produces`. The finding as
filed, kept legible:
`IndexBuilder` itself enforces nothing — it is a dumb accumulator, and the
ordering guarantee is carried entirely by the doc comment ("Feed it
`index_order`'s list"), not the type system. Direct attack, temporarily added
to `crates/vlog_semantic/tests/workspace.rs` and run:
+38 -3
View File
@@ -234,7 +234,7 @@ reasoning and the measurements: `docs/features/cancel-request/README.md`.
| layer | rebuilt when | cost |
|---|---|---|
| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` — **once per notification**, however many ranges it carried | one file, full recompute |
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist`/`lucisv.index.maxFileSize` (pushed **or** pulled) | full re-scan of the roots |
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `textDocument/didOpen` that **widens the scope**, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist`/`lucisv.index.maxFileSize`/`lucisv.index.scope`/`lucisv.index.scopeDepth` (pushed **or** pulled) | full re-scan of the scope |
| the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save |
**Per-file recompute on every keystroke** is the strategy TODO.md §6 states
@@ -244,10 +244,36 @@ ranges, but a `didChange` still throws the whole `Document` away and builds a
new one — one reparse per notification, which is also the one generation bump
the pull-diagnostics `resultId` depends on.
**Open buffers override disk** in every index rebuild: the roots are walked,
**Which files exist: the folder scope, since 2026-08-27** (index-scope). The
index no longer walks the whole workspace by default. The ladder, highest
first: a **filelist** defines the scope exactly, as it always has; else
`lucisv.index.scope: "workspace"` walks every workspace folder, which is what
every session did before this round and is now opt-in; else — the default —
the scope is **the folders the open buffers live in**, each raised
`lucisv.index.scopeDepth` levels (0 by default, clamped so it never climbs out
of the workspace folder containing it) and walked with every filter the wide
walk applies. Opening a file in a folder the scope does not cover **widens the
scope and rebuilds**, on the same bar and the same generation bump every other
rescan gets; closing one narrows nothing, ever. The startup index is therefore
empty until the first `didOpen`, which is the whole saving on a large project.
**Stated plainly, because it is what a user notices:** every cross-file answer
in the table above is **scope-relative**. A definition, a `workspace/symbol`
hit, an `incomingCalls` census, a `subtypes` list, a `find_references` sweep or
a workspace rename covers the files in scope and no others — a symbol in a
folder the scope has not reached does not exist as far as this server is
concerned, exactly as one outside a filelist never did. Opening a file in that
folder brings it into scope. `"lucisv.index.scope": "workspace"` restores the
pre-2026-08-27 behaviour in full. Rules, the clamp, the close decision and the
one `.gitignore` gap: `docs/features/index-scope/README.md`.
**Open buffers override disk** in every index rebuild: the scope is walked,
each file read, and then every open document with a path replaces the disk
copy (adding itself if it exists only in the editor). So the index never
disagrees with a buffer the user is looking at.
disagrees with a buffer the user is looking at. The open buffers' own files are
also fed to the index builder **first**, so a long rescan's progress bar
completes them before anything else; the builder sorts by path internally, so
that ordering cannot change the index it produces.
**Walked files over `lucisv.index.maxFileSize` (1 MiB by default) are not read
at all** — the size is taken from `fs::metadata` before the read, so a
@@ -342,6 +368,15 @@ not see.
drive-letter rule (`file:///C:/x` → `C:\x`) is written and compiled but
**untested on Windows** — it is behind `cfg!(windows)` so it cannot misfire
on a POSIX path legitimately named `/C:`.
- ~~**The workspace walk is plain.** `initialize`'s `workspace_folders`
(falling back to `root_uri`) are walked recursively.~~ **Superseded
(index-scope, 2026-08-27): the folders are the *clamp* now, not the work
list. What is walked by default is the folders the open buffers live in,
raised `lucisv.index.scopeDepth` levels; `lucisv.index.scope: "workspace"`
asks for the walk this paragraph describes. See the model section above and
`docs/features/index-scope/README.md`.** The rest of the paragraph — the
extensions, the `.gitignore` handling, the mid-session folder changes — is
unchanged and still applies to whichever directories are walked.
- **The workspace walk is plain.** `initialize`'s `workspace_folders` (falling
back to `root_uri`) are walked recursively for `*.v`/`*.sv`/`*.vh`/`*.svh`.
~~They are read once and frozen for the session.~~ **Superseded
+16
View File
@@ -235,6 +235,22 @@
"default": "",
"markdownDescription": "Path to an EDA filelist (`.f`), absolute or relative to the workspace folder. When set, **exactly** the files it names are indexed instead of the whole folder — `-f` nesting, `+incdir+`, `+define+`, `#`/`//` comments and `$VAR` expansion are all understood. Overrides a `filelist` key in the project's `lucisv.toml`; leave it empty to index the workspace folder."
},
"lucisv.index.scope": {
"type": "string",
"enum": ["folder", "workspace"],
"enumDescriptions": [
"Index the folders your open files live in, and everything under them.",
"Index every folder in the workspace, whatever is open."
],
"default": "folder",
"markdownDescription": "How much of your project the workspace index scans. **`folder` (the default) indexes only the folders your open files live in** — plus everything under them — which is what keeps a huge project from costing minutes on every scan. Opening a file in another folder widens the index to that folder as well, so the scope grows as you work; it never shrinks while the editor is open. **Until it reaches a folder, symbols in that folder do not exist as far as the server is concerned**: go-to-definition, workspace symbol search, call and type hierarchy, find-references and rename all answer within the current scope only. Set to `workspace` to index every workspace folder up front, as lucisv always did before this setting existed — the right choice for a small project or a fast machine. A `#lucisv.filelist#` overrides this setting entirely: a project file defines the scope."
},
"lucisv.index.scopeDepth": {
"type": "number",
"default": 0,
"minimum": 0,
"markdownDescription": "How many folders **above** an open file the `folder` scope starts from — the reach for relative files. `0` (the default) is the file's own folder and everything under it. `1` starts one folder up, so a file in `rtl/` also indexes `include/` beside it. The climb never leaves the workspace folder that contains the file, so a large number simply means the whole workspace folder. Raising this widens every answer listed under `#lucisv.index.scope#` and costs a larger scan. Ignored when `#lucisv.index.scope#` is `workspace` or a `#lucisv.filelist#` is set. With **no** workspace folder open there is nothing to clamp the climb against, so leave it at `0` for single files."
},
"lucisv.index.maxFileSize": {
"type": "number",
"default": 1048576,