Files
lucisv/crates/lucisv_server/src/server/tests/folders.rs
T
lucioandClaude Fable 5 b96827c51d Decomposition, lane C: lucisv_server's server.rs and completion.rs become modules, a pure move
TODO section 28, lane C (the file-size rule in CLAUDE.md).
server.rs (2 559 production + 6 293 test lines) becomes server/{mod,
dispatch, client, index, notification, progress, diagnostics, batch,
formatting, large_file, semantic_tokens}.rs with the tests in
server/tests/ (16 files, one per former banner section, 15 shared
helpers hoisted into the harness); completion.rs (1 716 + 2 463)
becomes completion/{mod, member, module, tiers, word, site,
harness}.rs with each provider's tests beside it. answer_request (393)
and handle_notification (197) stay whole as the dispatch tables they
are; perf.rs stays whole because its one sentence has no and. Every
import elsewhere in the crate resolves through pub(crate) re-exports,
so main.rs, inline.rs, instantiate.rs, hover.rs, nav.rs and state.rs
are byte-identical. Proof: per-binary counts identical (1 435 / 85 / 3;
workspace 3 215 / 48), e2e and the vsix smoke green, a live LSP session
against opentitan answering byte-identically from this build and the
base, and a line-multiset + signature census (360/360, 188/188) done
by the dev and redone from scratch by QA.

docs/features/decomposition-server/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 21:33:48 -07:00

443 lines
20 KiB
Rust

