From 45db6cd14f6e399d4256805a19bbd9b00a6358fc Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 26 Aug 2026 22:35:37 -0700 Subject: [PATCH] =?UTF-8?q?LSP=20=C2=A79c:=20workspace=20file=20operations?= =?UTF-8?q?=20=E2=80=94=20renames=20rewrite=20includes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit workspace/willRenameFiles rewrites every `include whose RESOLVED target is a renamed file — never a name match — sweeping sources() so unopened files count and open buffers contribute unsaved text. Rewrites preserve the include's form where the new location allows (bare stays bare in-dir; otherwise the shortest suffix that resolves under the rungs that form uses; ../ last; absolute stays absolute), a still-resolving include gets no edit, and an unrewritable one is left untouched with a warning rather than given an invented path. Directory renames ride the same prefix mapping for free, and the mirror case — the including file itself moving breaks its own-dir rung — ships with the same machinery. didRenameFiles/didDeleteFiles nudge the index through the watcher's own predicate. Three checks guard the write path: the edit range is the path token minus delimiters by construction; the rewritten line re-scans and re-lexes to exactly one include of the same form; and the rewritten path must resolve_as_if to exactly the new location against the post-rename filesystem — with every edit addressed to the PRE-rename uri, the spec detail a client silently drops edits over, pinned on the wire by QA. QA's corpus probe (a real ibex header, 87 real includers) caught the round's one real bug — unnormalized includer paths turning same-directory renames into false warnings — fixed with one normalize. Batch renames do not compound; recorded as a documented choice bounded by the safety net. 42 tests added (dev 33 + QA 9). verify.rs untouched. docs/features/file-operations/README.md Co-Authored-By: Claude Fable 5 --- TODO.md | 31 +- crates/lucisv_server/src/file_ops.rs | 1473 +++++++++++++++++++++++ crates/lucisv_server/src/includes.rs | 33 +- crates/lucisv_server/src/main.rs | 44 +- crates/lucisv_server/src/server.rs | 259 +++- crates/lucisv_server/src/watch.rs | 8 +- crates/lucisv_server/tests/e2e.rs | 156 +++ docs/features/file-operations/README.md | 540 +++++++++ docs/features/lucisv-server/README.md | 7 + 9 files changed, 2524 insertions(+), 27 deletions(-) create mode 100644 crates/lucisv_server/src/file_ops.rs create mode 100644 docs/features/file-operations/README.md diff --git a/TODO.md b/TODO.md index 756f21e..e45331c 100644 --- a/TODO.md +++ b/TODO.md @@ -892,10 +892,39 @@ and are not gaps. result by hand, and `vlog_parser` rejects `interface class`, so `implements` can never resolve and no item can carry `SymbolKind::Interface`. -- [ ] **File operations** — `workspace/willRenameFiles`: renaming a +- [x] **File operations** — `workspace/willRenameFiles`: renaming a `.sv/.svh` rewrites `` `include`` lines that reference it (the include graph exists); `didRename/didDelete` as cheaper index nudges than the watcher round-trip. + → delivered 2026-08-27 by `docs/features/file-operations/README.md`: + `workspace.fileOperations` + `crates/lucisv_server/src/file_ops.rs`. + An include is rewritten only when the graph says it **resolves** to + the renamed file — never on a filename match, so two `defs.svh` in + one workspace stay two files. The new spelling preserves the form + where the new location allows it (bare stays bare when a rung reaches + it, angled resolves through `+incdir+`s only, absolute stays + absolute), shortest resolving suffix first, with a `../`-relative + spelling as the last resort — which is also what answers a renamed + include *directory*, since lucisv does not edit filelists. An include + no spelling can reach is left exactly as written and named in a + `window/showMessage` warning ("log all, show the first", the + filelist rule): the server never invents a path that would not + resolve. **Folders are handled**, not declined — LSP sends only the + folder's URI and a folder is a path prefix, which is the same + operation a file rename already was. The rule shipped with a mirror + half the brief did not ask for: an include written *in* a file that + moves breaks the same way and is re-spelled too. Every edit covers + the path token alone (never the backtick, the delimiters or a + trailing comment) and is verified three ways before it is emitted — + re-scanned, re-lexed, and re-resolved against the filesystem the + rename will leave behind. `didRename`/`didDelete` reindex through + the same scope predicate the watcher uses, not deduplicated against + it (a double rebuild is a re-read, never a different answer). One + sweep is 54 ms over the 860-file corpus. `verify.rs` untouched. + `includes.rs` gained `resolve_as_if` (so there is still exactly one + copy of the EDA search order) and `normalize` became public; the + standing request to extract one `lucisv_core::path::normalize` for + the three private copies is still open. - [ ] **`workspace/didChangeWorkspaceFolders`** — roots are read once at initialize; adding/removing a folder mid-session is ignored. - [ ] **`workspace/configuration` (server-pull)** — we rely solely on diff --git a/crates/lucisv_server/src/file_ops.rs b/crates/lucisv_server/src/file_ops.rs new file mode 100644 index 0000000..96c70d2 --- /dev/null +++ b/crates/lucisv_server/src/file_ops.rs @@ -0,0 +1,1473 @@ +//! `workspace/willRenameFiles`, `workspace/didRenameFiles` and +//! `workspace/didDeleteFiles`. +//! +//! Renaming a header breaks every `` `include`` that reaches it. The include +//! graph already knows which those are — exactly, by resolution rather than by +//! filename — so this module answers the client's "I am about to rename these" +//! with the edits that keep them resolving, and the two notifications with the +//! index nudge a save would have given. See +//! `docs/features/file-operations/README.md`. +//! +//! Nothing here guesses. An include is rewritten only when the old spelling +//! resolved to the renamed file *and* the new spelling resolves to where it is +//! going, checked against the filesystem the rename will leave behind; an +//! include no legal spelling can reach is left alone and the user is told. + +// A `WorkspaceEdit`'s `changes` map is keyed by `lsp_types::Uri`, which carries +// a `Cell` for its own parse cache — interior mutability clippy cannot tell +// apart from a key that can change its hash. The cache is not part of `Hash` or +// `Eq`, and the map's shape is the protocol's, not ours (same note as +// `rename.rs`). +#![allow(clippy::mutable_key_type)] + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::str::FromStr; + +use lsp_types::{ + FileDelete, FileOperationFilter, FileOperationPattern, FileOperationPatternKind, + FileOperationRegistrationOptions, FileRename, TextEdit, Uri, WorkspaceEdit, + WorkspaceFileOperationsServerCapabilities, +}; +use vlog_parser::token::TokenKind; +use vlog_parser::{tokenize, LineIndex, TextRange}; + +use lucisv_core::walk::EXTENSIONS; + +use crate::convert::Positions; +use crate::includes::{normalize, scan, Include, IncludeGraph}; +use crate::state::Workspace; +use crate::uri::{path_to_uri, uri_to_path}; +use crate::watch::{watched, SOURCE_GLOB}; + +/// Every folder, for the one operation that has something to say about a +/// folder: moving a directory of headers moves every include that reached +/// into it. The glob is the pattern language's own "any path". +const ANY_FOLDER: &str = "**"; + +/// What the server tells the client it wants to hear about. +/// +/// `willRenameFiles` asks for source files *and* folders — a folder rename +/// carries only the folder's own URI, and the includes that reached into it +/// are exactly as broken as if each file had been named. The two notifications +/// ask for source files only: their whole job is a reindex, and a folder move +/// reaches the index through the file watcher's own events anyway. +/// +/// Not asked for, deliberately: `willCreateFiles`/`didCreateFiles` (a new file +/// has nothing pointing at it yet, and the watcher indexes it) and +/// `willDeleteFiles` (refusing or editing around a delete the user asked for +/// is not this server's business). +pub fn file_operations() -> WorkspaceFileOperationsServerCapabilities { + WorkspaceFileOperationsServerCapabilities { + will_rename: Some(FileOperationRegistrationOptions { + filters: vec![ + filter(SOURCE_GLOB, FileOperationPatternKind::File), + filter(ANY_FOLDER, FileOperationPatternKind::Folder), + ], + }), + did_rename: Some(sources_only()), + did_delete: Some(sources_only()), + ..Default::default() + } +} + +fn sources_only() -> FileOperationRegistrationOptions { + FileOperationRegistrationOptions { + filters: vec![filter(SOURCE_GLOB, FileOperationPatternKind::File)], + } +} + +/// One filter, scoped to `file:` — the only scheme with a path to resolve. +fn filter(glob: &str, matches: FileOperationPatternKind) -> FileOperationFilter { + FileOperationFilter { + scheme: Some("file".to_string()), + pattern: FileOperationPattern { + glob: glob.to_string(), + matches: Some(matches), + options: None, + }, + } +} + +/// The answer to one `workspace/willRenameFiles`: the edits to apply, and what +/// the user must be told was left alone. +#[derive(Default)] +pub struct Rewrite { + /// `None` when nothing needs rewriting — which the handler answers as the + /// protocol's `null`, not as an empty edit. + pub edit: Option, + /// One sentence per `` `include`` that pointed at a renamed file and that + /// no legal spelling can reach afterwards. Never silent: a stale include + /// the server noticed and said nothing about is the worst answer here. + pub warnings: Vec, +} + +/// Rewrite every `` `include`` in the workspace that resolves to a file the +/// client is about to rename. +/// +/// The sweep reads the in-scope files (`Workspace::sources`, so an unopened +/// file is read off disk and an open buffer contributes its unsaved text), and +/// asks the include graph — never the filename — which of them point at +/// something that moves. +pub fn will_rename(ws: &Workspace, files: &[FileRename]) -> Rewrite { + let moves = Moves::announced(files); + if moves.0.is_empty() { + return Rewrite::default(); + } + let graph = ws.includes(); + let mut changes: HashMap> = HashMap::new(); + let mut warnings = Vec::new(); + for (path, text) in ws.sources() { + // The overwhelming majority of files include nothing; one substring + // test each is what keeps this off the resolver for all of them. + if !text.contains("`include") { + continue; + } + // An include is resolved from where its file *will* be: a rename that + // moves the includer moves its own-directory rung with it. + let includer = moves.after(&path).unwrap_or_else(|| path.clone()); + let mut edits: Vec<(TextRange, String)> = Vec::new(); + for include in scan(&text) { + // Resolution against the filesystem as it stands — the rename has + // not happened yet, which is the whole point of `will`. + let Some(old) = graph.resolve(Some(&path), &include) else { continue }; + // Where that file will be. An include of an unmoved file written + // in an unmoved file cannot have broken, and is not looked at + // twice; an include written in a file that *moves* is, because its + // own-directory rung moves out from under it. + let moved = moves.after(&old); + if moved.is_none() && includer == path { + continue; + } + let target = moved.unwrap_or(old); + // Still resolving as written is the common case even when + // something moved: a header that keeps its name inside a + // `+incdir+`, or a rename that carries includer and included + // together. Nothing to write, and a no-op edit is noise in a diff. + if resolves_to(graph, &includer, &include, &target, &moves) { + continue; + } + match rewritten(graph, &includer, &text, &include, &target, &moves) { + Some(spelling) => edits.push((path_token(&include), spelling)), + None => warnings.push(unreachable_now(&path, &text, &include, &target)), + } + } + if edits.is_empty() { + continue; + } + let Some(uri) = path_to_uri(&path) else { + warnings.push(format!( + "{} holds `include`s of a renamed file but could not be addressed as a \ + document; they were left unchanged", + path.display() + )); + continue; + }; + let index = LineIndex::new(&text); + let positions = Positions::new(&text, &index); + let edits = edits + .into_iter() + .map(|(range, new_text)| TextEdit { range: positions.range(range), new_text }) + .collect(); + changes.insert(uri, edits); + } + let edit = (!changes.is_empty()).then(|| WorkspaceEdit::new(changes)); + Rewrite { edit, warnings } +} + +/// The path token alone: the bytes between the delimiters. +/// +/// This is the whole extent any edit this module produces may cover — never +/// the backtick, never the delimiters, never a trailing comment. A wrong +/// answer is then a wrong path inside a well-formed include line, and can +/// never be a moved byte anywhere else on it. +fn path_token(include: &Include) -> TextRange { + TextRange::new(include.path_span.start + 1, include.path_span.end - 1) +} + +/// The spelling to write into an include whose target moved to `target`, or +/// `None` when no spelling this workspace can resolve names it. +fn rewritten( + graph: &IncludeGraph, + includer: &Path, + text: &str, + include: &Include, + target: &Path, + moves: &Moves, +) -> Option { + candidate_spellings(graph, includer, include, target) + .into_iter() + .find(|spelling| survives(graph, includer, text, include, spelling, target, moves)) +} + +/// The three checks every emitted edit passes, run on the line the edit would +/// actually produce rather than on a sketch of it: +/// +/// 1. it still **scans** as one `` `include`` naming exactly the new spelling, +/// in the form it was written in (quoted stays quoted, angled stays angled); +/// 2. it still **lexes** as one directive — the whole line is one +/// `TokenKind::Directive` and nothing spilled out of it; +/// 3. it **resolves**, through the same search order every other consumer of +/// the graph uses, to exactly the file the rename is moving the old target +/// to — asked of the filesystem the rename will leave behind. +/// +/// Any of them failing means the candidate is dropped and the next one tried; +/// all of them failing for every candidate leaves the include untouched. +fn survives( + graph: &IncludeGraph, + includer: &Path, + text: &str, + include: &Include, + spelling: &str, + target: &Path, + moves: &Moves, +) -> bool { + let line = rewritten_line(text, include, spelling); + let found = scan(&line); + let [written] = found.as_slice() else { return false }; + if written.target != spelling || written.system != include.system { + return false; + } + if !one_include_directive(&line) { + return false; + } + resolves_to(graph, includer, written, target, moves) +} + +/// Whether `include`, written in a file that will live at `includer`, reaches +/// exactly `target` once every announced move has happened. +/// +/// The one resolution question this module asks, asked through the graph's own +/// search order — the same one `documentLink` and hover resolve with — of the +/// filesystem the rename will leave behind. +fn resolves_to( + graph: &IncludeGraph, + includer: &Path, + include: &Include, + target: &Path, + moves: &Moves, +) -> bool { + graph.resolve_as_if(Some(includer), include, &|path| moves.is_file(path)).as_deref() + == Some(target) +} + +/// The include's own line, with the path token replaced and every other byte +/// of the line kept. +fn rewritten_line(text: &str, include: &Include, spelling: &str) -> String { + let (start, end) = (include.span.start as usize, include.span.end as usize); + let from = text[..start].rfind('\n').map_or(0, |newline| newline + 1); + let to = text[end..].find('\n').map_or(text.len(), |newline| end + newline); + let line = &text[from..to]; + let path = path_token(include); + let (open, close) = (path.start as usize - from, path.end as usize - from); + format!("{}{spelling}{}", &line[..open], &line[close..]) +} + +/// Whether the whole line lexes as one `` `include`` directive. +/// +/// The scanner is a line scan and the lexer is the real thing; a rewritten +/// line has to satisfy both, so that no spelling can turn an include into +/// something the rest of the toolchain reads differently. +fn one_include_directive(line: &str) -> bool { + let Ok(tokens) = tokenize(line) else { return false }; + let mut real = tokens.iter().filter(|token| token.kind != TokenKind::Eof); + let Some(first) = real.next() else { return false }; + real.next().is_none() + && first.kind == TokenKind::Directive + && first.text.trim_start().starts_with("`include") +} + +/// Every spelling that could name `target` from `includer`, most preferred +/// first. Nothing here is trusted — each one is verified before it is used. +fn candidate_spellings( + graph: &IncludeGraph, + includer: &Path, + include: &Include, + target: &Path, +) -> Vec { + // An absolute include stays absolute: no search path was involved in it, + // so none is involved in its replacement either. + if Path::new(&include.target).is_absolute() { + return spelling_of(target).into_iter().collect(); + } + // `target` reaches here already folded (`graph.resolve`/`Moves::after` both + // normalize their answers), but `includer` is a raw workspace path — a + // root the client handed the server unnormalized carries that all the way + // down through `Workspace::sources()`. `target.strip_prefix` and + // `relative_spelling` are pure path-component algebra, run before either + // side ever touches the filesystem, so a `..` left in one operand and + // folded away in the other makes every rung fail to match even when both + // names the same directory — silently turning a same-directory rename + // into a false "no include path reaches it" warning instead of the + // one-word edit it should be. QA finding, file-operations, 2026-08-27, + // caught by the corpus probe: `resolve`/`resolve_as_if`'s own filesystem + // checks already tolerate this (`Path::is_file` and `Moves::is_file` both + // fold `..` themselves before deciding), which is why only this pure-path + // step needed the fix. + let includer = normalize(includer); + let own = match include.system { + // The angled form skips the own-directory rung, here as everywhere. + true => None, + false => includer.parent(), + }; + let mut spellings: Vec = own + .into_iter() + .chain(graph.incdirs().iter().map(PathBuf::as_path)) + .filter_map(|dir| target.strip_prefix(dir).ok()) + .filter_map(spelling_of) + .collect(); + // The shortest suffix first — `defs.svh` over `rtl/defs.svh` when both + // resolve. A stable sort, so the rung order breaks a tie: the including + // file's own directory before the first `+incdir+`, which is the order the + // resolver searches in anyway. + spellings.sort_by_key(|spelling| spelling.matches('/').count()); + // Last resort, and only for the form that has an own-directory rung: a + // path relative to the including file, `..` and all. It always resolves, + // but it is the ugliest spelling in the file, so nothing that goes through + // a `+incdir+` is passed over for it. + if let Some(dir) = own { + spellings.extend(relative_spelling(dir, target)); + } + spellings +} + +/// One path as an include writes it: forward slashes, whatever the platform's +/// separator is. A path that is not valid UTF-8 cannot be written into a +/// source file at all. +fn spelling_of(path: &Path) -> Option { + let spelling = path.to_str()?.replace('\\', "/"); + (!spelling.is_empty()).then_some(spelling) +} + +/// `target` written relative to `from_dir`, `..` for each directory left +/// behind. `None` when the two share no prefix at all — different drives, or +/// one of them relative — since no relative spelling exists then. +fn relative_spelling(from_dir: &Path, target: &Path) -> Option { + let from: Vec<_> = from_dir.components().collect(); + let to: Vec<_> = target.components().collect(); + let shared = from.iter().zip(&to).take_while(|(here, there)| here == there).count(); + if shared == 0 { + return None; + } + let mut parts: Vec<&str> = vec![".."; from.len() - shared]; + for component in &to[shared..] { + parts.push(component.as_os_str().to_str()?); + } + (!parts.is_empty()).then(|| parts.join("/")) +} + +/// What the user is told about an include the rename strands. +fn unreachable_now(path: &Path, text: &str, include: &Include, target: &Path) -> String { + let line = text[..include.span.start as usize].matches('\n').count() + 1; + let delimiters = match include.system { + true => ('<', '>'), + false => ('"', '"'), + }; + format!( + "{}:{line}: `include {}{}{} still names the old location — no include path reaches {}, \ + so it was left unchanged", + path.display(), + delimiters.0, + include.target, + delimiters.1, + target.display() + ) +} + +// ---------------------------------------------------------------------- +// the filesystem a rename leaves behind +// ---------------------------------------------------------------------- + +/// The renames the client announced, read as the filesystem they will produce: +/// everything under `old` will be under `new`. +/// +/// A file rename and a folder rename are the same operation here — a folder is +/// a prefix of the paths inside it, and LSP sends only the folder's own URI — +/// which is why folder renames cost this module no extra machinery. +struct Moves(Vec<(PathBuf, PathBuf)>); + +impl Moves { + /// The announced moves worth sweeping the workspace for: a source file, or + /// a directory (whose contents move with it). A rename of anything else, + /// and a rename that changes nothing, is dropped here — so a `.md` costs + /// one `is_dir` and answers `null`. + fn announced(files: &[FileRename]) -> Moves { + let mut moves = Vec::new(); + for file in files { + let (Some(old), Some(new)) = (path_of(&file.old_uri), path_of(&file.new_uri)) else { + continue; + }; + if old == new { + continue; + } + let extension = old.extension().and_then(|e| e.to_str()).unwrap_or_default(); + if EXTENSIONS.contains(&extension) || old.is_dir() { + moves.push((old, new)); + } + } + Moves(moves) + } + + /// Where `path` ends up, or `None` when nothing moves it. + fn after(&self, path: &Path) -> Option { + self.0.iter().find_map(|(old, new)| mapped(old, new, path)) + } + + /// Whether `path` will be a file once every announced move has happened. + /// + /// A path something moves *to* is answered by whether its source exists, + /// and that is asked first — so a swap (`a`→`b`, `b`→`a`) leaves both + /// files existing, which is exactly what it does on disk. + /// + /// The path is folded first: the resolver asks about `rtl/../inc/defs.svh` + /// as readily as about `inc/defs.svh`, and a prefix comparison against an + /// announced move only means anything on the folded form. `Path::is_file` + /// would have followed the `..` itself, which is exactly why the two must + /// not be allowed to disagree. + fn is_file(&self, path: &Path) -> bool { + let path = normalize(path); + if let Some(source) = self.0.iter().find_map(|(old, new)| mapped(new, old, &path)) { + return source.is_file(); + } + if self.after(&path).is_some() { + return false; + } + path.is_file() + } +} + +/// `path` with the prefix `from` replaced by `to`, or `None` when `from` is +/// not a prefix of it. +fn mapped(from: &Path, to: &Path, path: &Path) -> Option { + if path == from { + return Some(to.to_path_buf()); + } + let rest = path.strip_prefix(from).ok()?; + Some(to.join(rest)) +} + +// ---------------------------------------------------------------------- +// the two notifications +// ---------------------------------------------------------------------- + +/// The paths a `didRenameFiles` batch names — both ends of every rename, since +/// a file arriving moves the index exactly as much as one leaving. +pub fn renamed(files: &[FileRename]) -> Vec { + files + .iter() + .flat_map(|file| [path_of(&file.old_uri), path_of(&file.new_uri)]) + .flatten() + .collect() +} + +/// The paths a `didDeleteFiles` batch names. +pub fn deleted(files: &[FileDelete]) -> Vec { + files.iter().filter_map(|file| path_of(&file.uri)).collect() +} + +/// Whether a notification's paths touch anything the index reads. +/// +/// The same test a watched-file event gets, asked of the same predicate: a +/// client may well send both for one rename, and the two must agree about +/// whether it mattered. Reindexing twice is harmless — the rebuild is a pure +/// function of the tree — and costs one extra diagnostics generation. +pub fn touches_scope(paths: &[PathBuf], filelist: Option<&Path>) -> bool { + paths.iter().any(|path| watched(path, filelist)) +} + +/// The path a file-operation URI names. Unlike every other request, these +/// carry a `String` rather than a parsed `Uri`, so the parse happens here. +fn path_of(uri: &str) -> Option { + let path = uri_to_path(&Uri::from_str(uri).ok()?)?; + // Folded the way a resolved include is folded, so the two compare equal. + Some(normalize(&path)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + /// A scratch tree, removed on drop. + struct Tree { + path: PathBuf, + } + + impl Tree { + fn new(name: &str) -> Tree { + let path = std::env::temp_dir() + .join(format!("lucisv_server_file_ops_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).expect("parent"); + } + fs::write(&path, text).expect("write"); + path + } + + /// The workspace this tree's `files.f` governs, with nothing open. + fn workspace(&self) -> Workspace { + let mut ws = Workspace::default(); + if self.path.join("files.f").is_file() { + ws.set_client_settings(crate::settings::ClientSettings { + filelist: Some(self.path.join("files.f").display().to_string()), + ..Default::default() + }); + } + ws.open_roots(vec![self.path.clone()]); + ws + } + + fn rename(&self, from: &str, to: &str) -> FileRename { + FileRename { + old_uri: uri_of(&self.path.join(from)), + new_uri: uri_of(&self.path.join(to)), + } + } + } + + impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + fn uri_of(path: &Path) -> String { + path_to_uri(path).expect("uri").as_str().to_string() + } + + /// The one file the rewrite touches, as (uri, the new path spellings). + fn only_file(rewrite: &Rewrite) -> (String, Vec) { + let edit = rewrite.edit.as_ref().expect("an edit"); + let changes = edit.changes.as_ref().expect("changes"); + assert_eq!(changes.len(), 1, "expected one file, got {changes:#?}"); + let (uri, edits) = changes.iter().next().expect("one"); + (uri.as_str().to_string(), edits.iter().map(|e| e.new_text.clone()).collect()) + } + + /// Apply a rewrite to `text` the way a client would, so the test reads the + /// file the user would end up with. + fn applied(text: &str, rewrite: &Rewrite, uri: &str) -> String { + let edit = rewrite.edit.as_ref().expect("an edit"); + let changes = edit.changes.as_ref().expect("changes"); + let (_, edits) = changes + .iter() + .find(|(key, _)| key.as_str() == uri) + .unwrap_or_else(|| panic!("no edits for {uri} in {changes:#?}")); + let index = LineIndex::new(text); + let positions = Positions::new(text, &index); + // Back to front, so an earlier edit's offsets stay valid. + let mut ranges: Vec<(TextRange, String)> = edits + .iter() + .map(|edit| { + let start = positions.offset(edit.range.start); + let end = positions.offset(edit.range.end); + (TextRange::new(start, end), edit.new_text.clone()) + }) + .collect(); + ranges.sort_by_key(|(range, _)| std::cmp::Reverse(range.start)); + let mut out = text.to_string(); + for (range, new_text) in ranges { + out.replace_range(range.as_range(), &new_text); + } + out + } + + #[test] + fn a_same_directory_rename_keeps_the_bare_form() { + let tree = Tree::new("samedir"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); + + let text = fs::read_to_string(&top).expect("read"); + assert_eq!( + applied(&text, &rewrite, &uri_of(&top)), + "`include \"widths.svh\"\nmodule t;\nendmodule\n", + "the delimiters, the backtick and the rest of the file are untouched" + ); + } + + #[test] + fn a_cross_directory_rename_re_spells_through_an_incdir() { + let tree = Tree::new("crossdir"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "+incdir+inc\nrtl/top.sv\nrtl/defs.svh\n"); + fs::create_dir_all(tree.path.join("inc")).expect("mkdir"); + let ws = tree.workspace(); + + // Into a directory the filelist already names as an include path, with + // a new name: still the bare form, because the incdir rung reaches it + // — the shortest suffix that resolves, not the path from the includer. + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "inc/widths.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); + + // And the same move keeping the name needs no edit at all: the line + // already reads correctly once the incdir rung answers it. + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "inc/defs.svh")]); + assert!(rewrite.edit.is_none(), "{:?}", rewrite.edit); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + } + + #[test] + fn a_move_no_include_path_reaches_is_left_alone_and_reported() { + let tree = Tree::new("unreachable"); + tree.write("rtl/defs.svh", "`define W 8\n"); + tree.write("rtl/top.sv", "`include \n"); + // The angled form resolves against incdirs only, so `far/` — which is + // no include path — cannot be spelled from here at all. + tree.write("files.f", "+incdir+rtl\nrtl/top.sv\n"); + fs::create_dir_all(tree.path.join("far")).expect("mkdir"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "far/defs.svh")]); + assert!(rewrite.edit.is_none(), "no edit at all: {:?}", rewrite.edit); + assert_eq!(rewrite.warnings.len(), 1, "{:?}", rewrite.warnings); + let warning = &rewrite.warnings[0]; + assert!(warning.contains("top.sv:1"), "{warning}"); + assert!(warning.contains("`include "), "{warning}"); + assert!(warning.contains("left unchanged"), "{warning}"); + assert!(warning.contains("far/defs.svh"), "the new location is named: {warning}"); + } + + #[test] + fn every_include_of_one_renamed_file_is_rewritten_across_the_workspace() { + let tree = Tree::new("everywhere"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let a = tree.write("rtl/a.sv", "`include \"defs.svh\"\n`include \"defs.svh\"\n"); + let b = tree.write("rtl/b.sv", "module b;\nendmodule\n`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/a.sv\nrtl/b.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let changes = rewrite.edit.as_ref().expect("edit").changes.as_ref().expect("changes"); + assert_eq!(changes.len(), 2, "both files: {changes:#?}"); + let for_a = changes.iter().find(|(uri, _)| uri.as_str() == uri_of(&a)).expect("a.sv"); + assert_eq!(for_a.1.len(), 2, "both includes in the one file"); + + let text = fs::read_to_string(&b).expect("read"); + assert_eq!( + applied(&text, &rewrite, &uri_of(&b)), + "module b;\nendmodule\n`include \"widths.svh\"\n" + ); + } + + #[test] + fn an_include_of_a_different_file_with_the_same_name_is_untouched() { + // The whole reason this resolves rather than matching text: two + // `defs.svh` in one workspace, and only the one that is renamed moves. + let tree = Tree::new("samename"); + tree.write("a/defs.svh", "`define W 1\n"); + tree.write("b/defs.svh", "`define W 2\n"); + let top_a = tree.write("a/top.sv", "`include \"defs.svh\"\n"); + tree.write("b/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "a/top.sv\na/defs.svh\nb/top.sv\nb/defs.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("a/defs.svh", "a/widths.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let (uri, spellings) = only_file(&rewrite); + assert_eq!(uri, uri_of(&top_a), "only the file whose target moved"); + assert_eq!(spellings, vec!["widths.svh".to_string()]); + } + + #[test] + fn several_renames_in_one_request_answer_one_edit() { + let tree = Tree::new("batch"); + tree.write("rtl/defs.svh", "`define W 8\n"); + tree.write("rtl/ports.svh", "`define P 2\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n`include \"ports.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\nrtl/ports.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename( + &ws, + &[ + tree.rename("rtl/defs.svh", "rtl/widths.svh"), + tree.rename("rtl/ports.svh", "rtl/pins.svh"), + ], + ); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let text = fs::read_to_string(&top).expect("read"); + assert_eq!( + applied(&text, &rewrite, &uri_of(&top)), + "`include \"widths.svh\"\n`include \"pins.svh\"\n" + ); + } + + #[test] + fn a_batch_that_carries_includer_and_included_together_writes_nothing() { + // Both land in the same new directory, so the own-directory rung still + // answers `defs.svh` and the line is already right. + let tree = Tree::new("moveboth"); + tree.write("rtl/defs.svh", "`define W 8\n"); + tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + fs::create_dir_all(tree.path.join("src")).expect("mkdir"); + let ws = tree.workspace(); + + let rewrite = will_rename( + &ws, + &[tree.rename("rtl/top.sv", "src/top.sv"), tree.rename("rtl/defs.svh", "src/defs.svh")], + ); + assert!(rewrite.edit.is_none(), "{:?}", rewrite.edit); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + } + + #[test] + fn a_file_that_moves_away_from_its_own_headers_is_re_spelled_too() { + // The other half of the same rule: an include breaks when the file it + // is *written in* moves, because the own-directory rung moves with it. + // The answer is computed from where that file will be, and addressed + // to the URI it has now. + let tree = Tree::new("includermoves"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + fs::create_dir_all(tree.path.join("src")).expect("mkdir"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/top.sv", "src/top.sv")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let (uri, spellings) = only_file(&rewrite); + assert_eq!(uri, uri_of(&top), "addressed by the URI it has now"); + assert_eq!(spellings, vec!["../rtl/defs.svh".to_string()]); + } + + #[test] + fn every_source_extension_is_swept_and_nothing_else_is() { + let tree = Tree::new("extensions"); + tree.write("rtl/defs.vh", "`define W 8\n"); + let top = tree.write("rtl/top.v", "`include \"defs.vh\"\n"); + tree.write("notes.md", "not a source file\n"); + tree.write("files.f", "rtl/top.v\nrtl/defs.vh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.vh", "rtl/widths.vh")]); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.vh".to_string()])); + + // A file this server has no opinion about is answered with nothing — + // no edit, no warning, no sweep. + let rewrite = will_rename(&ws, &[tree.rename("notes.md", "NOTES.md")]); + assert!(rewrite.edit.is_none()); + assert!(rewrite.warnings.is_empty()); + } + + #[test] + fn a_directory_rename_moves_every_include_that_reached_into_it() { + // LSP names only the folder; the paths inside it move with it, which + // is the same prefix rewrite a file rename is. + let tree = Tree::new("directory"); + tree.write("inc/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"../inc/defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\ninc/defs.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("inc", "headers")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let text = fs::read_to_string(&top).expect("read"); + assert_eq!( + applied(&text, &rewrite, &uri_of(&top)), + "`include \"../headers/defs.svh\"\n", + "relative to the includer, which is the rung it resolved on before" + ); + } + + #[test] + fn a_renamed_include_directory_falls_back_to_a_relative_spelling() { + // Moving the directory a `+incdir+` names leaves the *filelist* stale, + // and this server does not edit filelists. What it can do is keep the + // source compiling: the own-directory rung is there in every tool, so + // the bare include becomes a relative one rather than staying broken. + // The `+incdir+` is then unused for this header — that is the user's + // to fix, and the file at least still resolves in the meantime. + let tree = Tree::new("incdirmoved"); + tree.write("inc/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "+incdir+inc\nrtl/top.sv\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("inc", "headers")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["../headers/defs.svh".to_string()])); + } + + #[test] + fn an_unopened_file_is_swept_too() { + // Includes live in files nobody has opened; the sweep reads them off + // disk through `sources()`, exactly as the index does. + let tree = Tree::new("unopened"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + assert!(ws.open_uris().is_empty(), "the premise: nothing open"); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); + } + + #[test] + fn an_unsaved_buffer_is_swept_from_its_own_text() { + let tree = Tree::new("buffer"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "module t;\nendmodule\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let mut ws = tree.workspace(); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), "`include \"defs.svh\"\nmodule t;\nendmodule\n".to_string()); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); + } + + #[test] + fn a_rename_that_moves_nothing_answers_nothing() { + let tree = Tree::new("noop"); + tree.write("rtl/defs.svh", "`define W 8\n"); + tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + // The same path twice is not a move. + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/defs.svh")]); + assert!(rewrite.edit.is_none()); + assert!(rewrite.warnings.is_empty()); + + // Nor is renaming a file nothing includes. + let rewrite = will_rename(&ws, &[tree.rename("rtl/top.sv", "rtl/toplevel.sv")]); + assert!(rewrite.edit.is_none(), "{:?}", rewrite.edit); + assert!(rewrite.warnings.is_empty()); + } + + #[test] + fn a_move_between_two_incdirs_that_keeps_the_spelling_produces_no_edit() { + // Both directories are include paths and the name does not change, so + // the include already reads correctly; an edit here would be noise in + // the user's diff. + let tree = Tree::new("noopmove"); + tree.write("a/defs.svh", "`define W 8\n"); + tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "+incdir+a\n+incdir+b\nrtl/top.sv\n"); + fs::create_dir_all(tree.path.join("b")).expect("mkdir"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("a/defs.svh", "b/defs.svh")]); + assert!(rewrite.edit.is_none(), "{:?}", rewrite.edit); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + } + + #[test] + fn the_edit_covers_the_path_token_and_not_one_byte_more() { + // Check (a), structurally: the range an edit carries is the bytes + // between the delimiters, so no answer this module can compute is able + // to disturb the backtick, the quotes, or a trailing comment. + let tree = Tree::new("token"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", " `include \"defs.svh\" // widths\nmodule t;\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + let text = fs::read_to_string(&top).expect("read"); + assert_eq!( + applied(&text, &rewrite, &uri_of(&top)), + " `include \"widths.svh\" // widths\nmodule t;\n", + "indent and trailing comment intact" + ); + let include = scan(&text).into_iter().next().expect("one"); + assert_eq!( + &text[path_token(&include).as_range()], + "defs.svh", + "no delimiters in the range" + ); + } + + #[test] + fn a_line_that_stops_being_one_include_is_never_written() { + // Check (c), attacked: a spelling carrying the closing delimiter would + // scan as a *different* include, and a spelling carrying a newline + // would leave a second line behind. Both are refused at the line the + // edit would produce, before anything is emitted. + let text = "`include \"defs.svh\"\n"; + let include = scan(text).into_iter().next().expect("one"); + assert_eq!(rewritten_line(text, &include, "widths.svh"), "`include \"widths.svh\""); + + let broken = rewritten_line(text, &include, "a\".svh"); + let found = scan(&broken); + assert_eq!(found.len(), 1, "{broken:?}"); + assert_ne!(found[0].target, "a\".svh", "the closing quote moved: {broken:?}"); + + let split = rewritten_line(text, &include, "a\nb.svh"); + assert!(!one_include_directive(&split), "two lines is not one directive: {split:?}"); + } + + #[test] + fn a_real_include_line_lexes_as_exactly_one_directive() { + assert!(one_include_directive("`include \"defs.svh\"")); + assert!(one_include_directive(" `include // a comment")); + assert!(one_include_directive("`include\"defs.svh\""), "no space, as the lexer allows"); + assert!(!one_include_directive("`define W 8"), "another directive entirely"); + assert!(!one_include_directive("wire a; `include \"defs.svh\""), "not alone on its line"); + } + + #[test] + fn a_spelling_that_would_resolve_somewhere_else_is_not_written() { + // Check (b), attacked: `defs.svh` is the shortest suffix of the new + // location, but a file of that name already sits beside the includer + // and wins the search — so that candidate resolves to the *wrong* + // file and is refused. The longer, correct spelling is written. + let tree = Tree::new("shadow"); + tree.write("rtl/defs.svh", "`define W 1\n"); + tree.write("inc/old.svh", "`define W 2\n"); + let top = tree.write("rtl/top.sv", "`include \"../inc/old.svh\"\n"); + tree.write("files.f", "+incdir+inc\nrtl/top.sv\nrtl/defs.svh\ninc/old.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("inc/old.svh", "inc/defs.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let text = fs::read_to_string(&top).expect("read"); + let applied = applied(&text, &rewrite, &uri_of(&top)); + assert_eq!( + applied, "`include \"../inc/defs.svh\"\n", + "the bare `defs.svh` would have resolved to rtl/defs.svh instead" + ); + } + + #[test] + fn the_capability_names_the_operations_this_server_answers() { + // Pinned as JSON: this is what goes on the wire, and a client sends + // these requests only where the filters say so. + let value = serde_json::to_value(file_operations()).expect("json"); + assert_eq!( + value, + serde_json::json!({ + "willRename": { "filters": [ + { "scheme": "file", "pattern": { "glob": "**/*.{v,vh,sv,svh}", "matches": "file" } }, + { "scheme": "file", "pattern": { "glob": "**", "matches": "folder" } }, + ] }, + "didRename": { "filters": [ + { "scheme": "file", "pattern": { "glob": "**/*.{v,vh,sv,svh}", "matches": "file" } }, + ] }, + "didDelete": { "filters": [ + { "scheme": "file", "pattern": { "glob": "**/*.{v,vh,sv,svh}", "matches": "file" } }, + ] }, + }), + "{value:#?}" + ); + } + + #[test] + fn a_notification_is_filtered_the_way_a_watched_file_event_is() { + let filelist = PathBuf::from("/p/files.f"); + let rename = |old: &str, new: &str| FileRename { + old_uri: uri_of(Path::new(old)), + new_uri: uri_of(Path::new(new)), + }; + let paths = renamed(&[rename("/p/a.sv", "/p/b.sv")]); + assert_eq!(paths.len(), 2, "both ends: {paths:?}"); + assert!(touches_scope(&paths, None)); + + assert!(!touches_scope(&renamed(&[rename("/p/a.md", "/p/b.md")]), None)); + // A file *becoming* a source file counts, exactly as a watcher's + // create event would. + assert!(touches_scope(&renamed(&[rename("/p/a.md", "/p/b.sv")]), None)); + + let deleting = |path: &str| FileDelete { uri: uri_of(Path::new(path)) }; + assert!(touches_scope(&deleted(&[deleting("/p/a.sv")]), None)); + assert!(!touches_scope(&deleted(&[deleting("/p/notes.txt")]), None)); + assert!(touches_scope(&deleted(&[deleting("/p/files.f")]), Some(&filelist))); + assert!(!touches_scope(&deleted(&[deleting("/p/other.f")]), Some(&filelist))); + assert!(!touches_scope(&[], None), "and an empty notification"); + } + + #[test] + fn a_non_file_uri_is_dropped_rather_than_guessed_at() { + let rename = FileRename { + old_uri: "untitled:Untitled-1".to_string(), + new_uri: "untitled:Untitled-2".to_string(), + }; + assert!(renamed(std::slice::from_ref(&rename)).is_empty()); + assert!(Moves::announced(&[rename]).0.is_empty()); + } + + #[test] + fn the_filesystem_a_rename_leaves_behind_answers_both_ends() { + let tree = Tree::new("moves"); + let here = tree.write("a.sv", "module a;\nendmodule\n"); + let moves = Moves(vec![(here.clone(), tree.path.join("b.sv"))]); + assert!(!moves.is_file(&here), "gone from where it was"); + assert!(moves.is_file(&tree.path.join("b.sv")), "and present where it goes"); + assert!(!moves.is_file(&tree.path.join("c.sv")), "an unrelated path is still absent"); + + // A swap leaves both files existing, as it does on disk. + let other = tree.write("b.sv", "module b;\nendmodule\n"); + let moves = Moves(vec![(here.clone(), other.clone()), (other.clone(), here.clone())]); + assert!(moves.is_file(&here) && moves.is_file(&other), "both, after the swap"); + } + + #[test] + fn a_relative_spelling_climbs_out_and_back_down() { + assert_eq!( + relative_spelling(Path::new("/p/rtl"), Path::new("/p/inc/defs.svh")).as_deref(), + Some("../inc/defs.svh") + ); + assert_eq!( + relative_spelling(Path::new("/p/rtl"), Path::new("/p/rtl/defs.svh")).as_deref(), + Some("defs.svh"), + "no climb needed" + ); + assert_eq!( + relative_spelling(Path::new("/p/a/b"), Path::new("/q/defs.svh")).as_deref(), + Some("../../../q/defs.svh"), + "the root is shared, so a spelling exists" + ); + assert_eq!(relative_spelling(Path::new("p/rtl"), Path::new("/q/defs.svh")), None); + } + + /// Order-of-magnitude perf check, not run as part of the ordinary suite: + /// timing assertions in a shared runner are flaky by nature. Run with + /// `cargo test --release -p lucisv_server --bin lucisv-server file_ops::tests::perf + /// -- --ignored --nocapture`. + mod perf { + use super::*; + + #[test] + #[ignore] + fn one_rename_sweeps_the_whole_corpus_in_milliseconds() { + // What a `willRenameFiles` costs: `sources()` re-reads every + // in-scope file, then one substring test each and the resolver for + // the few that include anything. Once per user gesture, and the + // 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()]); + let files = ws.index().files().len(); + assert!(files > 500, "the corpus is checked in: got {files}"); + let rename = FileRename { + old_uri: uri_of(&root.join("nothing_includes_this.svh")), + new_uri: uri_of(&root.join("moved.svh")), + }; + let start = std::time::Instant::now(); + let rewrite = will_rename(&ws, &[rename]); + eprintln!( + "perf: willRenameFiles over {files} corpus files in {:?} ({} warnings)", + start.elapsed(), + rewrite.warnings.len() + ); + } + } + + /// QA (file-operations, 2026-08-27): the attack surfaces the lead + /// specifically asked to hit before this rewrites-your-files feature + /// ships. Every test here either confirms the dev's claim or records what + /// actually happens; findings are written up in + /// `docs/features/file-operations/README.md`'s QA log, not here. + mod qa_2026_08_27_attacks { + use super::*; + use std::fs; + + /// Attack #1 (shadowing): the including file's own directory beats every + /// `+incdir+`. Two `defs.svh`, one reached by an own-dir rung and one only + /// by an `+incdir+` rung — renaming the incdir one must never touch the + /// include that resolves to the own-dir one, and vice versa. This is a + /// stronger shape than the dev's own same-name test (which uses two + /// separate directories with no incdir in play at all): here one of the + /// two spellings would *also* resolve to the incdir file if resolution + /// ever fell back to name-matching instead of the real search order. + #[test] + fn a_shadow_between_an_own_dir_file_and_an_incdir_file_is_never_crossed() { + let tree = Tree::new("qa_shadow_incdir"); + tree.write("a/defs.svh", "`define W 1\n"); // own-dir winner for top_a + tree.write("inc/defs.svh", "`define W 2\n"); // incdir winner for top_b + let top_a = tree.write("a/top.sv", "`include \"defs.svh\"\n"); + let top_b = tree.write("b/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "+incdir+inc\na/top.sv\na/defs.svh\nb/top.sv\ninc/defs.svh\n"); + let ws = tree.workspace(); + + // Rename the incdir file: only top_b's include (which resolves to it) + // may be touched. + let rewrite = will_rename(&ws, &[tree.rename("inc/defs.svh", "inc/widths.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let changes = + rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); + assert_eq!(changes.len(), 1, "only top_b: {changes:#?}"); + assert!(changes.contains_key(&Uri::from_str(&uri_of(&top_b)).expect("uri"))); + assert!( + !changes.contains_key(&Uri::from_str(&uri_of(&top_a)).expect("uri")), + "top_a resolves to a/defs.svh, which did not move: {changes:#?}" + ); + + // Rename the own-dir file: only top_a's include may be touched. + let rewrite = will_rename(&ws, &[tree.rename("a/defs.svh", "a/widths.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let changes = + rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); + assert_eq!(changes.len(), 1, "only top_a: {changes:#?}"); + assert!(changes.contains_key(&Uri::from_str(&uri_of(&top_a)).expect("uri"))); + assert!( + !changes.contains_key(&Uri::from_str(&uri_of(&top_b)).expect("uri")), + "top_b resolves to inc/defs.svh, which did not move: {changes:#?}" + ); + } + + /// Attack #4 (directory renames by prefix): `Moves` maps by path + /// *component* prefix, not string prefix. `rtl_extra/x.svh` must not be + /// claimed by a `rtl` → `rtl2` directory rename just because the string + /// "rtl" is a textual prefix of "rtl_extra". + /// + /// Both headers are referenced from a *sibling* directory (not from + /// inside the directory that moves), so renaming `rtl` actually forces + /// an edit — unlike moving a whole directory of includer-and-included + /// together, which is a no-op (`a_batch_that_carries_includer_and_\ + /// included_together_writes_nothing`) and would not have exercised the + /// prefix logic at all. + #[test] + fn a_directory_rename_does_not_claim_a_sibling_with_a_shared_string_prefix() { + let tree = Tree::new("qa_prefix"); + tree.write("rtl/defs.svh", "`define W 8\n"); + tree.write("rtl_extra/defs.svh", "`define W 9\n"); + let top = tree.write("outside/top.sv", "`include \"../rtl/defs.svh\"\n"); + let extra_top = tree.write("outside2/top2.sv", "`include \"../rtl_extra/defs.svh\"\n"); + tree.write( + "files.f", + "outside/top.sv\nrtl/defs.svh\noutside2/top2.sv\nrtl_extra/defs.svh\n", + ); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl", "rtl2")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let changes = + rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); + assert_eq!(changes.len(), 1, "only outside/top.sv, never top2.sv: {changes:#?}"); + let edit = &changes[&Uri::from_str(&uri_of(&top)).expect("uri")]; + assert_eq!(edit[0].new_text, "../rtl2/defs.svh"); + assert!( + !changes.contains_key(&Uri::from_str(&uri_of(&extra_top)).expect("uri")), + "a string-prefix match would wrongly touch rtl_extra: {changes:#?}" + ); + + // And the `Moves` primitive itself, directly: this is what a naive + // string-prefix implementation would get wrong. + let moves = Moves(vec![(tree.path.join("rtl"), tree.path.join("rtl2"))]); + assert_eq!( + moves.after(&tree.path.join("rtl/defs.svh")), + Some(tree.path.join("rtl2/defs.svh")) + ); + assert_eq!(moves.after(&tree.path.join("rtl_extra/defs.svh")), None); + } + + /// Attack #4b: a directory rename and a rename of a file inside that same + /// directory, both named in one batch. LSP says a folder rename carries + /// only the folder's own URI ("not its children"), so a spec-compliant + /// client never actually sends this — but nothing stops a client from + /// doing it anyway, and `Moves::after` takes the *first* matching entry + /// (`find_map`), so the two rules do not compound: whichever rename is + /// listed first in `params.files` decides that path's destination, and + /// the other entry is silently shadowed for any path under the directory. + /// Recorded here as a characterization, not asserted as "correct" — see + /// the QA log for the recommendation. + #[test] + fn a_directory_rename_and_a_file_rename_inside_it_do_not_compound() { + let tree = Tree::new("qa_nested_batch"); + tree.write("rtl/defs.svh", "`define W 8\n"); + tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + // The directory rename is listed first: `top.sv`'s explicit rename + // entry is never consulted for its own path. + let dir_first = Moves::announced(&[ + tree.rename("rtl", "rtl2"), + tree.rename("rtl/top.sv", "rtl/toplevel.sv"), + ]); + assert_eq!( + dir_first.after(&tree.path.join("rtl/top.sv")), + Some(tree.path.join("rtl2/top.sv")), + "the directory rule wins when listed first, not `toplevel.sv`" + ); + + // Reversed order: the file's own entry wins, and the directory rule + // no longer has a say over that one path. + let file_first = Moves::announced(&[ + tree.rename("rtl/top.sv", "rtl/toplevel.sv"), + tree.rename("rtl", "rtl2"), + ]); + assert_eq!( + file_first.after(&tree.path.join("rtl/top.sv")), + Some(tree.path.join("rtl/toplevel.sv")), + "order-dependent: whichever entry comes first claims the path" + ); + + // Either way, whatever `will_rename` writes is still checked against + // whichever model `Moves` produced (survives's check (c)), so no + // wrong-target edit escapes — the model can be surprising, but the + // output is never corrupt. + let rewrite = will_rename( + &ws, + &[tree.rename("rtl", "rtl2"), tree.rename("rtl/top.sv", "rtl/toplevel.sv")], + ); + if let Some(edit) = &rewrite.edit { + for edits in edit.changes.as_ref().expect("changes").values() { + for e in edits { + assert!(!e.new_text.contains('"'), "never a corrupt spelling: {e:?}"); + } + } + } + } + + /// Attack #5 (batch semantics): file A includes file B, and both move to + /// directories at different depths in the same batch. The right spelling + /// only falls out if *both* moves are consulted for the same resolution — + /// modeling just one of the two gives a spelling that is textually + /// different from the right answer, which is what makes this a real test + /// rather than a coincidence (some shapes of this scenario answer the + /// same text whichever move is dropped; this one does not). + #[test] + fn a_batch_where_both_the_includer_and_the_included_move_needs_both_moves_modeled() { + let tree = Tree::new("qa_both_moves"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + fs::create_dir_all(tree.path.join("deep/nested")).expect("mkdir"); + fs::create_dir_all(tree.path.join("other")).expect("mkdir"); + let ws = tree.workspace(); + + let rewrite = will_rename( + &ws, + &[ + tree.rename("rtl/top.sv", "deep/nested/top.sv"), + tree.rename("rtl/defs.svh", "other/defs.svh"), + ], + ); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let changes = + rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); + let edits = &changes[&Uri::from_str(&uri_of(&top)).expect("uri")]; + assert_eq!( + edits[0].new_text, "../../other/defs.svh", + "wrong if only one of the two moves were modeled: dropping the \ + includer's own move gives \"../other/defs.svh\" (one `..` short), \ + dropping the included file's move gives \"../../rtl/defs.svh\" \ + (the old directory): {edits:#?}" + ); + } + + /// Attack #2b (check (b), adversarially): a rename to a filename that + /// itself contains the delimiter character. POSIX allows `"` in a + /// filename, so this is a real, if perverse, input — not something the + /// server can refuse at the door. If the only candidate spelling embeds a + /// literal `"`, writing it would prematurely close the string and change + /// what the rest of the line means; `survives`'s re-scan must catch this + /// and refuse it. Hard invariant #1 (never corrupt) is what is actually + /// at stake here, not just this feature's own warning volume. + #[test] + fn a_rename_target_whose_name_contains_the_quote_delimiter_is_refused_not_written() { + let tree = Tree::new("qa_quote_name"); + // No incdir, no other spelling available: this is the *only* shape a + // quoted include of this file can take, forcing the bad candidate to + // be the one and only one tried. + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + let weird = tree.rename("rtl/defs.svh", "rtl/de\"fs.svh"); + let rewrite = will_rename(&ws, &[weird]); + + // Never a written edit that could corrupt the line: either no edit at + // all, or (if the checks pass some other way) a spelling that still + // scans as one clean include. + if let Some(edit) = &rewrite.edit { + let changes = edit.changes.as_ref().expect("changes"); + if let Some(edits) = changes.get(&Uri::from_str(&uri_of(&top)).expect("uri")) { + for e in edits { + let line = format!("`include \"{}\"", e.new_text); + let found = scan(&line); + assert_eq!(found.len(), 1, "must still scan as one include: {line:?}"); + assert_eq!( + found[0].target, e.new_text, + "must not truncate at an embedded quote" + ); + } + } + } else { + // The expected outcome: no legal quoted spelling exists (the + // literal name cannot be written between quotes at all), so the + // include is left alone and the user is warned, never guessed at. + assert_eq!(rewrite.warnings.len(), 1, "{:?}", rewrite.warnings); + assert!(rewrite.warnings[0].contains("left unchanged"), "{}", rewrite.warnings[0]); + } + // Either way, the file on disk was never touched by this call — the + // module returns edits, it does not write files itself. + assert_eq!(fs::read_to_string(&top).expect("read"), "`include \"defs.svh\"\n"); + } + + /// Attack #2c: a rename target with a plain space and one with non-ASCII + /// text. Neither character is a delimiter or a newline, so both are legal + /// inside a quoted `` `include`` and the rewrite should succeed cleanly — + /// this is the "total, correct" half of the lead's question, as opposed + /// to the quote case above, which is "refused, with a warning." + #[test] + fn a_rename_to_a_name_with_a_space_or_non_ascii_text_is_written_correctly() { + let tree = Tree::new("qa_space_unicode"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/new defs.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let changes = + rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); + assert_eq!( + changes[&Uri::from_str(&uri_of(&top)).expect("uri")][0].new_text, + "new defs.svh" + ); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/défs.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let changes = + rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); + assert_eq!( + changes[&Uri::from_str(&uri_of(&top)).expect("uri")][0].new_text, + "défs.svh" + ); + } + + /// Attack #2a: tabs in the indentation and a trailing block comment, not + /// just the line comment the dev's own test uses. The edit's byte range + /// must still cover exactly the path token. + #[test] + fn the_edit_range_is_exact_with_tab_indentation_and_a_block_comment() { + let tree = Tree::new("qa_tabs"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let text = "\t\t`include \"defs.svh\" /* widths */\nmodule t;\n"; + let top = tree.write("rtl/top.sv", text); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + let changes = + rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); + let edit = &changes[&Uri::from_str(&uri_of(&top)).expect("uri")][0]; + // Decode the LSP range back to a byte offset the way a client would, + // and check it names exactly the eight bytes of `defs.svh`. + let index = LineIndex::new(text); + let positions = Positions::new(text, &index); + let start = positions.offset(edit.range.start); + let end = positions.offset(edit.range.end); + assert_eq!(&text[start as usize..end as usize], "defs.svh", "{edit:?}"); + assert_eq!(edit.new_text, "widths.svh"); + } + + /// Corpus-scale probe: a real header with real fan-out, swept twice for + /// determinism. `prim_assert.sv` is included (own-directory rung, no + /// filelist needed) by 87 sibling files under + /// `ibex/vendor/lowrisc_ip/ip/prim/rtl/` — a renamed-file candidate that + /// actually exercises the "everywhere" path at scale, not a corpus file + /// picked at random that happens to include nothing. + /// + /// Every produced edit is checked against the post-rename filesystem + /// this module itself would use to verify a write (`resolve_as_if` + /// through `Moves`), and no file outside the 87 known includers may be + /// touched. + #[test] + fn a_real_corpus_header_with_wide_fan_out_is_swept_correctly_and_deterministically() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + let target_dir = root.join("ibex/vendor/lowrisc_ip/ip/prim/rtl"); + let old = target_dir.join("prim_assert.sv"); + assert!(old.is_file(), "the corpus is checked in: {old:?}"); + let new = target_dir.join("prim_assert_renamed.sv"); + + let mut ws = Workspace::default(); + ws.open_roots(vec![root.clone()]); + let rename = FileRename { old_uri: uri_of(&old), new_uri: uri_of(&new) }; + + let run = || { + let rewrite = will_rename(&ws, std::slice::from_ref(&rename)); + let changes = rewrite + .edit + .expect("87 known includers, so an edit is expected") + .changes + .expect("changes"); + (changes, rewrite.warnings) + }; + + let (first, warnings_first) = run(); + let (second, warnings_second) = run(); + assert_eq!( + first.len(), + second.len(), + "the same sweep run twice must touch the same number of files" + ); + assert_eq!(warnings_first.len(), warnings_second.len(), "and warn the same amount"); + + // Every touched file is genuinely an includer of the old target, + // and every edit's new spelling resolves to the new location once + // the rename this module models has happened — the same check + // `survives` runs before it will ever write a spelling, run again + // here from outside the module as an independent cross-check. + // + // Built through `Moves::announced`, not by hand: its entries are + // normalized (`path_of`), and comparing a normalized candidate + // against a hand-built, unnormalized `(old, new)` pair silently + // fails to match at all (`Path::strip_prefix`/`==` are + // component-wise, and a literal `..` is a different component + // from the directory it resolves to) — the same class of mismatch + // the fix above addresses, on the test's own side this time. + let moves = Moves::announced(std::slice::from_ref(&rename)); + let graph = ws.includes(); + let mut touched_dirs = std::collections::HashSet::new(); + for (uri, edits) in &first { + let path = uri_to_path(uri).expect("a file: URI"); + touched_dirs.insert(path.parent().map(Path::to_path_buf)); + let text = fs::read_to_string(&path).expect("read the real corpus file"); + for edit in edits { + assert_eq!(edit.new_text, "prim_assert_renamed.sv", "{edit:?}"); + // Not the include as it was written — that names the *old* + // spelling, which correctly no longer resolves once the + // rename has happened (that is exactly why an edit was + // needed). What must resolve is the *written* spelling, + // the same thing `survives` checks before this module + // ever emits it. + let original = scan(&text) + .into_iter() + .find(|inc| inc.target == "prim_assert.sv") + .expect("the include this edit was computed for"); + let written = Include { target: edit.new_text.clone(), ..original }; + let resolved = + graph.resolve_as_if(Some(&path), &written, &|p| moves.is_file(p)); + // `resolve_as_if` always folds `.`/`..` out of its answer + // (`normalize`), even when fed an unfolded `root` the way + // this test's own `CARGO_MANIFEST_DIR`-relative one is — + // so the expected side is folded here too. + assert_eq!(resolved, Some(normalize(&new)), "{path:?}: {edit:?}"); + } + } + // Every touched file really is one of the 87 known includers' + // directory — nothing outside it was swept in by this rename. + assert_eq!( + touched_dirs.len(), + 1, + "every includer of this own-dir-resolved header lives in one \ + directory; touching any other is a false positive: {touched_dirs:?}" + ); + assert_eq!(touched_dirs.into_iter().next().unwrap(), Some(target_dir)); + } + } +} diff --git a/crates/lucisv_server/src/includes.rs b/crates/lucisv_server/src/includes.rs index 642b389..4ca9bd2 100644 --- a/crates/lucisv_server/src/includes.rs +++ b/crates/lucisv_server/src/includes.rs @@ -134,6 +134,12 @@ impl IncludeGraph { graph } + /// The `+incdir+` directories an include is looked for in, in filelist + /// order — the search rungs past the including file's own directory. + pub fn incdirs(&self) -> &[PathBuf] { + &self.incdirs + } + /// The file an `` `include`` names, or `None` when nothing on disk /// answers to it. /// @@ -142,9 +148,26 @@ impl IncludeGraph { /// order. The `` form skips the own-directory rung, which is the C /// convention and the only difference the two spellings make here. pub fn resolve(&self, from: Option<&Path>, include: &Include) -> Option { + self.resolve_as_if(from, include, &|path| path.is_file()) + } + + /// [`IncludeGraph::resolve`], asked about a filesystem that has not + /// happened yet: `exists` decides which paths are files. + /// + /// The one search order, spent twice — `file_ops.rs` has to know where an + /// include *will* land once a rename the client has announced goes + /// through, and a second copy of the rung order there could disagree with + /// this one in exactly the corner cases nobody tests. See + /// `docs/features/file-operations/README.md`. + pub fn resolve_as_if( + &self, + from: Option<&Path>, + include: &Include, + exists: &dyn Fn(&Path) -> bool, + ) -> Option { let target = Path::new(&include.target); if target.is_absolute() { - return target.is_file().then(|| self.as_the_index_spells_it(normalize(target))); + return exists(target).then(|| self.as_the_index_spells_it(normalize(target))); } let own = match include.system { true => None, @@ -153,7 +176,7 @@ impl IncludeGraph { own.into_iter() .chain(self.incdirs.iter().map(PathBuf::as_path)) .map(|dir| dir.join(target)) - .find(|candidate| candidate.is_file()) + .find(|candidate| exists(candidate)) .map(|found| self.as_the_index_spells_it(normalize(&found))) } @@ -211,7 +234,11 @@ impl IncludeGraph { /// Fold `.`/`..` away so one file has one spelling, and so a resolved include /// compares equal to the same file's path in the index. Symlinks are /// deliberately not resolved, matching `lucisv_core`'s lexical rule. -fn normalize(path: &Path) -> PathBuf { +/// +/// Public since 2026-08-27 so `file_ops.rs` folds a renamed file's path the +/// same way a resolved include is folded — the two are compared, and a fourth +/// private copy of this loop is the one thing that guarantees they disagree. +pub fn normalize(path: &Path) -> PathBuf { let mut out = PathBuf::new(); for component in path.components() { match component { diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 5cea71a..71b163a 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -12,6 +12,7 @@ mod completion; mod convert; mod diagnostics; mod expand; +mod file_ops; mod folding; mod format; mod hierarchy; @@ -57,7 +58,7 @@ use lsp_types::{ SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability, - WorkDoneProgressOptions, + WorkDoneProgressOptions, WorkspaceServerCapabilities, }; use crate::server::{ClientAbilities, Server}; @@ -255,6 +256,20 @@ fn capabilities() -> ServerCapabilities { workspace_diagnostics: true, work_done_progress_options: WorkDoneProgressOptions::default(), })), + // File operations (3.16): renaming a header rewrites the + // `` `include``s that resolve to it, and a rename or a delete nudges + // the index without waiting for the watcher round-trip. Advertised + // unconditionally — unlike the watchers, nothing here is + // server-initiated, so a client that cannot send these requests simply + // never sends them and the capability costs it nothing. See + // `docs/features/file-operations/README.md`. + workspace: Some(WorkspaceServerCapabilities { + // Roots are still read once at `initialize`; adding a folder + // mid-session needs `didChangeWorkspaceFolders`, which is its own + // item in TODO.md §9c. + workspace_folders: None, + file_operations: Some(file_ops::file_operations()), + }), semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions( SemanticTokensOptions { work_done_progress_options: WorkDoneProgressOptions::default(), @@ -449,6 +464,33 @@ mod tests { assert!(caps.diagnostic_provider.is_some()); assert!(caps.code_lens_provider.is_some()); assert!(caps.document_on_type_formatting_provider.is_some()); + assert!(caps.workspace.is_some(), "the file operations live here"); + } + + #[test] + fn the_file_operations_reach_the_wire_under_workspace() { + // A client sends `willRenameFiles` only where the *server's* filters + // say so, and it looks for them at this exact key — a capability + // nested one level wrong is a capability that is never exercised. + let value = initialize_value().expect("the initialize result serializes"); + let operations = &value["capabilities"]["workspace"]["fileOperations"]; + assert_eq!( + operations["willRename"]["filters"][0]["pattern"]["glob"], + serde_json::json!(watch::SOURCE_GLOB), + "{value:#?}" + ); + assert_eq!( + operations["willRename"]["filters"][1]["pattern"]["matches"], + serde_json::json!("folder"), + "a folder rename moves every include that reached into it" + ); + assert_eq!(operations["didRename"]["filters"].as_array().map(Vec::len), Some(1)); + assert_eq!(operations["didDelete"]["filters"].as_array().map(Vec::len), Some(1)); + // The three this server does not answer are absent, not empty: a + // filter list a server cannot serve is a request it will be sent. + for absent in ["willCreate", "didCreate", "willDelete"] { + assert_eq!(operations[absent], serde_json::Value::Null, "{absent} is not answered"); + } } #[test] diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index a583662..bc623b7 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -15,8 +15,8 @@ use std::error::Error; use lsp_server::{Connection, ExtractError, Message, Notification, Request, RequestId, Response}; use lsp_types::notification::{ Cancel, DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles, - DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument, LogMessage, Notification as _, - Progress, PublishDiagnostics, ShowMessage, + DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument, DidRenameFiles, DidSaveTextDocument, + LogMessage, Notification as _, Progress, PublishDiagnostics, ShowMessage, }; use lsp_types::request::{ ApplyWorkspaceEdit, CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, @@ -28,25 +28,26 @@ use lsp_types::request::{ PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _, SelectionRangeRequest, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest, ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare, - TypeHierarchySubtypes, TypeHierarchySupertypes, UnregisterCapability, WillSaveWaitUntil, - WorkDoneProgressCreate, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, + TypeHierarchySubtypes, TypeHierarchySupertypes, UnregisterCapability, WillRenameFiles, + WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, }; use lsp_types::{ ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, CancelParams, CodeActionKind, - CodeActionParams, CodeLensParams, CompletionParams, DidChangeConfigurationParams, - DidChangeTextDocumentParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams, - DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentDiagnosticParams, - DocumentDiagnosticReport, DocumentDiagnosticReportResult, DocumentFormattingParams, - DocumentHighlightParams, DocumentLinkParams, DocumentOnTypeFormattingParams, - DocumentRangeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse, - ExecuteCommandParams, FoldingRangeParams, FullDocumentDiagnosticReport, GotoDefinitionParams, - GotoDefinitionResponse, HoverParams, InlayHintParams, InlineCompletionParams, - LinkedEditingRangeParams, Location, LogMessageParams, MessageType, NumberOrString, Position, - PreviousResultId, ProgressParams, ProgressParamsValue, ProgressToken, PublishDiagnosticsParams, - ReferenceParams, RegistrationParams, RelatedFullDocumentDiagnosticReport, - RelatedUnchangedDocumentDiagnosticReport, RenameParams, SelectionRangeParams, SemanticToken, - SemanticTokens, SemanticTokensDelta, SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, + CodeActionParams, CodeLensParams, CompletionParams, DeleteFilesParams, + DidChangeConfigurationParams, DidChangeTextDocumentParams, DidChangeWatchedFilesParams, + DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams, + DocumentDiagnosticParams, DocumentDiagnosticReport, DocumentDiagnosticReportResult, + DocumentFormattingParams, DocumentHighlightParams, DocumentLinkParams, + DocumentOnTypeFormattingParams, DocumentRangeFormattingParams, DocumentSymbolParams, + DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, FullDocumentDiagnosticReport, + GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams, + InlineCompletionParams, LinkedEditingRangeParams, Location, LogMessageParams, MessageType, + NumberOrString, Position, PreviousResultId, ProgressParams, ProgressParamsValue, ProgressToken, + PublishDiagnosticsParams, ReferenceParams, RegistrationParams, + RelatedFullDocumentDiagnosticReport, RelatedUnchangedDocumentDiagnosticReport, + RenameFilesParams, RenameParams, SelectionRangeParams, SemanticToken, SemanticTokens, + SemanticTokensDelta, SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, ShowDocumentParams, ShowMessageParams, SignatureHelpParams, TextDocumentPositionParams, TypeHierarchyPrepareParams, TypeHierarchySubtypesParams, @@ -62,9 +63,9 @@ use serde_json::Value; use crate::state::Workspace; use crate::{ - code_action, completion, diagnostics, folding, format, hierarchy, hover, includes, inlay, - inline, lens, linked, nav, on_type, pairs, ports, rename, selection, settings, signature, - symbols, sync, tokens, type_def, type_hierarchy, watch, + code_action, completion, diagnostics, file_ops, folding, format, hierarchy, hover, includes, + inlay, inline, lens, linked, nav, on_type, pairs, ports, rename, selection, settings, + signature, symbols, sync, tokens, type_def, type_hierarchy, watch, }; /// What the client said it can do, read once at `initialize` because that is @@ -610,6 +611,20 @@ impl Server { to_value(type_hierarchy::subtypes(&self.workspace, &p.item)) }) } + // The client is about to rename files and asks what that costs. + // Every `` `include`` that *resolves* to one of them is re-spelled + // so it still resolves afterwards; one that no include path can + // reach is left exactly as written and named in a warning, because + // inventing a path that resolves to nothing would be worse than + // the stale one. `null` when there is nothing to do. + WillRenameFiles::METHOD => decode(request).and_then(|p: RenameFilesParams| { + let rewrite = file_ops::will_rename(&self.workspace, &p.files); + self.report_scope(rewrite.warnings); + match rewrite.edit { + Some(edit) => to_value(edit), + None => Ok(Value::Null), + } + }), WorkspaceSymbolRequest::METHOD => { decode(request).and_then(|p: WorkspaceSymbolParams| { to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols( @@ -993,6 +1008,22 @@ impl Server { } } } + // The client moved or removed files itself. The same nudge a + // watched-file event gives, filtered by the same predicate, and + // deliberately not deduplicated against it: a client is free to + // send both, and a second rebuild is a pure re-read of the tree — + // it costs one scan and one diagnostics generation, never a + // different answer. + DidRenameFiles::METHOD => { + if let Ok(p) = extract::(notification) { + self.reindex_for(file_ops::renamed(&p.files)); + } + } + DidDeleteFiles::METHOD => { + if let Ok(p) = extract::(notification) { + self.reindex_for(file_ops::deleted(&p.files)); + } + } // The `lucisv.*` settings, pushed at startup and on every change. // Nothing here trusts the payload — `settings::from_payload` // drops whatever it cannot use. @@ -1107,9 +1138,19 @@ impl Server { id } + /// Rescan, but only when the paths a file-operation notification named are + /// paths the index reads. The same test a watched-file notification gets. + fn reindex_for(&mut self, paths: Vec) { + let filelist = self.workspace.filelist_path(); + if file_ops::touches_scope(&paths, filelist.as_deref()) { + self.reindex(); + } + } + /// Rescan the workspace and republish every open buffer against the new /// index. Every caller changed what the index should contain — a save, a - /// new `lucisv.exclude`/`lucisv.filelist`, or a watched file changing on disk. + /// new `lucisv.exclude`/`lucisv.filelist`, a watched file changing on disk, + /// or a file the client renamed or deleted. fn reindex(&mut self) { let bar = self.begin_indexing(); let warnings = self.workspace.rebuild_index(); @@ -1208,6 +1249,10 @@ impl Server { /// drifted from the tree can easily carry forty stale paths, and forty /// popups would be worse than the problem. Said once per rebuild, which is /// once per save — the same rhythm the `lucisv.toml` warning has. + /// + /// `workspace/willRenameFiles` reports through here too: an `` `include`` + /// a rename strands is the same kind of news, said at the same volume, and + /// a rename that strands forty of them must not open forty popups. fn report_scope(&self, warnings: Vec) { for warning in &warnings { self.notify( @@ -4374,4 +4419,176 @@ mod tests { // cancel did not intercept it. session.answer(server_id, Value::Null); } + + // ------------------------------------------------------------------ + // file operations (`docs/features/file-operations/README.md`) + // ------------------------------------------------------------------ + + /// One `workspace/willRenameFiles` for `from` → `to`, driven through the + /// real dispatch. + fn will_rename(session: &mut Session, from: &Path, to: &Path) -> Value { + session.result( + WillRenameFiles::METHOD, + serde_json::json!({ "files": [{ + "oldUri": path_to_uri(from).expect("uri"), + "newUri": path_to_uri(to).expect("uri"), + }] }), + ) + } + + #[test] + fn will_rename_answers_the_edit_that_keeps_an_include_resolving() { + 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 (from, to) = (tree.path.join("defs.svh"), tree.path.join("widths.svh")); + let answer = will_rename(&mut session, &from, &to); + let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri"); + let edits = &answer["changes"][uri.as_str()]; + assert_eq!(edits[0]["newText"], serde_json::json!("widths.svh"), "{answer:#?}"); + // The range is the path token: line 0, inside the quotes. + assert_eq!(edits[0]["range"]["start"], serde_json::json!({ "line": 0, "character": 10 })); + assert_eq!(edits[0]["range"]["end"], serde_json::json!({ "line": 0, "character": 18 })); + assert!(session.shown().is_empty(), "a rewrite everything could reach says nothing"); + } + + #[test] + fn will_rename_works_for_a_file_no_editor_ever_opened() { + // Includes live in unopened files; the sweep reads them off disk + // through the same `sources()` the index is built from. + 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); + assert!(session.server.workspace.open_uris().is_empty(), "premise: nothing open"); + + let answer = + will_rename(&mut session, &tree.path.join("defs.svh"), &tree.path.join("widths.svh")); + let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri"); + assert_eq!( + answer["changes"][uri.as_str()][0]["newText"], + serde_json::json!("widths.svh"), + "{answer:#?}" + ); + } + + #[test] + fn will_rename_answers_null_when_there_is_nothing_to_rewrite() { + let tree = Tree::new("willrenamenull"); + tree.package("rtl/a.sv", "a"); + tree.write("notes.md", "prose\n"); + let mut session = Session::new(vec![tree.path.clone()], false); + + // A source file nothing includes. + let answer = + will_rename(&mut session, &tree.path.join("rtl/a.sv"), &tree.path.join("rtl/b.sv")); + assert_eq!(answer, Value::Null, "{answer:#?}"); + // And a file this server has no opinion about at all. + let answer = + will_rename(&mut session, &tree.path.join("notes.md"), &tree.path.join("NOTES.md")); + assert_eq!(answer, Value::Null, "{answer:#?}"); + assert!(session.shown().is_empty()); + } + + #[test] + fn an_include_a_rename_strands_is_shown_once_and_logged() { + // The same "first shown, all logged" rule the scope warnings follow — + // a rename that strands forty includes must not open forty popups. + let tree = Tree::new("willrenamewarn"); + std::fs::create_dir_all(tree.path.join("inc")).expect("mkdir"); + tree.write("inc/defs.svh", "`define W 8\n"); + tree.write("a.sv", "`include \n"); + tree.write("b.sv", "`include \n"); + tree.write("files.f", "+incdir+inc\na.sv\nb.sv\n"); + tree.write("lucisv.toml", "filelist = \"files.f\"\n"); + let mut session = Session::new(vec![tree.path.clone()], false); + let _ = session.drain(); + + // The angled form resolves against incdirs only, so a move out of the + // one include path cannot be spelled from either file. + let answer = + will_rename(&mut session, &tree.path.join("inc/defs.svh"), &tree.path.join("far.svh")); + assert_eq!(answer, Value::Null, "nothing invented: {answer:#?}"); + let shown = session.drain(); + let popups: Vec<&Message> = shown + .iter() + .filter(|m| matches!(m, Message::Notification(n) if n.method == ShowMessage::METHOD)) + .collect(); + let logs: Vec<&Message> = shown + .iter() + .filter(|m| matches!(m, Message::Notification(n) if n.method == LogMessage::METHOD)) + .collect(); + assert_eq!(popups.len(), 1, "one popup for two stranded includes: {popups:#?}"); + assert_eq!(logs.len(), 2, "both are logged: {logs:#?}"); + } + + /// One `workspace/didRenameFiles` for `from` → `to`. + fn did_rename(session: &mut Session, from: &Path, to: &Path) { + session.notify( + DidRenameFiles::METHOD, + serde_json::json!({ "files": [{ + "oldUri": path_to_uri(from).expect("uri"), + "newUri": path_to_uri(to).expect("uri"), + }] }), + ); + } + + #[test] + 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); + 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"); + did_rename(&mut session, &tree.path.join("rtl/a.sv"), &tree.path.join("rtl/b.sv")); + assert_eq!(indexed(&session, "a"), 1, "still one package, found at its new path"); + + // And the same nudge from the watcher for the same move changes + // nothing: the rebuild is a re-read of the tree, not an increment. + session.watched(&[tree.path.join("rtl/b.sv")]); + assert_eq!(indexed(&session, "a"), 1, "reindexing twice is harmless"); + } + + #[test] + fn a_delete_notification_rebuilds_the_index() { + 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); + assert_eq!(indexed(&session, "gone_pkg"), 1, "premise: indexed"); + + std::fs::remove_file(tree.path.join("rtl/gone.sv")).expect("remove"); + session.notify( + DidDeleteFiles::METHOD, + serde_json::json!({ "files": [ + { "uri": path_to_uri(&tree.path.join("rtl/gone.sv")).expect("uri") }, + ] }), + ); + assert_eq!(indexed(&session, "gone_pkg"), 0, "gone from the index too"); + assert_eq!(indexed(&session, "a"), 1, "and the rest survives"); + } + + #[test] + fn a_file_operation_notification_for_nothing_the_index_reads_costs_no_rebuild() { + let tree = Tree::new("didrenamestray"); + tree.package("rtl/open.sv", "open_pkg"); + let mut session = Session::new(vec![tree.path.clone()], false); + session.open( + &tree.path.join("rtl/open.sv"), + "package open_pkg;\n localparam K = 1;\nendpackage\n", + ); + assert_eq!(session.publishes(), 1, "premise: `didOpen` published once"); + + did_rename(&mut session, &tree.path.join("README.md"), &tree.path.join("READ.md")); + session.notify( + DidDeleteFiles::METHOD, + serde_json::json!({ "files": [ + { "uri": path_to_uri(&tree.path.join("notes.txt")).expect("uri") }, + ] }), + ); + assert_eq!(session.publishes(), 0, "neither is a path the index reads"); + } } diff --git a/crates/lucisv_server/src/watch.rs b/crates/lucisv_server/src/watch.rs index 141dc88..8c4f084 100644 --- a/crates/lucisv_server/src/watch.rs +++ b/crates/lucisv_server/src/watch.rs @@ -112,7 +112,13 @@ pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool { .any(|path| watched(&path, filelist)) } -fn watched(path: &Path, filelist: Option<&Path>) -> bool { +/// 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; } diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index bbf0615..1b139b2 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -3636,3 +3636,159 @@ fn the_class_hierarchy_round_trips_over_the_wire_in_both_directions() { let _ = std::fs::remove_dir_all(&dir); } + +/// One `TextEdit` applied the way a client applies it: by line and character. +/// The fixtures below are ASCII, so a UTF-16 character is a byte column. +fn apply_edits(text: &str, edits: &[serde_json::Value]) -> String { + let mut lines: Vec = text.split('\n').map(str::to_string).collect(); + for edit in edits { + let range = &edit["range"]; + let line = range["start"]["line"].as_u64().expect("line") as usize; + assert_eq!(range["end"]["line"], range["start"]["line"], "one line per edit: {edit:#?}"); + let (from, to) = ( + range["start"]["character"].as_u64().expect("start") as usize, + range["end"]["character"].as_u64().expect("end") as usize, + ); + let new_text = edit["newText"].as_str().expect("newText"); + lines[line].replace_range(from..to, new_text); + } + lines.join("\n") +} + +/// The file-operations round trip against the real binary: the server is asked +/// what a rename costs, the answer is applied and the rename performed exactly +/// as a client would, and a second session proves the include resolves again +/// at its new location — the whole point of the exercise. +#[test] +fn a_rename_round_trips_through_the_edit_and_leaves_the_include_resolving() { + let dir = temp_dir("willrename"); + std::fs::create_dir_all(dir.join("inc")).expect("inc"); + let defs = dir.join("inc/defs.svh"); + std::fs::write(&defs, "`define WIDTH 8\n").expect("write"); + let top = dir.join("top.sv"); + let source = "`include \"inc/defs.svh\"\nmodule top;\nendmodule\n"; + std::fs::write(&top, source).expect("write"); + + let root = format!("file://{}", dir.display()); + let top_uri = format!("file://{}", top.display()); + let old_uri = format!("file://{}", defs.display()); + let moved = dir.join("inc/widths.svh"); + let new_uri = format!("file://{}", moved.display()); + + // Session one: "I am about to rename inc/defs.svh to inc/widths.svh." + let messages = talk( + &[ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"workspace/willRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(), + ); + + // The capability is advertised where a client looks for it. + let initialized = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); + let operations = &initialized["result"]["capabilities"]["workspace"]["fileOperations"]; + assert!(operations["willRename"]["filters"].is_array(), "{initialized:#?}"); + + let answer = messages.iter().find(|m| m["id"] == 2).expect("willRename response"); + let edits = answer["result"]["changes"][&top_uri].as_array().expect("edits for top.sv"); + assert_eq!(edits.len(), 1, "{answer:#?}"); + + // The client's half: apply the edit, then do the rename. + let rewritten = apply_edits(source, edits); + assert_eq!(rewritten, "`include \"inc/widths.svh\"\nmodule top;\nendmodule\n"); + std::fs::write(&top, &rewritten).expect("write back"); + std::fs::rename(&defs, &moved).expect("rename"); + + // Session two: the include is a live link again, at the new path. + let messages = talk( + &[ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"workspace/didRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(&rewritten).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/documentLink","params":{{"textDocument":{{"uri":"{top_uri}"}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(), + ); + let links = messages.iter().find(|m| m["id"] == 2).expect("documentLink response")["result"] + .as_array() + .expect("a link list") + .clone(); + assert_eq!(links.len(), 1, "{links:#?}"); + assert_eq!(links[0]["target"], new_uri.as_str(), "the include resolves to the new file"); + + let _ = std::fs::remove_dir_all(&dir); +} + +/// The mirror case, at the wire: the file *being renamed* is also the one +/// whose own include needs rewriting (its own-directory rung moves with it). +/// Per LSP, `willRenameFiles` edits apply before the rename, so the +/// `WorkspaceEdit` must name the file's *old* URI — a `TextDocumentEdit` +/// naming the new URI would be silently dropped by a real client, since that +/// document does not exist yet at the time the edit is applied. This is the +/// highest-risk detail in the feature, so it is pinned at the JSON-RPC level, +/// not just through the handler. +#[test] +fn a_moving_includer_s_own_edit_is_addressed_to_its_old_uri_on_the_wire() { + let dir = temp_dir("willrenameself"); + std::fs::create_dir_all(dir.join("rtl")).expect("rtl"); + std::fs::create_dir_all(dir.join("src")).expect("src"); + std::fs::write(dir.join("rtl/defs.svh"), "`define WIDTH 8\n").expect("write"); + let old_top = dir.join("rtl/top.sv"); + std::fs::write(&old_top, "`include \"defs.svh\"\nmodule top;\nendmodule\n").expect("write"); + let new_top = dir.join("src/top.sv"); + + let root = format!("file://{}", dir.display()); + let old_uri = format!("file://{}", old_top.display()); + let new_uri = format!("file://{}", new_top.display()); + + let messages = talk( + &[ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"workspace/willRenameFiles","params":{{"files":[{{"oldUri":"{old_uri}","newUri":"{new_uri}"}}]}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(), + ); + + let answer = messages.iter().find(|m| m["id"] == 2).expect("willRename response"); + let changes = answer["result"]["changes"].as_object().expect("changes map"); + assert_eq!(changes.len(), 1, "{answer:#?}"); + assert!( + changes.contains_key(&old_uri), + "the edit must be addressed to the pre-rename URI: {answer:#?}" + ); + assert!( + !changes.contains_key(&new_uri), + "a client applies these edits before the rename — the new URI does not \ + exist yet and an edit there would be dropped: {answer:#?}" + ); + let edits = changes[&old_uri].as_array().expect("edits"); + assert_eq!(edits[0]["newText"], serde_json::json!("../rtl/defs.svh"), "{answer:#?}"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features/file-operations/README.md b/docs/features/file-operations/README.md new file mode 100644 index 0000000..3a6ecf6 --- /dev/null +++ b/docs/features/file-operations/README.md @@ -0,0 +1,540 @@ +# file-operations + +## Goal + +Renaming a header breaks every `` `include`` that reaches it, and until now +lucisv watched that happen and said nothing — the editor moved `defs.svh`, four +files went on naming a path that no longer exists, and the only sign was that +ctrl-click stopped working. LSP 3.16 has the hook: a client that is about to +rename files asks the server first (`workspace/willRenameFiles`) and applies +whatever `WorkspaceEdit` comes back as part of the same undo step. The include +graph already knows exactly which lines point at the moved file — by +*resolution*, not by filename — so this round spends it: an include whose +resolved target moves is re-spelled so it still resolves, an include no legal +spelling can reach is left exactly as written and named in a warning, and the +two after-the-fact notifications (`didRenameFiles`, `didDeleteFiles`) nudge the +index without waiting for a watcher round-trip. + +## Assumptions + +- **Renames in one batch do not compound.** `Moves` maps a path by the first + matching rename (`find_map`), so a directory rename and an explicit rename + of a file inside that directory, sent in one request, apply whichever rule + matches first rather than both in sequence (QA log, 2026-08-27). No client + observed sends that shape — a directory rename lists the directory alone — + and the safety net still refuses any edit whose rewritten include does not + resolve, so the failure mode is a skipped edit plus the warning, never a + wrong write. Recorded so a future round that wants compounding knows it is + changing a documented choice. + + +- **Resolution decides, never the filename.** An include is rewritten only + when `IncludeGraph::resolve` says it reaches the renamed file. Two + `defs.svh` in one workspace are two different files here, and only the one + that moves is touched — pinned by + `an_include_of_a_different_file_with_the_same_name_is_untouched`. +- **The rename has not happened yet.** `willRenameFiles` is asked *before* the + move, so the old target is resolved against the filesystem as it stands. The + *new* spelling is resolved against the filesystem the rename will leave + behind, which `Moves` models: everything under `old` will be under `new`, a + path something moves away from is gone, a path something moves to exists if + its source does (so an `a`→`b`, `b`→`a` swap leaves both files, as it does on + disk). No filesystem is touched to answer that — it is a prefix rewrite plus + one `is_file` on the source. +- **A file rename and a folder rename are one operation.** LSP sends only the + folder's own URI for a folder rename ("when a folder is renamed, only the + folder will be included, and not its children"), and a folder is a *prefix* + of the paths inside it — which is exactly what `Moves` already computes for a + file. Handling folders therefore cost this module no machinery at all, which + is why they are handled rather than declined: the cost is one filter in the + capability and one workspace sweep on a user gesture (54 ms over the 860-file + corpus, see Cost), and the case it covers — moving a directory of headers — + is the single most include-breaking thing a user can do. +- **The two notifications ask for files only.** `didRenameFiles`/ + `didDeleteFiles` do one thing, reindex, and a folder filter there would buy a + full rebuild for every unrelated folder rename in the tree while the file + watcher already reports the individual files a folder move touches. So the + folder filter is on `willRename` alone, where it earns its keep. +- **The form is preserved where the new location allows it.** The candidate + spellings are the suffixes of the new path under each search rung the *same* + form would use — the including file's own directory (skipped for the angled + form, as everywhere) and then each `+incdir+` — shortest suffix first, with + the rung order breaking a tie. An originally **absolute** include stays + absolute. So a same-directory rename keeps the bare filename, and a move into + an `+incdir+` keeps it bare too. +- **A relative spelling is the last resort, not the first.** When no rung's + suffix resolves, a quoted include falls back to a path relative to the + including file (`../headers/defs.svh`), which resolves on the own-directory + rung every tool has. It is the ugliest spelling in the file, so nothing that + goes through an `+incdir+` is passed over for it. This is what answers a + renamed *include directory*: the `+incdir+` in the filelist is then stale and + **lucisv does not edit filelists**, but the source keeps compiling, which is + the better half of a bad situation. +- **An include that still reads correctly is not edited.** Before anything is + computed, the include as written is re-resolved against the post-rename + filesystem; if it still reaches its file, there is no edit and no warning. A + header moving between two `+incdir+`s under the same name, and a rename that + carries includer and included together, are both no-ops — a no-op edit is + noise in the user's diff. +- **An include the rename strands is left alone *and* said out loud.** The + server will not invent a path that resolves to nothing (that would be a + guess, and a guess written into the user's file). It also will not stay + silent about a line it knows it just broke. So: no edit, and one + `window/showMessage` WARNING naming the file, the line and the include — + through `report_scope`, so forty stranded includes are one popup and forty + log lines. +- **Both ends of the edge are watched.** The brief's rule was "an include whose + resolved target is the renamed file"; the shipped rule adds the mirror case, + an include written *in* a file that moves, because that breaks for exactly + the same reason (the own-directory rung moves out from under it) and would + otherwise be a silent breakage the feature politely watched happen. +- **Edits are addressed to the file's current URI.** A file that is itself + being renamed *and* needs an include rewritten is edited at the URI it has + now, while its new content is computed from where it will be. That is what + VS Code and every other file-operation participant expect: the edit lands on + the document, and the rename carries it. +- **The scope ladder still decides what lucisv can see.** The sweep reads + `Workspace::sources()` — the in-scope files, with open buffers overriding + disk. An include in a file the filelist does not name is not rewritten, + exactly as it is not indexed, not linted and not searched. +- **The capability is static and ungated.** `ServerCapabilities` is built + before the client's own capabilities are read, and unlike the file watchers + nothing here is server-initiated: a client that cannot send these requests + simply never sends them. Gating would buy nothing and cost the + `capabilities()` function a parameter. + +## The safety net + +The `WorkspaceEdit` this feature produces **rewrites the user's source files**, +which nothing else in the server does unasked. It is fenced three ways, and +every candidate spelling passes all three or is discarded (`survives`): + +1. **The edit can only cover the path token.** Its range is + `path_span.start + 1 .. path_span.end - 1` — the bytes *between* the + delimiters. Structurally, no answer this module can compute is able to move + the backtick, the quotes, the indentation or a trailing comment; the worst + a bug can produce is a wrong path inside a well-formed include line. + (`the_edit_covers_the_path_token_and_not_one_byte_more`.) +2. **It still scans as the include it was.** The line the edit would produce is + built and re-scanned with `includes::scan`: exactly one include, target + equal to the spelling, same quoted/angled form. A spelling carrying the + closing delimiter or a newline dies here. +3. **It still lexes, and it still resolves.** The same line is run through + `vlog_parser::tokenize` and must be one `TokenKind::Directive` and nothing + else; and the *re-scanned* include — what the scanner will actually read + back, not what we meant to write — must resolve, through + `IncludeGraph::resolve_as_if`, to exactly the file the rename is moving the + old target to. A spelling that would resolve to a *different* file (a bare + name shadowed by a header beside the includer) is refused here, and the + longer correct spelling is written instead + (`a_spelling_that_would_resolve_somewhere_else_is_not_written`). + +`verify.rs` is untouched: no normalization was added or broadened, so hard +invariant #4 is not in play. The formatter is not involved in this path at all. + +## Handshakes + +### Consumed + +- `lucisv_server::includes` — the whole of the resolution story. Three changes, + all additive: + - **`IncludeGraph::resolve_as_if(from, include, exists)`** is new, and + `resolve` is now `resolve_as_if(.., &|p| p.is_file())`. There is still + exactly **one** copy of the EDA search order; this module needed to ask it + about a filesystem that has not happened yet, and a second copy here would + have disagreed with the first in the corner cases nobody tests. + - **`IncludeGraph::incdirs()`** — a read-only accessor, so a candidate + spelling can be a suffix under a real include path rather than a guess. + - **`includes::normalize` is now `pub`** (it was private). A renamed path and + a resolved include are compared, and they must be folded the same way; a + fourth private copy of that loop is the one thing that guarantees they + drift. This is the same `.`/`..` folding + `lucisv_core::filelist::Reader::normalize` and + `lucisv_core::config::Discovery::absolute` each have privately — the + include-nav README's standing request to extract one + `lucisv_core::path::normalize` and point all of them at it is **still + open**, and this round deliberately did not widen its scope to do it. +- `lucisv_server::watch::watched` is now `pub` (it was private). The + notifications filter their paths with exactly the predicate a + `didChangeWatchedFiles` event is filtered with — two copies of "is this a + path the index reads" would drift, and the two paths must agree because a + client may well send both for one rename. +- `lucisv_server::watch::SOURCE_GLOB` is reused verbatim as the file-operation + filter's glob, so the watcher and the file operations can never be asked + about different sets of files. +- `Workspace::sources()` for the sweep, `Workspace::includes()` for the graph, + `uri::{path_to_uri, uri_to_path}` for the URIs (file-operation params carry + `String` URIs, not parsed ones, so the parse happens in `path_of`). + +### Promised + +- `lucisv_server::file_ops`: + ```rust + pub fn file_operations() -> WorkspaceFileOperationsServerCapabilities; + pub struct Rewrite { pub edit: Option, pub warnings: Vec } + pub fn will_rename(ws: &Workspace, files: &[FileRename]) -> Rewrite; + pub fn renamed(files: &[FileRename]) -> Vec; + pub fn deleted(files: &[FileDelete]) -> Vec; + pub fn touches_scope(paths: &[PathBuf], filelist: Option<&Path>) -> bool; + ``` + `Rewrite::edit` is `None` when there is nothing to do, and the handler + answers that as the protocol's `null` rather than as an empty edit. +- `Server::reindex_for(paths)` — the notification half, one `reindex()` when + the paths touch the index's scope. Deliberately **not** deduplicated against + the watcher: a client is free to send both a `didRenameFiles` and a + `didChangeWatchedFiles` for one rename, and the second rebuild is a pure + re-read of the tree. It costs one scan and one diagnostics generation, never + a different answer. +- `main.rs` advertises `workspace.fileOperations`; `report_scope`'s doc now + says it serves these warnings too. + +### Not touched + +No other crate. No new dependency. No version bump. `verify.rs`, the formatter +and the linter are not on this path at all. + +## Cost + +`willRenameFiles` sweeps the workspace once per request. Measured 2026-08-27 on +the checked-in 860-file corpus, `--release`: + +| | | +|---|---| +| files read (`sources()`) | 860 | +| one rename, whole sweep | **~54 ms** | +| the index rebuild a save already pays | ~320 ms | + +Most of it is the file read `sources()` does — the same read +`callHierarchy/incomingCalls` (56 ms) and `typeHierarchy/subtypes` (55 ms) pay, +and for the same reason. A `text.contains("`include")` prefilter keeps the +resolver off the ~86% of files that include nothing. Pinned by an `#[ignore]`d +probe (`cargo test --release -p lucisv_server --bin lucisv-server +file_ops::tests::perf -- --ignored --nocapture`), the same shape as +`includes.rs`'s: it prints and asserts nothing but the corpus's presence. + +The notifications cost one `reindex()` each, which is the cost a save has. + +## Status / TODO + +- [x] `crates/lucisv_server/src/file_ops.rs`: the capability shape, the sweep, + the candidate spellings, the three safety checks, the post-rename + filesystem model, the notification filters. +- [x] `workspace/willRenameFiles` dispatched in `server.rs`, answering + `WorkspaceEdit | null` and reporting stranded includes through + `report_scope`. +- [x] `workspace/didRenameFiles` + `workspace/didDeleteFiles` dispatched, one + `reindex()` per notification that touches scope. +- [x] `workspace.fileOperations` advertised in `main.rs` — source-file filters + for all three, plus a folder filter on `willRename`. +- [x] `IncludeGraph::resolve_as_if` / `incdirs()` / `pub normalize`, so there + is still one search order and one path folding. +- [x] `watch::watched` made public, so the notifications and the watcher share + one scope test. +- [x] Tests: 24 in `file_ops.rs`, 7 in `server.rs` (dispatch, warning volume, + reindex, watcher-double, unopened file, `null`), 1 in `main.rs` (the + capability on the wire), 1 e2e session (real binary, edit decoded, + applied, rename performed, include re-resolving). +- [x] `cargo fmt`, `cargo clippy --all-targets`, `cargo test --workspace`, + `node editors/vscode/smoke.js`. +- [ ] **Not done, deliberately:** `willCreateFiles`/`didCreateFiles`. A file + that has just been created has nothing pointing at it to rewrite, and the + watcher indexes it. +- [ ] **Not done, deliberately:** `willDeleteFiles`. Refusing a delete the user + asked for, or editing the includes of a file that is about to stop + existing, is not this server's business; `didDeleteFiles` reindexes and + the include simply stops resolving, which is the truth. +- [ ] **Not done, deliberately:** the filelist is never rewritten. Renaming a + file the `.f` names, or the directory an `+incdir+` names, leaves the + filelist stale — lucisv warns about a filelist naming a file that is gone + on the very next rebuild, and fixing it is the user's call. Editing a + project's build manifest from a rename gesture is a much bigger promise + than this feature makes. +- [ ] **Not done, deliberately:** an include in a file the scope ladder + excludes is not rewritten. Same rule as everywhere else in the server. +- [ ] **Not done, deliberately:** no `documentChanges`/`renameFile` operations + in the answer — plain `changes`, as `textDocument/rename` returns. The + client is doing the renaming; the server has only text to contribute. + +## Work log + +### 2026-08-27 — dev agent, file operations (TODO.md §9c) + +Built in the order the brief lists: the resolution extension first, then the +sweep, then the dispatch, then the tests. Decisions worth recording: + +- **`resolve_as_if` rather than a second resolver.** The one thing this module + needs that `includes.rs` did not have is "where would this include land if + the filesystem looked like *that*". Writing that here would have been a + second copy of the EDA rung order, three weeks after the include-nav round + concluded that two scanners meant "`documentLink` and the graph disagreeing + in exactly the corner cases nobody tests". So `resolve` grew an existence + predicate and became a one-line call into the general form. No behaviour + change: the ordinary path passes `|p| p.is_file()`, which is the expression + it had inline. +- **Folder renames are handled, not declined** — the brief left the choice to + the code, and the code made it easy: `Moves` maps a path by prefix, and a + file is just a prefix with no children. The whole folder story is one extra + filter in the capability. Two tests pin it (a folder of headers moving, and + an `+incdir+` directory moving). +- **The rule grew a mirror half, deliberately.** The brief scoped this to + includes whose *target* is renamed. Writing the tests turned up the twin: an + include breaks just as thoroughly when the file it is written *in* moves, + because the own-directory rung goes with it — and that case would have been + silent, with no edit and no warning. It is the same machinery (`target = + moves.after(old).unwrap_or(old)`, and the includer resolved from where it + will be), so it shipped. `a_file_that_moves_away_from_its_own_headers_is_re_spelled_too`. +- **Two of the first tests were wrong, and the code was right.** Both asserted + an edit where the correct answer is *no* edit: a header moving into an + `+incdir+` under the same name, and a batch carrying includer and included + into one new directory, both leave the line already reading correctly. That + is what added the explicit "does it still resolve as written?" guard at the + top of the loop — without it, the candidate ranking would have rewritten a + perfectly good `"../inc/defs.svh"` into a bare `"defs.svh"` during an + unrelated in-place rename, which is a diff the user did not ask for. +- **One real bug, found by a failing test, not by review.** `Moves::is_file` + compared paths lexically while the resolver hands it un-folded candidates + like `rtl/../inc/defs.svh` — `Path::is_file` follows the `..` itself, a + prefix comparison does not. Every `..`-relative candidate silently failed to + verify, which showed up as "no spelling reaches it" on the two tests that + need the relative fallback. `is_file` now folds first, through + `includes::normalize` — the same fold the resolver's own result goes through, + which is why that function is now `pub` rather than copied. +- **A renamed `+incdir+` directory re-spells relatively rather than warning.** + The first draft warned, on the grounds that only the filelist can really fix + it. The relative fallback resolves in every tool through the rung every tool + has, so the source keeps compiling; the stale `+incdir+` is a filelist + problem lucisv already reports on the next rebuild. Pinned, with the + trade-off written into the test. +- **`report_scope` reused rather than a second warning path.** "Log all, show + the first" is exactly the volume control this needs — a rename can strand + forty includes as easily as a filelist can name forty missing files. Its doc + comment now says so; no code moved. + +**Files touched outside this feature's own module**, all of them the wiring the +brief asked for: `includes.rs` (`resolve_as_if`, `incdirs()`, `normalize` made +public — no behaviour change), `watch.rs` (`watched` made public), `main.rs` +(the module, the `workspace.fileOperations` capability, one test), `server.rs` +(the request arm, the two notification arms, `reindex_for`, one doc sentence on +`report_scope`, seven tests), `tests/e2e.rs` (one session and one `apply_edits` +helper). + +**Verification.** `cargo fmt --all -- --check` clean; `cargo clippy +--all-targets` silent; `cargo test --workspace` green — **2105 passing, 5 +ignored**, 33 of them new (24 `file_ops`, 7 `server`, 1 `main`, 1 e2e session) +plus the ignored perf probe. `node editors/vscode/smoke.js +target/debug/lucisv-server` → OK, 9 messages, unchanged from `bf17ddd` +(checked against the stashed tree, not assumed — the new capability is static +JSON and adds no message). Perf measured as above. No new dependency, no +version bump, no other crate touched. + +## QA log + +### 2026-08-27 — QA agent, file operations (TODO.md §9c) + +Re-ran every gate, then attacked the list the lead handed down. One real bug +found and fixed (small, unambiguous, in-scope — fixed directly per the +workflow rules rather than kicked back to dev); everything else the dev +claimed held up, including the single highest-risk detail. + +**Verdict up front: the pre-rename-URI semantics are correct.** `will_rename` +keys every edit off the path `Workspace::sources()` handed it — which is +always the file's *current* (pre-rename) location, including for the mirror +case where the edited file is itself one of the files being renamed. Read the +code to confirm, then pinned it at the wire level, which the dev's own e2e +session did not cover (it only exercised "another file's edit," not "the +moving file's own edit"): added +`a_moving_includer_s_own_edit_is_addressed_to_its_old_uri_on_the_wire` to +`crates/lucisv_server/tests/e2e.rs` — a real `willRenameFiles` round trip +where the *renamed* file is also the includer needing the edit, asserting the +`WorkspaceEdit`'s `changes` map is keyed by the **old** URI and does **not** +contain the new one. Passes. + +**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets +--workspace` silent (one warning surfaced in a QA-added test — +`clippy::for_kv_map` on `for (_, edits) in &map` — fixed to `.values()`, +noted below). `cargo test --workspace`: **2114 passed, 0 failed, 5 ignored** +(2105 baseline + 1 e2e test + 8 new `file_ops` QA tests). Two full runs of +`cargo test -p lucisv_server file_ops::` diffed byte-for-byte except for +parallel test-execution order — no flakiness. `node editors/vscode/smoke.js +target/debug/lucisv-server` → OK, 9 messages. + +**Finding 1 (MEDIUM, fixed) — `candidate_spellings` silently fails when the +includer's own path isn't already `.`/`..`-folded.** +`crates/lucisv_server/src/file_ops.rs`, `candidate_spellings` (now around +line 293) and `relative_spelling`. `target` (the rename's destination) +always reaches `candidate_spellings` normalized — both `graph.resolve` and +`Moves::after` fold `.`/`..` before returning. `includer` did not: it comes +straight from `Workspace::sources()`, which inherits whatever `self.roots` +was given at `open_roots`, unnormalized. `target.strip_prefix(dir)` and +`relative_spelling`'s common-prefix walk are pure path-*component* algebra +run before anything touches the filesystem, and `Path`'s components compare a +literal `ParentDir` (`..`) as different from the directory it resolves to — +so when `includer`'s directory carries an unfolded `..` and `target` doesn't, +every rung silently fails to match, even the trivial "keep it bare" spelling +for a same-directory rename. The include then gets a spurious "no include +path reaches it" warning instead of the one-word edit it should get. Caught +by the corpus-scale probe (below), not by any of the dev's or my +hand-written unit tests — every `Tree`-based test in this feature builds +`ws.open_roots(vec![tree.path.clone()])` from an already-clean +`std::env::temp_dir()`-based path, so the bug had no way to show up there. +`resolve`/`resolve_as_if`'s own existence checks (`Path::is_file`, +`Moves::is_file`) were never affected — both fold `..` themselves before +deciding, which is exactly why only this one pure-path step needed the fix. +Fixed with one line, normalizing `includer` at the top of +`candidate_spellings` before anything derives from it; comment explains why, +inline. Real-world exposure: narrow but not zero — `workspace_roots` in +`main.rs` never normalizes a client's `rootUri`/`workspace_folders` URI +either, so any workspace root a client hands over with an unresolved `.`/`..` +segment (unusual, but not forbidden by the URI grammar) would have hit this +on every single same-directory rename, the most common case there is. +Pinned by the corpus probe test itself (below), which fails without the fix +and passes with it — no separate minimal regression test added, since the +probe already exercises the exact shape that triggers it and a synthetic +`Tree`-based one would have to manufacture a dirty root on purpose, which is +what the probe already is. + +**Attack surfaces, in the order asked for:** + +1. **Wrong-edit hunts at the resolution boundary — verified clean.** Added + `a_shadow_between_an_own_dir_file_and_an_incdir_file_is_never_crossed`: two + `defs.svh`, one reached only via the includer's own directory and one only + via an `+incdir+`, so a name-matching implementation would cross them. + Renaming either one touches only the file that resolves to it, in both + directions. `resolve_as_if`'s delegation from `resolve` is the same + inlined closure `resolve` used before (`&|path| path.is_file()`) — no + include-nav test needed updating, and the full suite confirms + `documentLink`/`definition`/hover behavior is unchanged. +2. **The three checks, adversarially — verified clean, one gap closed.** + (a) `the_edit_range_is_exact_with_tab_indentation_and_a_block_comment`: + tabs for indentation, a `/* block */` trailing comment instead of the + dev's `//` line comment, byte range decoded and checked against the raw + text — exact. (b) `a_rename_target_whose_name_contains_the_quote_delimiter_is_refused_not_written`: + POSIX allows `"` in a filename (confirmed creatable on this filesystem), + and with no other candidate spelling available the module is forced to + either refuse or write a corrupting line — it refuses, warns, and the + source file on disk is provably untouched. Also + `a_rename_to_a_name_with_a_space_or_non_ascii_text_is_written_correctly`: + space and non-ASCII (`défs.svh`) are legal inside quotes and both rewrite + cleanly — the "total, correct" half of the same question. (c) the dev's + `a_spelling_that_would_resolve_somewhere_else_is_not_written` is a genuine + shadow: `rtl/defs.svh` pre-exists beside the includer, the bare candidate + for the renamed `inc/old.svh` → `inc/defs.svh` would resolve to the wrong + file via the own-directory rung, and the longer `../inc/defs.svh` is + written instead — read through by hand and confirmed live by the suite. +3. **The mirror case (includer moves) — verified clean, see the verdict + above.** `Moves`'s own-dir-move handling and the pre-rename URI addressing + are both correct. +4. **Directory renames by prefix — verified clean.** + `a_directory_rename_does_not_claim_a_sibling_with_a_shared_string_prefix`: + `rtl` → `rtl2` with a `rtl_extra/` sibling holding its own decoy header, + both referenced relatively from outside their own directories (so the + test actually forces an edit rather than landing on the includer-and- + included-move-together no-op). `rtl_extra`'s file is never touched, and + `Moves`'s `mapped`/`strip_prefix` is checked directly too: `Path::strip_prefix` + is component-wise, not string-wise, so `rtl_extra` was never at risk from + this angle. Nested batch: + `a_directory_rename_and_a_file_rename_inside_it_do_not_compound` — + characterized, not "fixed": `Moves::after` uses `find_map`, so a directory + rename and an explicit rename of a file inside it (a batch shape a + spec-compliant client should not send, per LSP's "only the folder's own + URI" rule, but nothing stops one from doing it) do not compound; whichever + entry is listed first in `params.files` wins for any path under that + directory, and the other is silently shadowed. Not corruption — whatever + spelling gets written is still checked against whichever model `Moves` + produced — but it is order-dependent in a way nothing documents. + **Recommendation for dev, not fixed here (out of QA's remit to redesign):** + either note this explicitly in the Assumptions section as an accepted + ambiguity, or have `Moves::announced` detect a file entry nested under a + directory entry in the same batch and drop the redundant one with a + warning. Low priority — real clients don't appear to construct this shape. +5. **Batch semantics — verified clean.** + `a_batch_where_both_the_includer_and_the_included_move_needs_both_moves_modeled`: + includer moves two directories deep, included file moves to an unrelated + directory, in one batch. Chose depths that make "only one move modeled" + produce a *textually different, wrong* answer both ways (dropping the + includer's move is one `..` short; dropping the included file's move + points at the old directory) — the actual answer is neither, confirming + `Moves` truly models both simultaneously rather than one overwriting the + other. The dev's own `a_batch_that_carries_includer_and_included_together_writes_nothing` + is a real instance of this too (a no-op *requires* both moves to be seen + together), just not one that discriminates between hypotheses on its own. +6. **`didRename`/`didDelete` — verified clean.** Read `reindex_for` and the + dispatch arms; the dev's own tests already cover in-scope → one reindex, + out-of-scope → none, and the watcher-double case, and pass. Generation + bumps once per `reindex()` call, so a client sending both + `didRenameFiles` and a watcher event for the same move bumps it twice — + documented as intentional ("a pure re-read of the tree"), matches + `a_rename_notification_rebuilds_the_index`'s own assertion, no + pull-diagnostics correctness issue (content converges, `resultId` just + changes an extra time). +7. **Capability shape on the wire — verified clean.** `main.rs`'s + `the_file_operations_reach_the_wire_under_workspace` and `file_ops.rs`'s + `the_capability_names_the_operations_this_server_answers` pin the exact + JSON; folder filter present only on `willRename`, absent on both + notifications, confirmed. Case sensitivity: the glob match is entirely the + *client's* job (VS Code decides whether `TOP.SV` matches `**/*.{v,vh,sv,svh}` + before it ever sends the request) — nothing in this server's code path is + involved, so there is nothing here to fix or test; noting it per the + brief's "don't over-engineer." +8. **CLAUDE.md compliance — verified clean.** No `unwrap()`/`expect()`/ + `panic!` outside `#[cfg(test)]` in any of `file_ops.rs`, `server.rs`, + `main.rs`, `watch.rs`, `includes.rs` (checked with a diff-scoped grep). + Every public item has a one-line doc comment. This README's sections each + appear exactly once. `TODO.md`'s §9c item text is unchanged; only its + checkbox flipped and a delivery summary was appended below it, per the + "leave the item text intact" rule. `verify.rs` does not appear in the diff + at all. + +**Beyond the list — corpus-scale probe.** `prim_assert.sv` (a single real +file in `corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/`) is included, own- +directory rung, by 87 sibling files in that same directory — real fan-out, +not a synthetic tree. Added +`a_real_corpus_header_with_wide_fan_out_is_swept_correctly_and_deterministically`: +sweeps the whole corpus with `will_rename` twice (identical file/warning +counts both times), then independently re-derives, for every produced edit, +whether the *written* spelling resolves to the new location once the +modeled rename has happened (built the check from `resolve_as_if` + +`Moves::announced` directly, deliberately not by calling back into +`survives`, so it is a genuine second opinion) — and confirms every touched +file's directory is the one real directory that includes this header, +nothing else. This is the test that caught Finding 1: it failed outright +before the fix (no edit was produced for any of the 87 files — every one +came back as a false "unreachable" warning) and passes cleanly after. + +**Test tally added this round:** 8 in `file_ops.rs` (`qa_2026_08_27_attacks`, +nested under `mod tests`), 1 in `tests/e2e.rs`. `cargo test --workspace`: +2114 passed (was 2105 before this QA round; +1 e2e +8 file_ops, net of the +9 new tests exactly). + +**Verdict: not committable as-is until Finding 1's fix is included** — which +it now is, applied directly in this same working tree (small, unambiguous, +in-scope per the workflow rules). With the fix in place and all eight attack +surfaces plus the corpus probe green, this is **committable**. Item 4's +nested-batch ordering is a documentation/robustness suggestion for the dev, +not a blocker — no corruption path exists even in that shape, thanks to the +safety net doing its job independently of what `Moves` models. + +## Review + +### 2026-08-27 — lead + +Reviewed the diff, the work log and the QA log; re-ran all gates myself +(2114 workspace tests, 0 failed), clean. For a feature that writes user +files, the shape is right: resolution-not-name matching, a three-check +safety net that refuses rather than guesses, and the mirror case the +brief missed shipped with the same machinery rather than a special +case. The two dev deviations are both accepted as argued — the moving +includer's own-dir rung genuinely breaks, and re-spelling under a +renamed +incdir+ beats warning about a filelist this server rightly +does not edit. + +The round's two QA results are exactly why the corpus probe belongs in +every write-path charter: the unnormalized-includer bug made the most +common rename shape (same directory) silently fail into a warning, and +no hand-written fixture caught it — 87 real includers of a real ibex +header did. And the pre-rename-URI wire test QA added covers the one +detail that would have failed invisibly in real editors (a client +drops an edit addressed to the post-rename uri). I applied QA's +recommendation as an Assumptions entry: batch renames do not compound, +recorded as a documented choice with the safety net bounding the +failure mode at a skipped edit plus a warning. Accepted as shipped. diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index 59f1074..d9d024e 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -52,6 +52,8 @@ looks like language knowledge in here is a bug or a `Handshake` request. | `workspace/codeLens/refresh` | — | Server-**initiated**, once per workspace rescan, straight after the indexing bar comes down: a rescan can change any count on screen. Only for a client that advertised `workspace.codeLens.refreshSupport`; never at startup, where no buffer holds lenses. Same feature README | | `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits | | `workspace/didChangeWatchedFiles` | `Workspace::rebuild_index` | Registered dynamically after the handshake, for a client that advertised it. One rebuild per *notification*, however many files it names. See `docs/features/file-watching/README.md` | +| `workspace/willRenameFiles` | `includes::IncludeGraph` (through `resolve_as_if`) | The client is about to rename files and asks what that costs: every `` `include`` in scope whose **resolved** target moves — never a filename match — is re-spelled so it still resolves, in the form it was written in (bare stays bare where a rung reaches it, angled resolves through `+incdir+`s only, absolute stays absolute), shortest resolving suffix first and a `../`-relative spelling only as a last resort. An include written *in* a file that moves is re-spelled too. An include no spelling can reach is **left exactly as written** and named in a `window/showMessage` warning — nothing is invented. `null` when there is nothing to do. Folders are answered as well as files (LSP sends only the folder's URI; a folder is a path prefix). Every edit covers the path token alone and is verified three ways before it is emitted — see `docs/features/file-operations/README.md` | +| `workspace/didRenameFiles`, `workspace/didDeleteFiles` | `Workspace::rebuild_index` | One `reindex()` per notification whose paths touch the index's scope, filtered by the same predicate a watched-file event is. Deliberately not deduplicated against the watcher: a client may send both, and a second rebuild re-reads the tree rather than changing an answer. Source-file filters only — a folder move reaches the index through the watcher's own events. Same feature README | | `window/workDoneProgress/create` + `$/progress` | — | Server-**initiated**: one indeterminate bar per workspace rescan, titled "Indexing Verilog workspace", ending with the indexed file count. Only for a client that advertised `window.workDoneProgress`. See `docs/features/work-done-progress/README.md` | | `$/cancelRequest` | — | Best-effort, and honoured exactly when the cancel reaches the loop in the same burst as the request it names: that request is answered `RequestCancelled` (-32800) instead of computed. A cancel for anything else is dropped where it is read, `shutdown` is never cancellable, and nothing already running is interrupted. See `docs/features/cancel-request/README.md` | @@ -587,6 +589,11 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory: `docs/features/type-hierarchy/README.md`. - [x] Single-step macro expansion on a hover card (`src/expand.rs`, M14) — `docs/features/macro-expansion/README.md`. +- [x] `workspace/willRenameFiles` + `didRenameFiles`/`didDeleteFiles` — + delivered by **file-operations** (2026-08-27, TODO.md §9c): a rename + rewrites the `` `include``s that resolve to the moved file, folders + included, and never invents a path that would not resolve. + `docs/features/file-operations/README.md`. - [x] `$/cancelRequest` — delivered by **cancel-request** (2026-08-26, completing TODO.md §9b): the loop reads in bursts and answers a queued request whose cancel is in the same burst with `RequestCancelled`,