Owner-requested round. WorkspaceIndex::update_file/remove_file replace one file's contribution without reading or parsing anything else; Server::reindex_one takes the fast path for a didSave of one held file or a one-file watcher event (33 ms vs 1.5 s on the corpus, 45x), with everything else — settings, scope, filelist, multi-file events — keeping the full rebuild, pinned by a trigger-table test. FileIds stay sorted positions by deliberate deviation: renumbering through the one merge both finish and update_file end in makes build(W) byte-identical to build(W minus F).update_file(F) — fingerprint equality, attacked by QA across long interleaved sequences, disambiguation flips, define shadowing and the ghost hunt (the affected-keys union reads old and new records both). The per-file FileFacts the index retains are the documented memory cost (~1.4 MB on the corpus). The two oldest filed Handshakes land: instantiation and inheritance edge tables, built by the byte-for-byte moved census walks, turn codeLens counts (92 ms to 0.26 ms), incomingCalls and typeHierarchy subtypes into lookups — census policies pinned unchanged at both the consumers and now the source. Counts are as of the index, not of unsaved keystrokes: the freshness delta is documented and pinned from both sides. Saves no longer raise a progress bar; generation and lens refresh still ride. Round 18's three inherited scope obligations are pinned permanent. 36 tests added (dev 27 + QA 9). Left open, filed: wholesale republish, Candidates re-derivation cost, incremental removal vs include re-resolution. docs/features/incremental-index/README.md Co-Authored-By: Claude Fable 5 <[email protected]>
296 lines
12 KiB
Rust
296 lines
12 KiB
Rust
//! `workspace/didChangeWatchedFiles`: the index's answer to changes lucisv never
|
|
//! saw an editor make.
|
|
//!
|
|
//! Until this, the index was rebuilt on save and (with no workspace root) on
|
|
//! open — so a `git pull`, a branch checkout, a generated file, or an edit to
|
|
//! the `.f` filelist itself stayed invisible until the user happened to save
|
|
//! something. The client already watches the disk for its own reasons; this
|
|
//! module asks it to say what it sees. See
|
|
//! `docs/features/file-watching/README.md`.
|
|
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use lsp_types::notification::{DidChangeWatchedFiles, Notification as _};
|
|
use lsp_types::{
|
|
DidChangeWatchedFilesRegistrationOptions, FileEvent, FileSystemWatcher, GlobPattern,
|
|
InitializeParams, Registration, Unregistration,
|
|
};
|
|
|
|
use lucisv_core::walk::EXTENSIONS;
|
|
|
|
use crate::uri::uri_to_path;
|
|
|
|
/// Every source file the workspace walk would take, in one glob.
|
|
///
|
|
/// Deliberately the same four extensions as `lucisv_core::walk::EXTENSIONS` and
|
|
/// nothing else: a watcher wide enough to cover a build directory or a
|
|
/// `target/` tree would hand us thousands of events that cannot change the
|
|
/// index. `pinned_to_the_extensions_the_walk_takes` asserts the two agree.
|
|
pub const SOURCE_GLOB: &str = "**/*.{v,vh,sv,svh}";
|
|
|
|
/// Whether the client can be asked to watch files at all.
|
|
///
|
|
/// The protocol has no static form of this capability — a server that wants
|
|
/// file events must register for them, and a client that did not advertise
|
|
/// dynamic registration cannot be asked. Such a client simply keeps the
|
|
/// save-only staleness model it had before this feature.
|
|
pub fn dynamic_registration(params: &InitializeParams) -> bool {
|
|
params
|
|
.capabilities
|
|
.workspace
|
|
.as_ref()
|
|
.and_then(|workspace| workspace.did_change_watched_files.as_ref())
|
|
.and_then(|watched| watched.dynamic_registration)
|
|
.unwrap_or(false)
|
|
}
|
|
|
|
/// The registration to send as `client/registerCapability`: the source glob,
|
|
/// plus the configured filelist's own path when there is one.
|
|
///
|
|
/// `serial` numbers the registration so a later one can unregister it by name;
|
|
/// a re-registration is what a change of `lucisv.filelist` needs, because the
|
|
/// path being watched is part of the registration itself.
|
|
///
|
|
/// No `kind` is set on either watcher, which the protocol defines as
|
|
/// create|change|delete — all three matter here, since a file appearing and a
|
|
/// file vanishing move the index exactly as much as one being rewritten.
|
|
pub fn registration(serial: u32, filelist: Option<&Path>) -> Registration {
|
|
let options = DidChangeWatchedFilesRegistrationOptions { watchers: watchers(filelist) };
|
|
Registration {
|
|
id: registration_id(serial),
|
|
method: DidChangeWatchedFiles::METHOD.to_string(),
|
|
// Cannot fail for this shape (no non-string map keys, no floats), and
|
|
// a `None` here would register a watcher for nothing rather than
|
|
// corrupt anything — so there is nothing to report and nobody to
|
|
// report it to.
|
|
register_options: serde_json::to_value(options).ok(),
|
|
}
|
|
}
|
|
|
|
/// Undo a previous `registration`, by the id it carried.
|
|
pub fn unregistration(id: String) -> Unregistration {
|
|
Unregistration { id, method: DidChangeWatchedFiles::METHOD.to_string() }
|
|
}
|
|
|
|
/// The watchers a registration carries: sources always, the filelist when the
|
|
/// project has one.
|
|
///
|
|
/// The filelist is watched by its own absolute path rather than by a `*.f`
|
|
/// glob: a filelist can be called anything (`files.list`, `srcs.txt`), and a
|
|
/// glob wide enough for every name would also fire on every unrelated `.f` in
|
|
/// the tree. A path that is not valid UTF-8 cannot be written as a glob and is
|
|
/// simply not watched — the same restriction `uri.rs` already lives under.
|
|
fn watchers(filelist: Option<&Path>) -> Vec<FileSystemWatcher> {
|
|
let mut watchers = vec![watcher(SOURCE_GLOB.to_string())];
|
|
if let Some(pattern) = filelist.and_then(|path| path.to_str()) {
|
|
watchers.push(watcher(pattern.to_string()));
|
|
}
|
|
watchers
|
|
}
|
|
|
|
fn watcher(pattern: String) -> FileSystemWatcher {
|
|
FileSystemWatcher { glob_pattern: GlobPattern::String(pattern), kind: None }
|
|
}
|
|
|
|
fn registration_id(serial: u32) -> String {
|
|
format!("lucisv-watched-files-{serial}")
|
|
}
|
|
|
|
/// Whether a notification's events touch anything the index reads.
|
|
///
|
|
/// Asked **once per notification**, not once per file: a branch checkout
|
|
/// arrives as one notification carrying hundreds of events, and rebuilding per
|
|
/// event would re-scan the workspace hundreds of times for one answer.
|
|
///
|
|
/// The client's globs already filter, but a client is free to send more than
|
|
/// it was asked for (some watch a whole workspace and forward everything), and
|
|
/// a stray `.txt` must not cost a workspace re-scan.
|
|
pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool {
|
|
changes
|
|
.iter()
|
|
.filter_map(|change| uri_to_path(&change.uri))
|
|
.any(|path| watched(&path, filelist))
|
|
}
|
|
|
|
/// The one file an event named, when it named exactly one and that one is not
|
|
/// the filelist.
|
|
///
|
|
/// The gate on the incremental rescan path (`server.rs`'s `reindex_one`): a
|
|
/// checkout fills this list, and a list of one is the case a single file's
|
|
/// contribution can be replaced in place. The filelist is excluded because a
|
|
/// change to it moves the whole scope, which is a rebuild by definition. An
|
|
/// event naming the same path twice — a client is free to send `Changed` and
|
|
/// `Created` for one file — is still one file.
|
|
pub fn one_scope_file(changes: &[FileEvent], filelist: Option<&Path>) -> Option<PathBuf> {
|
|
let mut named: Vec<PathBuf> = changes
|
|
.iter()
|
|
.filter_map(|change| uri_to_path(&change.uri))
|
|
.filter(|path| watched(path, filelist))
|
|
.collect();
|
|
named.sort();
|
|
named.dedup();
|
|
match named.as_slice() {
|
|
[only] if Some(only.as_path()) != filelist => Some(only.clone()),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// Whether one path is something the index reads: a source file, or the
|
|
/// filelist that decides which source files there are.
|
|
///
|
|
/// Public since 2026-08-27 for `file_ops.rs`: `didRenameFiles`/`didDeleteFiles`
|
|
/// nudge the index for exactly the paths a watcher event would, and two copies
|
|
/// of that test would drift.
|
|
pub fn watched(path: &Path, filelist: Option<&Path>) -> bool {
|
|
if filelist == Some(path) {
|
|
return true;
|
|
}
|
|
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or_default();
|
|
EXTENSIONS.contains(&extension)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use lsp_types::{
|
|
ClientCapabilities, DidChangeWatchedFilesClientCapabilities, FileChangeType, Uri,
|
|
WorkspaceClientCapabilities,
|
|
};
|
|
use std::path::PathBuf;
|
|
use std::str::FromStr;
|
|
|
|
fn saying(dynamic_registration: Option<bool>) -> InitializeParams {
|
|
InitializeParams {
|
|
capabilities: ClientCapabilities {
|
|
workspace: Some(WorkspaceClientCapabilities {
|
|
did_change_watched_files: Some(DidChangeWatchedFilesClientCapabilities {
|
|
dynamic_registration,
|
|
relative_pattern_support: None,
|
|
}),
|
|
..Default::default()
|
|
}),
|
|
..Default::default()
|
|
},
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn only_a_client_that_says_so_is_asked_to_watch() {
|
|
assert!(!dynamic_registration(&InitializeParams::default()), "silence means no");
|
|
assert!(!dynamic_registration(&saying(None)), "an empty capability means no");
|
|
assert!(!dynamic_registration(&saying(Some(false))));
|
|
assert!(dynamic_registration(&saying(Some(true))));
|
|
}
|
|
|
|
#[test]
|
|
fn the_registration_is_the_shape_the_protocol_asks_for() {
|
|
// Pinned as JSON, because this is what goes on the wire and a client
|
|
// that cannot read it watches nothing at all — silently.
|
|
let value = serde_json::to_value(registration(0, None)).expect("json");
|
|
assert_eq!(
|
|
value,
|
|
serde_json::json!({
|
|
"id": "lucisv-watched-files-0",
|
|
"method": "workspace/didChangeWatchedFiles",
|
|
"registerOptions": { "watchers": [{ "globPattern": "**/*.{v,vh,sv,svh}" }] },
|
|
})
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_configured_filelist_is_watched_by_its_own_path() {
|
|
let value =
|
|
serde_json::to_value(registration(2, Some(Path::new("/p/files.f")))).expect("json");
|
|
assert_eq!(
|
|
value,
|
|
serde_json::json!({
|
|
"id": "lucisv-watched-files-2",
|
|
"method": "workspace/didChangeWatchedFiles",
|
|
"registerOptions": { "watchers": [
|
|
{ "globPattern": "**/*.{v,vh,sv,svh}" },
|
|
{ "globPattern": "/p/files.f" },
|
|
] },
|
|
})
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn no_filelist_means_no_second_watcher() {
|
|
assert_eq!(watchers(None).len(), 1, "sources only");
|
|
assert_eq!(watchers(Some(Path::new("/p/files.f"))).len(), 2, "and the filelist");
|
|
}
|
|
|
|
#[test]
|
|
fn an_unregistration_names_the_same_id_and_method() {
|
|
let registration = registration(7, None);
|
|
let undo = unregistration(registration.id.clone());
|
|
assert_eq!(undo.id, "lucisv-watched-files-7");
|
|
assert_eq!(undo.method, registration.method);
|
|
}
|
|
|
|
#[test]
|
|
fn the_glob_is_pinned_to_the_extensions_the_walk_takes() {
|
|
// A file the walk indexes but the glob does not name is a file whose
|
|
// external changes are invisible; the reverse is wasted rebuilds.
|
|
for extension in EXTENSIONS {
|
|
assert!(
|
|
SOURCE_GLOB.contains(&format!("{extension},"))
|
|
|| SOURCE_GLOB.contains(&format!("{extension}}}")),
|
|
"{extension} is not in {SOURCE_GLOB}"
|
|
);
|
|
}
|
|
assert_eq!(EXTENSIONS.len(), 4, "a fifth extension needs a wider glob");
|
|
}
|
|
|
|
fn event(path: &str) -> FileEvent {
|
|
FileEvent {
|
|
uri: Uri::from_str(&format!("file://{path}")).expect("uri"),
|
|
typ: FileChangeType::CHANGED,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_source_file_event_asks_for_a_rebuild() {
|
|
for name in ["/p/a.sv", "/p/a.v", "/p/a.svh", "/p/a.vh"] {
|
|
assert!(touches_scope(&[event(name)], None), "{name}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn an_unrelated_extension_does_not() {
|
|
// The stray-event case: a client that forwards more than it was asked
|
|
// for must not cost a workspace re-scan per keystroke in a README.
|
|
assert!(!touches_scope(&[event("/p/notes.txt")], None));
|
|
assert!(!touches_scope(&[event("/p/target/build.log")], None));
|
|
assert!(!touches_scope(&[event("/p/files.f")], None), "an unconfigured filelist");
|
|
assert!(!touches_scope(&[], None), "and an empty notification");
|
|
}
|
|
|
|
#[test]
|
|
fn the_configured_filelist_asks_for_a_rebuild() {
|
|
let filelist = PathBuf::from("/p/files.f");
|
|
assert!(touches_scope(&[event("/p/files.f")], Some(&filelist)));
|
|
assert!(!touches_scope(&[event("/p/other.f")], Some(&filelist)), "not another one");
|
|
}
|
|
|
|
#[test]
|
|
fn one_relevant_event_among_many_is_enough() {
|
|
// The `git checkout` shape: one notification, a long list, one answer.
|
|
let mut changes: Vec<FileEvent> =
|
|
(0..200).map(|i| event(&format!("/p/n{i}.txt"))).collect();
|
|
assert!(!touches_scope(&changes, None));
|
|
changes.push(event("/p/rtl/top.sv"));
|
|
assert!(touches_scope(&changes, None));
|
|
}
|
|
|
|
#[test]
|
|
fn a_non_file_uri_is_ignored_rather_than_guessed_at() {
|
|
let event = FileEvent {
|
|
uri: Uri::from_str("untitled:Untitled-1").expect("uri"),
|
|
typ: FileChangeType::CREATED,
|
|
};
|
|
assert!(!touches_scope(&[event], None));
|
|
}
|
|
}
|