//! `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 files the include graph recorded an `` `include`` in /// (`Workspace::include_sources`, so an unopened one 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. /// /// It used to read *every* in-scope file, which on a 3 976-file workspace is /// 3 900-odd reads to answer "this file has no `` `include``". The graph /// already holds that answer; the argument that the smaller set gives the /// identical `Rewrite` is in `docs/features/file-operations/README.md`. 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.include_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_whole_workspace(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 sufficiency property [`will_rename`]'s narrowed sweep rests on, /// asserted directly over whatever tree the caller built: every in-scope /// file the sweep no longer reads writes no `` `include`` this workspace /// can resolve, so its turn in the loop could only ever have `continue`d. /// /// Checked as the complement rather than as an equality because it is the /// complement that could hide a lost edit: an extra file in the set costs /// a read, a missing one costs an `` `include`` left pointing at nothing. fn nothing_skipped_has_an_include_to_rewrite(ws: &Workspace) { let read: Vec = ws.include_sources().into_iter().map(|(path, _)| path).collect(); let graph = ws.includes(); let mut skipped = 0usize; for (path, text) in ws.sources() { if read.contains(&path) { continue; } skipped += 1; for include in scan(&text) { assert!( graph.resolve(Some(&path), &include).is_none(), "{} was skipped but its `include \"{}\"` resolves", path.display(), include.target ); } } assert!(skipped > 0, "the tree must actually exercise the narrowing"); } /// 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 } /// A wide workspace where almost nothing includes anything — the shape a /// real one has, and the reason the sweep no longer reads all of it. The /// answer must be the one the whole-workspace sweep gave, and the property /// above must hold over the same tree. #[test] fn the_narrowed_sweep_reads_the_includers_and_answers_the_same() { let tree = Tree::new("narrowed"); tree.write("rtl/defs.svh", "`define W 8\n"); let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n"); let mut list = String::from("rtl/top.sv\nrtl/defs.svh\n"); // Twenty files with no `include at all, plus two whose includes name // nothing on disk — both kinds are files the sweep may skip. for n in 0..20 { let rel = format!("rtl/quiet{n}.sv"); tree.write(&rel, &format!("module quiet{n};\n wire w;\nendmodule\n")); list.push_str(&format!("{rel}\n")); } for n in 0..2 { let rel = format!("rtl/dangling{n}.sv"); tree.write(&rel, &format!("`include \"no_such_{n}.svh\"\nmodule d{n};\nendmodule\n")); list.push_str(&format!("{rel}\n")); } tree.write("files.f", &list); let ws = tree.workspace(); assert_eq!(ws.sources().len(), 24, "the whole scope"); assert_eq!(ws.include_sources().len(), 1, "only `top.sv` includes anything that lands"); nothing_skipped_has_an_include_to_rewrite(&ws); 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()])); } /// An `` `include`` typed into a buffer and not yet saved is in no edge the /// graph holds — the graph is rebuilt on save. The buffer is in the sweep /// whatever the graph says, which is what keeps that include rewritten. #[test] fn an_unsaved_include_is_still_rewritten() { let tree = Tree::new("unsaved_include"); 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(); assert_eq!(ws.include_sources().len(), 0, "premise: the graph knows of no include"); let buffered = "`include \"defs.svh\"\nmodule t;\nendmodule\n"; ws.set_document(path_to_uri(&top).expect("uri"), buffered.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()])); assert_eq!( applied(buffered, &rewrite, &uri_of(&top)), "`include \"widths.svh\"\nmodule t;\nendmodule\n" ); } /// QA, 2026-08-28 attack: a chain `a.svh -> b.svh`. Renaming `b.svh` must /// narrow to `a.svh` (its *direct* includer, via `includers()`), and must /// **not** narrow away a file that includes `a.svh` but never spells /// `b.svh` at all — `will_rename` only ever rewrites a *direct* include of /// the file that moves, so a third-order includer has nothing to rewrite /// either way, but it must still not be mistaken for a candidate (which /// would cost a read, not a corruption, but is worth pinning). #[test] fn an_include_chain_narrows_to_the_direct_includer_of_the_moved_file() { let tree = Tree::new("chain"); tree.write("rtl/b.svh", "`define W 8\n"); let a = tree.write("rtl/a.svh", "`include \"b.svh\"\n"); let c = tree.write("rtl/c.sv", "`include \"a.svh\"\nmodule c;\nendmodule\n"); tree.write("files.f", "rtl/a.svh\nrtl/b.svh\nrtl/c.sv\n"); let ws = tree.workspace(); let read: Vec = ws.include_sources().into_iter().map(|(path, _)| path).collect(); assert!(read.contains(&a), "a.svh includes b.svh directly: {read:?}"); assert!(read.contains(&c), "c.sv includes a.svh directly: {read:?}"); nothing_skipped_has_an_include_to_rewrite(&ws); let rewrite = will_rename(&ws, &[tree.rename("rtl/b.svh", "rtl/renamed_b.svh")]); assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); // Only a.svh's own `include \"b.svh\"` line changes; c.sv's // `include \"a.svh\"` is untouched because a.svh itself did not move. assert_eq!(only_file(&rewrite), (uri_of(&a), vec!["renamed_b.svh".to_string()])); } /// QA, 2026-08-28 attack: an include spelled with different letter case /// than the file actually has on disk (`` `include "DEFS.svh"`` against a /// real `defs.svh`) — legal and silently resolved on the common /// case-insensitive filesystems (confirmed case-insensitive in this test /// environment). `IncludeGraph::found`/`found_as_if` resolve through the /// filesystem's own `Path::is_file`, so the includer still lands in `raw` /// (keyed by the *includer's* path, not the target's spelling) and /// therefore in `includers()`/`include_sources()` — the narrowing must not /// accidentally depend on the include's target spelling matching the /// disk's. #[test] fn a_case_mismatched_include_spelling_still_narrows_in_and_rewrites() { let tree = Tree::new("case_mismatch"); 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 read: Vec = ws.include_sources().into_iter().map(|(path, _)| path).collect(); assert!( read.contains(&top), "top.sv's case-mismatched include still resolves and must narrow in: {read:?}" ); 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()])); } #[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" ); } /// Renaming a file that is open **on the large-file fast path** /// (`docs/features/large-file-mode/README.md`). The renamed file's own /// `` `include``s (it has none here — a netlist would not) are out of /// `will_rename`'s sweep because `Workspace::sources()` already leaves a /// fast-path buffer out entirely; what this pins is the other half: an /// **unrelated** small file's include *of* the large file still resolves /// and still gets rewritten, because resolution walks the filesystem /// (`IncludeGraph::resolve`, `Path::is_file`) rather than the source list /// the fast-path buffer was excluded from. #[test] fn renaming_a_large_open_buffer_still_rewrites_other_files_includes_to_it() { let tree = Tree::new("largerename"); let net = tree.write("rtl/net.v", "module net;\nendmodule\n"); let top = tree.write("rtl/top.sv", "`include \"net.v\"\nmodule t;\nendmodule\n"); tree.write("files.f", "rtl/top.sv\nrtl/net.v\n"); let mut ws = tree.workspace(); ws.set_client_settings(crate::settings::ClientSettings { filelist: Some(tree.path.join("files.f").display().to_string()), large_file_threshold: 10, ..Default::default() }); let net_uri = path_to_uri(&net).expect("uri"); // Padded past the 10-byte test threshold, so it opens on the fast path. ws.set_document(net_uri.clone(), format!("module net;\nendmodule\n{}", " ".repeat(20))); assert!(ws.document(&net_uri).expect("open").large, "premise: the fast path"); let rewrite = will_rename(&ws, &[tree.rename("rtl/net.v", "rtl/netlist.v")]); assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["netlist.v".to_string()])); } #[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_whole_workspace(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"); // Skipped when `corpus/` is not checked out, like every other // corpus test in this crate — asserting its presence panicked any // environment (a bare CI checkout, `act`) that never fetched it. if !old.is_file() { eprintln!("corpus/ not checked out — skipping"); return; } let new = target_dir.join("prim_assert_renamed.sv"); let mut ws = Workspace::default(); ws.open_whole_workspace(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)); } } }