//! Workspace folders (2026-08-27) and the scope a `didOpen` widens.
use super::*;
// ------------------------------------------------------------------
// workspace folders (2026-08-27)
// ------------------------------------------------------------------
/// A `workspace/didChangeWorkspaceFolders` event, as a client sends it.
fn folder_event(added: &[&Path], removed: &[&Path]) -> Value {
let folders = |paths: &[&Path]| -> Vec<Value> {
paths
.iter()
.map(|path| {
serde_json::json!({
"uri": path_to_uri(path).expect("uri"),
"name": path.file_name().and_then(|n| n.to_str()).unwrap_or("folder"),
})
})
.collect()
};
serde_json::json!({ "event": { "added": folders(added), "removed": folders(removed) } })
}
fn folders_changed(session: &mut Session, added: &[&Path], removed: &[&Path]) {
session.notify(DidChangeWorkspaceFolders::METHOD, folder_event(added, removed));
}
#[test]
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("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 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, "a new folder widens by reindexing");
folders_changed(&mut session, &[&folder.path], &[]);
assert!(session.server.workspace.has_roots(), "the workspace now has a root");
// 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("rtl/b.sv"), "package b;\n localparam K = 1;\nendpackage\n");
assert_eq!(
session.server.generation,
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"
);
assert!(
session.published().iter().any(|p| p.uri == uri),
"it is still published, just not rescanned"
);
}
#[test]
fn widen_of_takes_the_cheap_path_for_a_pure_add_and_nothing_else() {
// The chooser, as a table. Everything but "grew and lost nothing"
// falls back to the whole rescan, which is always a correct answer.
let a = PathBuf::from("/w/a");
let b = PathBuf::from("/w/b");
let c = PathBuf::from("/w/c");
let all = [a.clone(), b.clone(), c.clone()];
assert_eq!(widen_of(&[], &[]), Widen::Nothing, "a scope that never moved");
assert_eq!(
widen_of(&all, &all),
Widen::Nothing,
"and one an open buffer could not widen — a filelist or the wide rung, both empty"
);
assert_eq!(
widen_of(std::slice::from_ref(&a), &[a.clone(), b.clone()]),
Widen::Added(vec![b.clone()]),
"one folder added: only that folder is indexed"
);
assert_eq!(
widen_of(&[], &all),
Widen::Added(all.to_vec()),
"the first open of a session adds every directory it has"
);
assert_eq!(
widen_of(std::slice::from_ref(&b), &[a.clone(), b.clone(), c.clone()]),
Widen::Added(vec![a.clone(), c.clone()]),
"two added around one held: both, and never the held one"
);
// The `scopeDepth: 2` shape `performance_take2.md` §5b measured: the
// newly opened file raises to a directory that *contains* one already
// in scope. The contained directory is still in `after` — every opened
// directory is raised on its own and none of them is ever dropped — so
// this is an add like any other, and the widen's own file diff is what
// stops the overlap being read twice
// (`state::tests::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`).
let ip = PathBuf::from("/w");
assert_eq!(
widen_of(std::slice::from_ref(&a), &[ip.clone(), a.clone()]),
Widen::Added(vec![ip]),
"a folder that subsumes the old scope is an add, not a removal"
);
assert_eq!(
widen_of(&[a.clone(), b.clone()], std::slice::from_ref(&a)),
Widen::Whole,
"a directory that left is not an add: the whole rescan settles what went with it"
);
assert_eq!(
widen_of(&[a.clone(), b.clone()], &[a, c]),
Widen::Whole,
"and a swap is a removal too, however many arrived beside it"
);
}
#[test]
fn a_didopen_widen_leaves_the_index_a_whole_rescan_would_have_left() {
// The round's claim, through the real dispatch: two jumps into two new
// folders, each answered by indexing only that folder, and the tables
// that come out are the ones a whole rescan produces — asked by
// running that rescan afterwards and comparing.
let tree = Tree::new("didopenwidenequal");
tree.package("rtl/a.sv", "a");
tree.package("rtl/a2.sv", "a2");
tree.package("lib/b.sv", "b");
tree.package("lib/b2.sv", "b2");
tree.package("tb/c.sv", "c");
let mut session = Session::new(vec![tree.path.clone()], false);
let _ =
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
let _ =
session.open(&tree.path.join("lib/b.sv"), "package b;\n localparam K = 1;\nendpackage\n");
let _ =
session.open(&tree.path.join("tb/c.sv"), "package c;\n localparam K = 1;\nendpackage\n");
assert_eq!(session.server.workspace.index().files().len(), 5, "all three folders");
assert_eq!(indexed(&session, "b2"), 1, "including files nobody opened");
let widened = session.server.workspace.index().fingerprint();
let words = session.server.workspace.candidates().words("").to_vec();
let includes = session.server.workspace.includes().fingerprint();
session.server.workspace.rebuild_index();
assert_eq!(widened, session.server.workspace.index().fingerprint(), "index");
assert_eq!(words, session.server.workspace.candidates().words(""), "completion words");
assert_eq!(includes, session.server.workspace.includes().fingerprint(), "include graph");
}
#[test]
fn a_widen_asked_for_mid_scan_defers_to_one_whole_rescan_behind_it() {
// A widen answered while a scan runs cannot fold itself in: that scan
// holds a work list taken from the *old* scope, so folding a widen
// into it would make "which files exist" mean two things inside one
// scan. It sets the same `rescan_wanted` flag every other mid-scan
// trigger sets — one more whole scan after this one, coalesced with
// whatever else asked (`docs/features/scan-interleave/README.md`).
//
// Driven directly rather than over the wire, because the wire cannot
// reach it in one step: a widen itself never drains the queue, and the
// startup scan under the folder scope indexes nothing and so never
// interleaves. The reachable route is a `didOpen` answered inside a
// long *whole* rescan, which is this flag and this call.
let tree = Tree::new("widenmidscan");
tree.package("rtl/a.sv", "a");
tree.package("lib/late.sv", "late");
let mut session = Session::new(vec![tree.path.clone()], false);
// The shipped depth is 2 since 2026-08-28, which would have `lib/` in
// scope before the widen this test is about — so the premise names the
// narrow depth rather than assuming it.
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "index": { "scopeDepth": 0 } } } }),
);
let _ =
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
assert_eq!(indexed(&session, "a"), 1, "premise: the first folder is in scope");
session.server.scanning = true;
session.server.reindex_widened(vec![tree.path.join("lib")]);
assert!(session.server.rescan_wanted, "the widen was deferred, not run inside the scan");
assert_eq!(indexed(&session, "late"), 0, "and nothing was folded into the running scan");
// What the running scan's own loop then does with the flag.
session.server.scanning = false;
let warnings = session.server.scan_until_settled(true);
assert!(warnings.is_empty(), "{warnings:?}");
assert!(!session.server.rescan_wanted, "one more scan is all it was owed");
// Not indexed, and correctly so: the deferred rescan is a *whole* one
// over the scope as it now stands, and `lib/` entered that scope only
// because a buffer was opened from it — which this test never did.
assert_eq!(indexed(&session, "late"), 0, "the scope itself did not move");
}
#[test]
fn a_folder_added_mid_session_is_indexed_and_answers_workspace_symbol() {
// The whole point: "Add Folder to Workspace" used to change nothing
// until the editor was restarted.
let first = Tree::new("folderadd");
first.package("rtl/a.sv", "a");
let second = Tree::new("folderaddsecond");
second.package("rtl/b.sv", "b");
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], &[]);
assert_eq!(indexed(&session, "b"), 1, "the added folder is scanned");
assert_eq!(indexed(&session, "a"), 1, "and the one already open survives");
// And it is reachable through a real request, not only in the index.
let hits = session.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query":"b"}));
let found = hits.as_array().expect("a symbol list");
assert!(
found.iter().any(|hit| hit["location"]["uri"]
.as_str()
.is_some_and(|uri| uri.contains("folderaddsecond"))),
"{found:#?}"
);
}
#[test]
fn a_removed_folder_leaves_the_index_and_its_open_buffer_keeps_being_diagnosed() {
// The client owns buffer lifecycle: closing a folder does not close
// the editors that were open in it. Such a buffer keeps the deal
// every rootless buffer has always had — it is still analyzed, still
// published, and still overrides disk in the index.
let first = Tree::new("folderremove");
first.package("rtl/a.sv", "a");
let second = Tree::new("folderremovesecond");
second.package("rtl/open.sv", "open_pkg");
second.package("rtl/other.sv", "other_pkg");
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",
);
assert_eq!(indexed(&session, "other_pkg"), 1, "premise: the whole folder is indexed");
folders_changed(&mut session, &[], &[&second.path]);
assert_eq!(indexed(&session, "other_pkg"), 0, "the folder's files left the index");
assert_eq!(indexed(&session, "a"), 1, "the folder that stayed is untouched");
assert_eq!(
indexed(&session, "open_pkg"),
1,
"the open buffer contributes itself, as every out-of-scope buffer does"
);
// The rebuild republished it, and an edit to it is still diagnosed.
let published = session.published();
assert!(published.iter().any(|p| p.uri == uri), "{published:#?}");
change(
&mut session,
&uri,
2,
serde_json::json!([{ "text": "package open_pkg;\n localparam ;\nendpackage\n" }]),
);
let published = session.published();
assert_eq!(published.len(), 1, "{published:#?}");
assert_eq!(published[0].uri, uri);
assert!(!published[0].diagnostics.is_empty(), "a broken buffer still reports");
// And closing it clears cleanly — the removed folder is not a special
// case for `didClose`, which already sends an empty publish for
// whatever buffer is named regardless of where it lived.
// QA (2026-08-27): pinned per the dev's own review checklist item.
session.notify(
DidCloseTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
let published = session.published();
assert_eq!(published.len(), 1, "{published:#?}");
assert_eq!(published[0].uri, uri);
assert!(published[0].diagnostics.is_empty(), "the close cleared it");
}
#[test]
fn one_folder_notification_is_one_rescan_with_one_bar_and_one_generation() {
// Everything a rescan owes rides inside `reindex()`; an event carries
// both lists, so it must cost exactly one of each.
let first = Tree::new("folderonce");
first.package("rtl/a.sv", "a");
let second = Tree::new("folderoncesecond");
second.package("rtl/b.sv", "b");
let third = Tree::new("folderoncethird");
third.package("rtl/c.sv", "c");
let abilities =
ClientAbilities { work_done_progress: true, code_lens_refresh: true, ..Default::default() };
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();
// One notification that both adds and removes: two changes, one scan.
folders_changed(&mut session, &[&third.path], &[&second.path]);
assert_eq!(indexed(&session, "c"), 1, "the addition took");
assert_eq!(indexed(&session, "b"), 0, "and so did the removal");
assert_eq!(session.server.generation, before + 1, "one generation bump");
let messages = session.drain();
let steps: Vec<&'static str> =
messages.iter().cloned().filter_map(progress_step).map(|(step, _)| step).collect();
// One bar, up and down — with a report for each of the two files the
// new root set holds (`a.sv` and `c.sv`).
assert_eq!(steps, vec!["create", "begin", "report", "report", "end"], "one bar");
let publishes = messages
.iter()
.filter(|m| matches!(m, Message::Notification(n) if n.method == PublishDiagnostics::METHOD))
.count();
assert_eq!(publishes, 1, "the one open buffer is republished once");
let refreshes = messages
.iter()
.filter(|m| matches!(m, Message::Request(r) if r.method == CodeLensRefresh::METHOD))
.count();
assert_eq!(refreshes, 1, "the counts on screen were invalidated once");
}
#[test]
fn a_rapid_add_remove_add_of_the_same_folder_costs_three_rescans_and_ends_up_added() {
// Three separate notifications, each of which genuinely moves the
// root set (unlike the no-op shapes above), must cost three separate
// rescans — `change_roots` has no batching across notifications, only
// within one — and the state after must be consistent with the net
// effect: two adds and one remove is "present".
// QA (2026-08-27): "own shapes" case from the review checklist.
let root = Tree::new("rapidflaproot");
root.package("rtl/a.sv", "a");
let flapping = Tree::new("rapidflapfolder");
flapping.package("rtl/b.sv", "b");
let mut session = Session::wide(vec![root.path.clone()], false);
let before = session.server.generation;
folders_changed(&mut session, &[&flapping.path], &[]);
assert_eq!(indexed(&session, "b"), 1, "added");
folders_changed(&mut session, &[], &[&flapping.path]);
assert_eq!(indexed(&session, "b"), 0, "removed");
folders_changed(&mut session, &[&flapping.path], &[]);
assert_eq!(indexed(&session, "b"), 1, "added again");
assert_eq!(session.server.generation, before + 3, "one rescan per notification, three total");
assert_eq!(indexed(&session, "a"), 1, "the folder that never moved is untouched throughout");
}
#[test]
fn a_folder_event_that_moves_nothing_costs_nothing() {
// Total and no-op-safe: every shape a client can send that leaves the
// 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::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();
folders_changed(&mut session, &[], &[]);
folders_changed(&mut session, &[&tree.path], &[]);
folders_changed(&mut session, &[], &[&tree.path.join("never-added")]);
folders_changed(&mut session, &[&tree.path], &[&tree.path]);
// Params that do not parse at all, and a folder that is not a path.
session.notify(DidChangeWorkspaceFolders::METHOD, serde_json::json!({ "nonsense": 1 }));
session.notify(
DidChangeWorkspaceFolders::METHOD,
serde_json::json!({ "event": {
"added": [{ "uri": "untitled:Untitled-1", "name": "scratch" }], "removed": [],
} }),
);
assert!(session.progress().is_empty(), "no rescan for any of them");
assert_eq!(session.publishes(), 0, "and nothing was republished");
assert_eq!(session.server.generation, before, "and no generation moved");
assert_eq!(indexed(&session, "a"), 1, "the root itself survived every one");
}
#[test]
fn a_folder_change_re_registers_the_watchers_only_when_the_watched_path_moves() {
// The source glob is workspace-wide — the client matches it against
// whatever folders it holds, so a folder change needs no new
// registration for it. The *filelist* watcher is an absolute path
// anchored at the first root, so a folder change can move it without
// anyone touching the setting.
let first = Tree::new("folderwatch");
first.package("rtl/a.sv", "a");
first.write("files.f", "rtl/a.sv\n");
let second = Tree::new("folderwatchsecond");
second.package("rtl/b.sv", "b");
second.write("files.f", "rtl/b.sv\n");
let mut session = Session::new(vec![first.path.clone()], true);
let _ = session.drain();
// No filelist setting: nothing about the registration depends on the
// roots, so adding a folder re-registers nothing.
folders_changed(&mut session, &[&second.path], &[]);
assert!(session.requests().is_empty(), "the source glob is workspace-wide");
// With a *relative* filelist the watched path is `<first root>/files.f`...
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
let _ = session.drain();
// ...so dropping that root moves it to the second folder's copy.
folders_changed(&mut session, &[], &[&first.path]);
let requests = session.requests();
assert_eq!(requests.len(), 2, "{requests:#?}");
assert_eq!(requests[0].0, UnregisterCapability::METHOD);
assert_eq!(requests[1].0, RegisterCapability::METHOD);
assert_eq!(
requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"],
second.path.join("files.f").to_str().expect("utf-8").to_string(),
"{requests:#?}"
);
}