diff --git a/TODO.md b/TODO.md index 1d2a84d..0feb4d2 100644 --- a/TODO.md +++ b/TODO.md @@ -1148,12 +1148,24 @@ crates/lucisv_server/src/{rename.rs,file_ops.rs,state.rs,perf.rs}, docs/features/{refactor-rename,file-operations}/README.md, docs/perf/README.md) -- [ ] `prepareRename` 2.5–3.0 s (F2 blocks everything) → buffer+index +- [x] `prepareRename` 2.5–3.0 s (F2 blocks everything) → buffer+index answer, < 1 ms; refusal-by-refusal parity table in the README. -- [ ] `rename` 3.6–8.7 s → reference-postings fan-out subset with a + **1.663 s → 139 ns on OpenTitan**; parity table and six + byte-by-byte parity suites in refactor-rename's README, plus 564 + offsets of a real `tb.sv` swept identical, zero deferrals. +- [x] `rename` 3.6–8.7 s → reference-postings fan-out subset with a written sufficiency argument; verifier integrity proven. -- [ ] `willRenameFiles` same `ws.sources()` shape (file_ops.rs:120) → - include-graph/index-bounded subset. + **3.467 s → 105.5 ms on OpenTitan**, edits byte-identical at every + cursor checked (7 files at `aes`, 114 files at `clk_rst_if`), the + capture refusal still firing on a real workspace. QA found one + lost refusal (a dangling use of the *new* name); closed by a sixth + rung, `WorkspaceIndex::files_spelling` — 852 µs worst case on + OpenTitan. One accepted residue remains — + macro-**invocation**-argument warnings in files outside the + fan-out, costing no edit and no refusal. +- [x] `willRenameFiles` same `ws.sources()` shape (file_ops.rs:120) → + include-graph/index-bounded subset. **249 ms of `sources()` → a + 14.1 ms whole answer on OpenTitan** (331 includers of 3 976). ### Lane B — hot path + UX (worktree B; files: crates/lucisv_server/src/{completion.rs,candidates.rs,nav.rs, @@ -1177,6 +1189,14 @@ references-nav,index-scope}/README.md, docs/perf/README.md) index-only (~0 ms regardless of fan-out), edits computed on lightbulb click — kills the 83 ms worst case. Owner-approved direction, after the wave. -- [ ] Rename over an index-stale workspace: Lane A must state the +- [x] Rename over an index-stale workspace: Lane A must state the staleness premise; if the verifier cannot catch a hidden - reference, the honesty gate is the lead's review call. + reference, the honesty gate is the lead's review call. Stated + verbatim under "The staleness premise, stated exactly" in + refactor-rename's README, with what it costs (a file whose disk + copy moved unseen is neither rewritten nor refused over) and the + one exemption (open buffers, always in the set). Both residues + ruled on: the dangling-use lost refusal was rejected and fixed + (rung 6, `files_spelling`); the macro-invocation warning loss is + accepted as documented, with the `FileFacts` macro census filed + as the real fix. diff --git a/crates/lucisv_server/src/file_ops.rs b/crates/lucisv_server/src/file_ops.rs index 8104cb5..ed9aadb 100644 --- a/crates/lucisv_server/src/file_ops.rs +++ b/crates/lucisv_server/src/file_ops.rs @@ -105,10 +105,15 @@ pub struct Rewrite { /// 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. +/// 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() { @@ -117,7 +122,7 @@ pub fn will_rename(ws: &Workspace, files: &[FileRename]) -> Rewrite { let graph = ws.includes(); let mut changes: HashMap> = HashMap::new(); let mut warnings = Vec::new(); - for (path, text) in ws.sources() { + 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") { @@ -542,6 +547,35 @@ mod tests { 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"); @@ -579,6 +613,120 @@ mod tests { 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"); diff --git a/crates/lucisv_server/src/includes.rs b/crates/lucisv_server/src/includes.rs index 237d121..e39e97c 100644 --- a/crates/lucisv_server/src/includes.rs +++ b/crates/lucisv_server/src/includes.rs @@ -325,6 +325,18 @@ impl IncludeGraph { } } + /// Every file that writes at least one `` `include`` the disk answered — + /// the keys of the edge table, in no particular order. + /// + /// The complement is the interesting half: a file that is *not* here + /// either includes nothing or includes only what nothing resolves, so + /// [`IncludeGraph::resolve`] answers `None` for every include it writes. + /// `file_ops.rs` reads that as "this file cannot produce an edit or a + /// warning" and never reads it (`Workspace::include_sources`). + pub fn includers(&self) -> impl Iterator { + self.raw.keys() + } + /// Every file reachable from `seeds` through include edges, the seeds /// themselves included. /// diff --git a/crates/lucisv_server/src/perf.rs b/crates/lucisv_server/src/perf.rs index 4a8ac72..d1cc826 100644 --- a/crates/lucisv_server/src/perf.rs +++ b/crates/lucisv_server/src/perf.rs @@ -637,11 +637,9 @@ fn a_code_action_at_an_instantiation_before_and_after() { let read = mean(3, || { black_box(ws.sources()); }); - // What `textDocument/prepareRename` still costs on the same workspace — - // the number the follow-up in the feature README is filed with. Left - // alone deliberately: a rename must see every file that could name the - // symbol, and the postings-based subset for it is its own design - // discussion. + // What `textDocument/prepareRename` cost on the same workspace when this + // probe was written — the number the follow-up in the feature README was + // filed with, and the one `a_rename_before_and_after` below now closes. let prepare = mean(3, || { let sources = ws.sources(); let _ = @@ -657,3 +655,147 @@ fn a_code_action_at_an_instantiation_before_and_after() { ); let _ = std::fs::remove_dir_all(&dir); } + +/// A workspace of `files` unrelated generated modules plus a `sub` module +/// instantiated by three tops — the shape both rename probes measure over. +/// Returns the directory, so the caller removes it. +fn rename_corpus(tag: &str, files: usize, lines: usize) -> (PathBuf, &'static str) { + let sub = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n"; + let dir = std::env::temp_dir().join(format!("lucisv_perf_{tag}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + std::fs::write(dir.join("sub.sv"), sub).expect("write"); + for n in 0..3 { + std::fs::write( + dir.join(format!("top{n}.sv")), + format!("module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"), + ) + .expect("write"); + } + for n in 0..files { + std::fs::write( + dir.join(format!("f{n:04}.sv")), + generated_module(&format!("f{n:04}"), lines), + ) + .expect("write"); + } + (dir, sub) +} + +/// `cargo test --release -p lucisv_server perf::a_rename -- --ignored --nocapture --test-threads=1` +#[test] +#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] +fn a_rename_before_and_after() { + // The owner's OpenTitan session: `prepareRename` 2.5–3.0 s and `rename` + // 3.6–8.7 s, both of them `ws.sources()` followed by an index build and an + // analysis over every in-scope file. `prepareRename` is what the rename + // key sends *before the box opens*, so those seconds are a frozen editor + // on a keypress that has committed to nothing. + // + // Four numbers over one workspace and one cursor: + // + // * **prepare, before** — `prepare_rename` over `sources()`; + // * **prepare, after** — the buffer's own analysis and the index, reading + // nothing; + // * **rename, before** — `rename` over `sources()`; + // * **rename, after** — `rename` over the symbol's fan-out. + let (files, lines) = (500, 200); + let (dir, sub) = rename_corpus("rename", files, lines); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let path = dir.join("sub.sv"); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), sub.to_string()); + // The module's own name, which fans out to the three files naming it. + let offset = sub.find("sub (").expect("the module name") as u32; + + let prepare_before = mean(3, || { + let sources = ws.sources(); + let _ = + black_box(vlog_refactor::prepare_rename(&sources, black_box(&path), black_box(offset))); + }); + let prepare_after = mean(2_000, || { + let _ = black_box(crate::rename::prepare(&ws, &uri, black_box(offset))); + }); + let rename_before = mean(3, || { + let sources = ws.sources(); + let _ = black_box(vlog_refactor::rename(&sources, &path, black_box(offset), "renamed")); + }); + let rename_after = mean(20, || { + let _ = black_box(crate::rename::rename(&ws, &uri, black_box(offset), "renamed")); + }); + let fan_out = ws.rename_sources(&path, "sub", Some("renamed")).len(); + // Building the file set at all, and the one rung of it that is a linear + // walk over every file's records rather than a keyed lookup + // (`WorkspaceIndex::files_spelling`, the new name's dangling-use rung — + // `docs/features/refactor-rename/README.md`). Measured on its own because + // it is the only part of the set builder whose cost grows with the + // workspace rather than with the symbol. + let file_set = mean(2_000, || { + black_box(ws.rename_sources(black_box(&path), "sub", Some("renamed"))); + }); + let spelling_rung = mean(2_000, || { + black_box(ws.index().files_spelling(black_box("renamed")).count()); + }); + + // A measurement of an answer that was not given is worthless. + assert!(crate::rename::prepare(&ws, &uri, offset).is_ok()); + let (edit, _) = crate::rename::rename(&ws, &uri, offset, "renamed").expect("renames"); + assert_eq!(edit.changes.map(|c| c.len()), Some(4), "the module and its three tops"); + + eprintln!( + "rename of `sub`, instantiated in 3 of {} files ({lines} lines each), fan-out {fan_out} files:\n \ + prepareRename: whole workspace {prepare_before:?} -> buffer+index {prepare_after:?}\n \ + rename: whole workspace {rename_before:?} -> fan-out {rename_after:?}\n \ + building the file set: {file_set:?}, of which `files_spelling`: {spelling_rung:?}", + ws.index().files().len() + ); + let _ = std::fs::remove_dir_all(&dir); +} + +/// `cargo test --release -p lucisv_server perf::a_will_rename -- --ignored --nocapture --test-threads=1` +#[test] +#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] +fn a_will_rename_before_and_after() { + // `workspace/willRenameFiles` read every in-scope file to ask each one + // "do you write an `include?" — a question the include graph already + // holds the answer to. Renaming any folder in the VS Code explorer sent + // it, so it is the same `sources()` shape as the two above. + let (files, lines) = (500, 200); + let (dir, _) = rename_corpus("willrename", files, lines); + std::fs::write(dir.join("defs.svh"), "`define W 8\n").expect("write"); + std::fs::write(dir.join("includer.sv"), "`include \"defs.svh\"\nmodule includer;\nendmodule\n") + .expect("write"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri_of = |path: &std::path::Path| path_to_uri(path).expect("uri").as_str().to_string(); + let renamed = vec![lsp_types::FileRename { + old_uri: uri_of(&dir.join("defs.svh")), + new_uri: uri_of(&dir.join("widths.svh")), + }]; + + let read_all = mean(3, || { + black_box(ws.sources()); + }); + let read_includers = mean(200, || { + black_box(ws.include_sources()); + }); + let after = mean(20, || { + black_box(crate::file_ops::will_rename(&ws, black_box(&renamed))); + }); + let rewrite = crate::file_ops::will_rename(&ws, &renamed); + assert_eq!( + rewrite.edit.and_then(|edit| edit.changes.map(|c| c.len())), + Some(1), + "the one includer" + ); + eprintln!( + "willRenameFiles over {} files, 1 of which includes anything:\n \ + reading the scope {read_all:?} -> reading the includers {read_includers:?}\n \ + whole answer, after: {after:?}", + ws.index().files().len() + ); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/lucisv_server/src/rename.rs b/crates/lucisv_server/src/rename.rs index a9f94e2..a4d2ad9 100644 --- a/crates/lucisv_server/src/rename.rs +++ b/crates/lucisv_server/src/rename.rs @@ -24,10 +24,20 @@ use crate::uri::path_to_uri; /// The identifier at `offset` and its current name, or the reason it cannot /// be renamed. Returning the reason — rather than `null` — is what puts the /// engine's sentence in the editor's rename box instead of a shrug. +/// +/// Answered from the buffer's own analysis and the index alone: no file is +/// read, nothing is parsed. This request is what the rename key sends before +/// the rename box even opens, and reading the workspace for it froze the whole +/// server for 2.5–3.0 s on OpenTitan. Which refusals that costs — and which of +/// them `rename` then delivers instead — is the table in +/// `docs/features/refactor-rename/README.md`. pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Result { let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?; - let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?; - let target = vlog_refactor::prepare_rename(&ws.sources(), &path, offset)?; + if doc.path.is_none() { + return Err(UNSAVED.to_string()); + } + let target = + vlog_refactor::prepare_rename_here(&doc.semantics, &doc.external, ws.index(), offset)?; Ok(PrepareRenameResponse::RangeWithPlaceholder { range: doc.positions().range(target.range), placeholder: target.name, @@ -44,7 +54,16 @@ pub fn rename( ) -> Result<(WorkspaceEdit, Vec), String> { let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?; let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?; - let refactoring = vlog_refactor::rename(&ws.sources(), &path, offset, new_name)?; + // The name the cursor sits on, read off the buffer, is what the index is + // asked for the fan-out. No refusal is taken here: `vlog_refactor::rename` + // is the one voice that decides, and it decides over the files below. A + // cursor on nothing has no fan-out to ask for, so the whole scope goes — + // the engine will say so, and saying it is cheap either way. + let sources = match vlog_refactor::rename_name_at(&doc.semantics, offset) { + Some(name) => ws.rename_sources(&path, &name, Some(new_name)), + None => ws.sources(), + }; + let refactoring = vlog_refactor::rename(&sources, &path, offset, new_name)?; let mut changes: HashMap> = HashMap::new(); for (path, edits) in &refactoring.edits { @@ -80,7 +99,7 @@ const UNSAVED: &str = "lucisv can only rename inside a saved file."; mod tests { use super::*; use std::fs; - use std::path::PathBuf; + use std::path::{Path, PathBuf}; use std::str::FromStr; /// A scratch workspace root. Removed on drop. @@ -206,6 +225,617 @@ mod tests { assert_eq!(edits[0].range.start.character, 7); } + // ------------------------------------------------------------------ + // The fan-out equivalence suite + // ------------------------------------------------------------------ + // + // `rename` is handed the symbol's fan-out through the index instead of + // every in-scope file. A rename that edits fewer files than the truth is + // corruption (CLAUDE.md invariant 1), and a refusal the narrow set cannot + // reach is a refusal the user never sees — so every case below asks the + // engine the same question twice, over the subset and over the whole + // workspace, and asserts the two answers are the same bytes and the same + // sentences. The sufficiency argument they are the evidence for is in + // `docs/features/refactor-rename/README.md`. + + /// The file set the server would hand `rename` for a cursor at `offset`. + fn fan_out(ws: &Workspace, path: &Path, offset: u32, new_name: &str) -> Vec { + let doc = ws.document_for_path(path).expect("the request's file is open"); + match vlog_refactor::rename_name_at(&doc.semantics, offset) { + Some(name) => ws.rename_sources(path, &name, Some(new_name)), + None => ws.sources(), + } + .into_iter() + .map(|(path, _)| path) + .collect() + } + + /// Ask the engine over the fan-out and over the whole workspace, and + /// assert the two answers are indistinguishable. Returns the answer, so a + /// caller can also assert *what* it was. + fn same_answer( + ws: &Workspace, + path: &Path, + offset: u32, + new_name: &str, + ) -> Result { + let everything = ws.sources(); + let doc = ws.document_for_path(path).expect("the request's file is open"); + let subset = match vlog_refactor::rename_name_at(&doc.semantics, offset) { + Some(name) => ws.rename_sources(path, &name, Some(new_name)), + None => everything.clone(), + }; + for (path, text) in &subset { + let found = everything.iter().find(|(held, _)| held == path); + assert_eq!( + found.map(|(_, text)| text), + Some(text), + "{} is in the fan-out with text the whole scope does not have", + path.display() + ); + } + let whole = vlog_refactor::rename(&everything, path, offset, new_name); + let narrow = vlog_refactor::rename(&subset, path, offset, new_name); + match (&whole, &narrow) { + (Ok(whole), Ok(narrow)) => { + assert_eq!(whole.edits, narrow.edits, "the fan-out edited different bytes"); + assert_eq!(whole.warnings, narrow.warnings, "the fan-out warned differently"); + } + (Err(whole), Err(narrow)) => { + assert_eq!(whole, narrow, "the fan-out refused in different words"); + } + (Ok(whole), Err(narrow)) => panic!( + "the fan-out invented a refusal: {narrow}, where the workspace edited {} files", + whole.file_count() + ), + (Err(whole), Ok(narrow)) => panic!( + "the fan-out lost the refusal `{whole}` and edited {} files instead", + narrow.file_count() + ), + } + narrow + } + + /// A workspace of `files`, every one of them also opened as a buffer when + /// `open` names it, with the first named file's URI returned. + fn tree_with(tree: &Tree, files: &[(&str, &str)], open: &[&str]) -> (Workspace, Vec) { + let paths: Vec = files.iter().map(|(name, text)| tree.write(name, text)).collect(); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + for name in open { + let path = tree.path.join(name); + let text = fs::read_to_string(&path).expect("written above"); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri, text); + } + (ws, paths) + } + + const MOD: &str = "module sub #(parameter int W = 1) (input logic clk, output logic q);\n wire local_net;\n assign q = clk & local_net;\nendmodule : sub\n"; + const ONE: &str = "module one;\n logic c, d;\n sub u_a (.clk(c), .q(d));\nendmodule\n"; + const TWO: &str = + "module two;\n logic c, d;\n sub #(.W(3)) u_b (.clk(c), .q(d));\nendmodule\n"; + const GEN: &str = "module three;\n genvar i;\n generate\n for (i = 0; i < 2; i++) begin : lane\n sub u_c (.clk(1'b0), .q());\n end\n endgenerate\nendmodule\n"; + const QUIET: &str = "module quiet;\n wire unrelated;\n assign unrelated = 1'b0;\nendmodule\n"; + + #[test] + fn the_fan_out_answers_a_cross_file_module_rename_exactly_as_the_workspace_does() { + let tree = Tree::new("fanout_module"); + let files = [ + ("sub.sv", MOD), + ("one.sv", ONE), + ("two.sv", TWO), + ("three.sv", GEN), + ("quiet.sv", QUIET), + ]; + let (ws, _) = tree_with(&tree, &files, &["one.sv"]); + let path = tree.path.join("one.sv"); + let at = at(ONE, "sub u_a"); + + let edit = same_answer(&ws, &path, at, "child").expect("renames"); + assert_eq!(edit.file_count(), 4, "the declaration and the three files naming it"); + + // And the narrowing is real: the file that never spells the name is + // not read at all. + let fan = fan_out(&ws, &path, at, "child"); + assert!(!fan.contains(&tree.path.join("quiet.sv")), "{fan:?}"); + assert!(fan.contains(&tree.path.join("three.sv")), "the generate-block site: {fan:?}"); + } + + #[test] + fn the_fan_out_keeps_the_end_label_and_the_declaration_together() { + let tree = Tree::new("fanout_endlabel"); + let (ws, _) = tree_with(&tree, &[("sub.sv", MOD), ("one.sv", ONE)], &["sub.sv"]); + let path = tree.path.join("sub.sv"); + let edit = same_answer(&ws, &path, at(MOD, "sub #"), "child").expect("renames"); + let own = edit.edits_for(&path); + assert_eq!(own.len(), 2, "the header name and the `endmodule : sub` label"); + } + + #[test] + fn the_fan_out_carries_a_port_rename_to_every_connection() { + let tree = Tree::new("fanout_port"); + let files = [("sub.sv", MOD), ("one.sv", ONE), ("two.sv", TWO), ("quiet.sv", QUIET)]; + let (ws, _) = tree_with(&tree, &files, &["sub.sv"]); + let path = tree.path.join("sub.sv"); + let edit = same_answer(&ws, &path, at(MOD, "clk,"), "clock").expect("renames"); + assert_eq!(edit.file_count(), 3, "the module and both files connecting `.clk`"); + } + + #[test] + fn the_fan_out_carries_a_package_member_rename_to_every_importer() { + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + const IMPORTER: &str = + "module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\nendmodule\n"; + const QUALIFIER: &str = + "module qualifier;\n localparam int D = cfg_pkg::DEPTH;\nendmodule\n"; + let tree = Tree::new("fanout_pkg"); + let files = + [("pkg.sv", PKG), ("reader.sv", IMPORTER), ("qual.sv", QUALIFIER), ("quiet.sv", QUIET)]; + let (ws, _) = tree_with(&tree, &files, &["reader.sv"]); + let path = tree.path.join("reader.sv"); + let edit = same_answer(&ws, &path, at(IMPORTER, "DEPTH;"), "SIZE").expect("renames"); + assert_eq!(edit.file_count(), 3, "the package and both files reading it"); + } + + #[test] + fn the_fan_out_sees_a_reference_only_an_unsaved_buffer_has() { + let tree = Tree::new("fanout_unsaved"); + // On disk `two.sv` says nothing about `sub`; the buffer instantiates + // it. The index has never seen the buffer's text. + let files = [("sub.sv", MOD), ("one.sv", ONE), ("two.sv", QUIET)]; + let (mut ws, _) = tree_with(&tree, &files, &["one.sv"]); + let two = tree.path.join("two.sv"); + ws.set_document(path_to_uri(&two).expect("uri"), TWO.to_string()); + assert!( + ws.index().instantiations_of("sub").len() < 2, + "premise: the index has not seen the buffer's instantiation" + ); + + let path = tree.path.join("one.sv"); + let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames"); + assert!(!edit.edits_for(&two).is_empty(), "the unsaved instantiation is renamed too"); + } + + #[test] + fn the_fan_out_refuses_a_name_the_workspace_declares_twice_in_the_same_words() { + let tree = Tree::new("fanout_dup"); + let files = [("sub.sv", MOD), ("copy.sv", MOD), ("one.sv", ONE)]; + let (ws, _) = tree_with(&tree, &files, &["one.sv"]); + let path = tree.path.join("one.sv"); + let refusal = + same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect_err("declared twice"); + assert!(refusal.contains("more than one indexed file"), "{refusal}"); + } + + #[test] + fn the_fan_out_still_refuses_a_rename_that_would_capture_a_name_elsewhere() { + // `three.sv` names `sub`; `taken.sv` declares the module the rename + // wants to become. Renaming `sub` to `taken` makes every `sub` site + // ambiguous — a file the postings for `sub` alone would never name. + const TAKEN: &str = "module taken;\nendmodule\n"; + const USES_TAKEN: &str = "module holder;\n taken u_t ();\nendmodule\n"; + let tree = Tree::new("fanout_capture"); + let files = + [("sub.sv", MOD), ("one.sv", ONE), ("taken.sv", TAKEN), ("uses.sv", USES_TAKEN)]; + let (ws, _) = tree_with(&tree, &files, &["one.sv"]); + let path = tree.path.join("one.sv"); + let refusal = + same_answer(&ws, &path, at(ONE, "sub u_a"), "taken").expect_err("would capture"); + assert!(refusal.contains("would change what"), "{refusal}"); + + let fan = fan_out(&ws, &path, at(ONE, "sub u_a"), "taken"); + assert!(fan.contains(&tree.path.join("uses.sv")), "the new name's own fan-out: {fan:?}"); + } + + /// The two `` `define`` warnings come from files the index's own define + /// tables name, so both survive the narrowing: a macro *called* the name, + /// and a macro whose **body** spells it, each in a file that has nothing + /// else to do with the symbol. + #[test] + fn the_fan_out_keeps_the_define_warnings_of_files_it_would_not_otherwise_read() { + const NAMED: &str = "`define sub 1\nmodule named_holder;\nendmodule\n"; + const BODY: &str = "`define WRAP(x) sub x\nmodule body_holder;\n wire w;\nendmodule\n"; + let tree = Tree::new("fanout_macro"); + let files = [ + ("sub.sv", MOD), + ("one.sv", ONE), + ("named.sv", NAMED), + ("body.svh", BODY), + ("quiet.sv", QUIET), + ]; + let (ws, _) = tree_with(&tree, &files, &["one.sv"]); + let path = tree.path.join("one.sv"); + let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames"); + assert!( + edit.warnings.iter().any(|w| w.contains("is also a macro defined")), + "{:?}", + edit.warnings + ); + assert!( + edit.warnings.iter().any(|w| w.contains("in the body of macro `WRAP`")), + "{:?}", + edit.warnings + ); + let fan = fan_out(&ws, &path, at(ONE, "sub u_a"), "child"); + assert!(fan.contains(&tree.path.join("named.sv")), "the macro's own name: {fan:?}"); + assert!(fan.contains(&tree.path.join("body.svh")), "the macro's body: {fan:?}"); + assert!(!fan.contains(&tree.path.join("quiet.sv")), "and nothing else: {fan:?}"); + } + + #[test] + fn every_file_the_workspace_rename_edits_is_in_the_fan_out() { + // The invariant-1 assertion, made directly rather than through an + // equality: whatever the whole workspace would rewrite, the narrow set + // must contain — otherwise a rename edits fewer files than the truth. + let tree = Tree::new("fanout_covers"); + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + const IMPORTER: &str = "module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\n sub u (.clk(1'b0), .q());\nendmodule\n"; + let files = [ + ("sub.sv", MOD), + ("one.sv", ONE), + ("two.sv", TWO), + ("three.sv", GEN), + ("pkg.sv", PKG), + ("reader.sv", IMPORTER), + ("quiet.sv", QUIET), + ]; + let (ws, _) = tree_with(&tree, &files, &["reader.sv"]); + let path = tree.path.join("reader.sv"); + let everything = ws.sources(); + let text = fs::read_to_string(&path).expect("written"); + for offset in 0..=text.len() as u32 { + let Ok(whole) = vlog_refactor::rename(&everything, &path, offset, "renamed_thing") + else { + continue; + }; + let fan = fan_out(&ws, &path, offset, "renamed_thing"); + for (edited, _) in &whole.edits { + assert!( + fan.contains(edited), + "byte {offset} renames {} and the fan-out does not hold it: {fan:?}", + edited.display() + ); + } + let _ = same_answer(&ws, &path, offset, "renamed_thing"); + } + } + + /// QA, 2026-08-28 attack: an instantiation spelled with an escaped + /// identifier (`` \sub ``) is a *different* name from `sub` to + /// `vlog_semantic` today (a pre-existing simplification, noted in this + /// feature's own 2026-08-24 QA round for a declaration, not an + /// instantiation) — it resolves to nothing, so it is renamed by neither + /// path. The question this pins is narrower: does narrowing the file set + /// change that answer? It must not, since both paths call the identical + /// engine; the risk would be the fan-out *dropping* the file outright + /// while the whole-workspace run still watches it (`\sub` contains the + /// word `sub`, so `contains_word` — and hence `watched_files` — still + /// picks it up in the whole run). `same_answer` checks the observable + /// output only (edits, warnings, or refusal), which is what must agree. + #[test] + fn an_escaped_identifier_instantiation_does_not_break_fan_out_parity() { + const ESCAPED: &str = "module holder;\n \\sub u_weird (.clk(1'b0), .q());\nendmodule\n"; + let tree = Tree::new("fanout_escaped"); + let files = [("sub.sv", MOD), ("one.sv", ONE), ("escaped.sv", ESCAPED)]; + let (ws, _) = tree_with(&tree, &files, &["one.sv"]); + let path = tree.path.join("one.sv"); + let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames"); + assert!( + edit.edits_for(&tree.path.join("escaped.sv")).is_empty(), + "the escaped spelling is a different name to vlog_semantic and must stay untouched" + ); + } + + /// QA, 2026-08-28 attack: a same-spelling but *different* symbol (a + /// module unit named `sub` vs. a port/member also named `sub` in an + /// unrelated module) must not cross-contaminate the fan-out — renaming + /// the unit must not touch the member's own declaration or its file. + #[test] + fn a_same_spelling_different_symbol_kind_is_not_captured_by_the_fan_out() { + const OTHER_MODULE_WITH_A_PORT_NAMED_SUB: &str = + "module other;\n wire sub;\n assign sub = 1'b0;\nendmodule\n"; + let tree = Tree::new("fanout_same_spelling_different_symbol"); + let files = + [("sub.sv", MOD), ("one.sv", ONE), ("other.sv", OTHER_MODULE_WITH_A_PORT_NAMED_SUB)]; + let (ws, _) = tree_with(&tree, &files, &["one.sv"]); + let path = tree.path.join("one.sv"); + let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames"); + assert!( + edit.edits_for(&tree.path.join("other.sv")).is_empty(), + "the unrelated wire named `sub` must not be touched: {:?}", + edit.edits_for(&tree.path.join("other.sv")) + ); + // other.sv may legitimately be *watched* by the whole-word text + // search (it spells "sub"), but it must never be *edited* — checked + // above — nor must its own local wire's meaning change, which + // `same_answer`'s byte-identical edits/warnings assertion already + // confirmed by passing at all. + } + + /// QA, 2026-08-28 attack: the escape hatch (refusal 10 / ambiguous + /// posting) must fire even when the ambiguity is on the **new** name, + /// discovered on the second spelling `fan_out_of` walks, not the first. + /// `Workspace::rename_sources` iterates `[name, new_name]` in that order + /// and bails to `sources()` on the first ambiguous hit — this attacks the + /// case where the *old* name's rung is completely unambiguous and only + /// the second iteration finds the problem, to check the early return + /// doesn't leak a partially-built (too-narrow) `wanted` set instead of + /// truly falling back to the whole scope. + #[test] + fn the_escape_hatch_fires_when_only_the_new_names_posting_is_ambiguous() { + const A: &str = "package taken_pkg;\n parameter int DEPTH = 1;\nendpackage\n"; + const B: &str = "package taken_pkg;\n parameter int DEPTH = 2;\nendpackage\n"; + const READER: &str = + "module reader;\n import taken_pkg::*;\n localparam int D = DEPTH;\nendmodule\n"; + let tree = Tree::new("fanout_ambig_on_new_name"); + let files = + [("sub.sv", MOD), ("one.sv", ONE), ("a.sv", A), ("b.sv", B), ("reader.sv", READER)]; + let (ws, _) = tree_with(&tree, &files, &["one.sv"]); + let path = tree.path.join("one.sv"); + let at = at(ONE, "sub u_a"); + // `sub` (the old name) has an unambiguous, tiny fan-out on its own. + let fan = fan_out(&ws, &path, at, "taken_pkg"); + assert_eq!( + fan.len(), + ws.sources().len(), + "the new name's own ambiguity must still hand back the whole scope: {fan:?}" + ); + same_answer(&ws, &path, at, "taken_pkg").expect_err("ambiguous new name"); + } + + #[test] + fn an_ambiguously_referenced_declaration_falls_back_to_the_whole_scope() { + // Two files declare the *same* package, so `cfg_pkg::DEPTH` names + // either declaration equally. The index records that the declarations + // are ambiguously referenced but not which file does it, so the + // fan-out refuses to narrow at all — which is how the refusal + // survives. + const A: &str = "package cfg_pkg;\n parameter int DEPTH = 1;\nendpackage\n"; + const B: &str = "package cfg_pkg;\n parameter int DEPTH = 2;\nendpackage\n"; + const READER: &str = + "module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\nendmodule\n"; + let tree = Tree::new("fanout_ambig"); + let files = [("a.sv", A), ("b.sv", B), ("reader.sv", READER), ("quiet.sv", QUIET)]; + let (ws, _) = tree_with(&tree, &files, &["a.sv"]); + let path = tree.path.join("a.sv"); + let at = at(A, "DEPTH ="); + let fan = fan_out(&ws, &path, at, "SIZE"); + assert_eq!( + fan.len(), + ws.sources().len(), + "an ambiguous posting hands back the whole scope: {fan:?}" + ); + same_answer(&ws, &path, at, "SIZE").expect_err("ambiguous"); + } + + /// Found by QA on 2026-08-28 as a **lost refusal**, and closed by the + /// sixth rung the lead ruled for the same day; kept as the regression + /// test for it, now asserting parity rather than pinning the divergence. + /// + /// A file whose only mention of the **new** name is a bare use that + /// resolves to nothing today — `import taken_pkg::*` of a package nobody + /// declares yet — declares nothing, references nothing under the *old* + /// name, instantiates nothing and defines no macro, so the first five + /// rungs of the fan-out cannot see it. The rename is exactly what gives + /// that import a meaning, which is what capture rule 12 refuses over, so + /// the narrow path used to answer `Ok` where the whole workspace refused + /// — a materially weaker answer, not a lost warning. + /// `WorkspaceIndex::files_spelling` is the rung that finds it: the + /// per-file records keep every external use under the name it spells, + /// including the ones that resolved to nothing. + #[test] + fn a_dangling_import_of_the_new_name_is_refused_by_both_paths() { + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + const STRAY_IMPORT: &str = "module strayer;\n import taken_pkg::*;\nendmodule\n"; + let tree = Tree::new("fanout_dangling_import"); + let files = [("pkg.sv", PKG), ("stray.sv", STRAY_IMPORT)]; + let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); + let path = tree.path.join("pkg.sv"); + let at = at(PKG, "cfg_pkg;"); + + let fan = fan_out(&ws, &path, at, "taken_pkg"); + assert!( + fan.contains(&tree.path.join("stray.sv")), + "the dangling import's file is in the fan-out through `files_spelling`: {fan:?}" + ); + + let refusal = + same_answer(&ws, &path, at, "taken_pkg").expect_err("would capture the import"); + assert!(refusal.contains("would change what"), "{refusal}"); + assert!(refusal.contains("taken_pkg"), "{refusal}"); + } + + /// The other half of the ruling: the **old** name needs no such rung, and + /// this is the case that would expose it if it did. `stray.sv`'s only tie + /// to the rename is an `import cfg_pkg::*`-shaped use of a name that + /// resolves to nothing — spelled with the name being renamed *away*. + /// A rename only ever removes declarations of the old name, so a lookup + /// that failed before still fails after; the answer cannot move, and both + /// paths agree without `stray.sv` being read. + #[test] + fn a_dangling_use_of_the_old_name_needs_no_rung_of_its_own() { + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + // `absent_pkg` is declared nowhere, and is what the rename renames to + // nothing: the file's only spelling of it stays unresolved throughout. + const STRAY: &str = "module strayer;\n import absent_pkg::*;\nendmodule\n"; + let tree = Tree::new("fanout_dangling_old"); + let files = [("pkg.sv", PKG), ("stray.sv", STRAY)]; + let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); + let path = tree.path.join("pkg.sv"); + + // Rename the *package* to `absent_pkg` — the new-name rung must pull + // `stray.sv` in and both paths must refuse … + let package = at(PKG, "cfg_pkg;"); + same_answer(&ws, &path, package, "absent_pkg").expect_err("would capture the import"); + + // … while a rename whose *old* name is the dangling one has nothing to + // capture: renaming `DEPTH`, which `stray.sv` never spells, leaves it + // out of the set and both paths agree. + let depth = at(PKG, "DEPTH ="); + let edit = same_answer(&ws, &path, depth, "SIZE").expect("renames"); + assert_eq!(edit.file_count(), 1, "only the package's own file"); + let fan = fan_out(&ws, &path, depth, "SIZE"); + assert!(!fan.contains(&tree.path.join("stray.sv")), "{fan:?}"); + } + + // ------------------------------------------------------------------ + // QA, 2026-08-29: re-verification of rung 6 (files_spelling) after the + // lead-authorized fix for the dangling-import residue. + // ------------------------------------------------------------------ + + /// Attack on rung 6's completeness: the new name spelled **only** as the + /// base of an `extends` clause the workspace does not (yet) declare. This + /// goes through `Target::Unit`, not `Target::Package` — a different + /// resolution path than the import case rung 6 was built for — so it is + /// worth checking on its own rather than trusting the same mechanism + /// covers it by analogy. + #[test] + fn a_new_name_spelled_only_as_an_extends_base_is_still_caught_by_rung_6() { + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + const STRAY_EXTENDS: &str = + "class derived extends taken_base;\n function void go();\n endfunction\nendclass\n"; + let tree = Tree::new("fanout_extends_base"); + let files = [("pkg.sv", PKG), ("stray.sv", STRAY_EXTENDS)]; + let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); + let path = tree.path.join("pkg.sv"); + let at = at(PKG, "cfg_pkg;"); + + let fan = fan_out(&ws, &path, at, "taken_base"); + assert!( + fan.contains(&tree.path.join("stray.sv")), + "the extends base is a Target::Unit miss, always non-empty paths: {fan:?}" + ); + let refusal = + same_answer(&ws, &path, at, "taken_base").expect_err("would give the base a meaning"); + assert!(refusal.contains("would change what"), "{refusal}"); + } + + /// Attack on rung 6's completeness: a bare, unqualified reference to the + /// new name written inside a class that `extends` an **existing, + /// unrelated** base, with no import in scope — the one shape that + /// produces `Resolution::InheritedCandidate` with genuinely **empty** + /// paths (`miss()`'s branch when `nearest_extends` finds a base but no + /// import supplied anything), which `files_spelling` cannot see (it reads + /// only facts with non-empty paths). The argument this pins: such a + /// reference is resolved *purely* from the file's own unedited text and + /// never depends on the workspace (`resolve_external` never even tries + /// `follow_paths` against an empty list), so it cannot change meaning + /// under any rename — excluding the file costs nothing, on this rung or + /// the whole-workspace path alike. + #[test] + fn an_unqualified_use_inside_an_extending_class_with_empty_paths_needs_no_rung() { + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + const EXISTING_BASE: &str = "class existing_base;\nendclass\n"; + // No import anywhere in `stray.sv`, so the lexical miss on + // `taken_member` inside `derived` (which extends `existing_base`) + // collects an empty `external` list and becomes an `InheritedCandidate` + // with `paths: []` — recorded nowhere, per `facts_from_analysis`. + const STRAY: &str = "class derived extends existing_base;\n function void go();\n taken_member = 1;\n endfunction\nendclass\n"; + let tree = Tree::new("fanout_inherited_empty_paths"); + let files = [("pkg.sv", PKG), ("base.sv", EXISTING_BASE), ("stray.sv", STRAY)]; + let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); + let path = tree.path.join("pkg.sv"); + let at = at(PKG, "cfg_pkg;"); + + let fan = fan_out(&ws, &path, at, "taken_member"); + assert!( + !fan.contains(&tree.path.join("stray.sv")), + "an empty-paths InheritedCandidate is invisible to files_spelling by design: {fan:?}" + ); + // Parity must still hold: excluding the file must not change the + // answer, because the reference inside it can never resolve + // differently regardless of what `cfg_pkg` becomes. + same_answer(&ws, &path, at, "taken_member").expect("renames, no capture possible"); + } + + /// Attack on rung 6's soundness: a **local-only** symbol in a third file + /// that happens to share the new name's spelling must not trigger a + /// bogus refusal. `files_spelling` explicitly excludes `ReferenceFact::Local` + /// facts (a local declaration/use resolves inside its own file and the + /// workspace was never consulted), so the file should not even be pulled + /// in — and if it were, the rename must still succeed, since no capture is + /// possible against a symbol nothing outside that file can see. + #[test] + fn a_local_only_symbol_sharing_the_new_names_spelling_is_not_a_bogus_refusal() { + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + const LOCAL_ONLY: &str = + "module unrelated;\n wire taken_local;\n assign taken_local = 1'b0;\nendmodule\n"; + let tree = Tree::new("fanout_local_only"); + let files = [("pkg.sv", PKG), ("local.sv", LOCAL_ONLY)]; + let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); + let path = tree.path.join("pkg.sv"); + let at = at(PKG, "cfg_pkg;"); + + let fan = fan_out(&ws, &path, at, "taken_local"); + assert!( + !fan.contains(&tree.path.join("local.sv")), + "a purely local declaration/use is not an external fact: {fan:?}" + ); + let edit = + same_answer(&ws, &path, at, "taken_local").expect("renames, no capture possible"); + assert!(edit.edits_for(&tree.path.join("local.sv")).is_empty()); + } + + /// Attack on the old-name exemption: a shadowing/"unmasking" hunt. Two + /// packages, `p_pkg` and `q_pkg`, both export a member spelled the same + /// (`shared_name`); a third file imports both, `p_pkg` first, so + /// "first-written import wins" resolves `shared_name` to `p_pkg`'s + /// declaration. Renaming *away* `p_pkg::shared_name` removes the winning + /// candidate, so the same reference should fall through to `q_pkg`'s + /// pre-existing, completely unrelated declaration — a meaning change the + /// whole-workspace verifier must refuse over (rule 12, in the direction + /// "an existing use is captured by nothing new — it silently rebinds to + /// another *existing* declaration"). The old-name argument says this + /// cannot be missed because rung 1 walks *every* declaration named + /// `shared_name` (both `p_pkg`'s and `q_pkg`'s, not just the target's), + /// so the importer is pulled in via `references_to` of `p_pkg`'s + /// declaration regardless. + #[test] + fn removing_the_old_names_winning_declaration_does_not_escape_the_fan_out() { + const P: &str = "package p_pkg;\n parameter int shared_name = 1;\nendpackage\n"; + const Q: &str = "package q_pkg;\n parameter int shared_name = 2;\nendpackage\n"; + const USER: &str = "module user;\n import p_pkg::*;\n import q_pkg::*;\n localparam int X = shared_name;\nendmodule\n"; + let tree = Tree::new("fanout_shadow_unmask"); + let files = [("p.sv", P), ("q.sv", Q), ("user.sv", USER)]; + let (ws, _) = tree_with(&tree, &files, &["p.sv"]); + let path = tree.path.join("p.sv"); + let at = at(P, "shared_name ="); + + let fan = fan_out(&ws, &path, at, "renamed_thing"); + assert!( + fan.contains(&tree.path.join("user.sv")), + "the importer is posted against p_pkg's declaration today: {fan:?}" + ); + assert!( + fan.contains(&tree.path.join("q.sv")), + "rung 1 walks every declaration named `shared_name`, not only the target's: {fan:?}" + ); + // Whichever way the whole-workspace path answers this (refuse, since + // `user.sv`'s meaning silently moves from p_pkg to q_pkg; or edit, + // if some other rule intervenes first), the subset must answer + // identically — that is the property under attack, not a specific + // outcome. + // The hunt comes up empty, and reading why is the point: `user.sv`'s + // `shared_name` currently resolves to `p_pkg`'s declaration — the + // rename target itself — so it is not a bystander a removal could + // silently unmask, it is an *edit site*: the rename rewrites it to + // `renamed_thing` along with the declaration, so the text never says + // `shared_name` again for `follow_paths` to re-resolve against + // `q_pkg`. A reference can only be affected by a name's removal by + // spelling that exact name, and by the Lemma any such reference + // either resolves to the target (edited away, as here) or to some + // *other* declaration of the same name (already covered by rung 1/2's + // sweep over every declarer, not only the target's) — there is no + // third case for the old name to fall into. + let edit = same_answer(&ws, &path, at, "renamed_thing").expect("renames"); + assert_eq!(edit.file_count(), 2, "the declaration and the importer's edited reference"); + assert!( + edit.edits_for(&tree.path.join("q.sv")).is_empty(), + "q_pkg's own unrelated declaration is never touched" + ); + } + #[test] fn an_open_buffer_beats_disk_when_the_rename_is_computed() { let tree = Tree::new("buffer"); diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index 3e34bb1..f54000a 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -15,7 +15,7 @@ use vlog_parser::defines::{collect_defines, DefineTable}; use vlog_parser::token::Token; use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic}; use vlog_semantic::{ - analyze, index_order, resolve_external, ExternalResolutions, FileFacts, Semantics, + analyze, index_order, resolve_external, Def, ExternalResolutions, FileFacts, FileId, Semantics, WorkspaceIndex, }; @@ -1457,6 +1457,202 @@ impl Workspace { .collect() } + /// The in-scope files a rename of `name` — to `new_name`, when the request + /// carries one — can read, write or refuse over: [`Workspace::sources`] + /// narrowed to what the index already knows about those two spellings. + /// + /// A `textDocument/rename` cost 3.6–8.7 s on OpenTitan and a + /// `prepareRename` 2.5–3.0 s, almost all of it re-reading, re-parsing and + /// re-indexing 3 976 files to find the handful that spell one name. The + /// index holds every declaration of a name and every use it resolved, so + /// the engine can be handed those files and nothing else. **Why the + /// smaller set gives the same answer is argued in full in + /// `docs/features/refactor-rename/README.md`**; the rungs are: + /// + /// * **the file the request names**, whatever else it is; + /// * **every open buffer**, whose unsaved text the index has not seen — + /// the one place this set deliberately does not trust the index; + /// * per spelling `N` in `{name, new_name}`: + /// * **every file declaring `N`** — as a unit or as a member of one + /// ([`WorkspaceIndex::workspace_symbols`], filtered to the exact + /// name). This is the rung the whole equality argument turns on: + /// `follow_paths` only ever looks a reference's *own* name up, so a + /// set holding every declarer of `N` resolves every reference spelling + /// `N` exactly as the whole workspace does; + /// * **every file with a use the index resolved to one of them** + /// ([`WorkspaceIndex::references_to`]) — every file a rename can edit, + /// and every file whose meaning the verifier could see move; + /// * **every file instantiating `N`** + /// ([`WorkspaceIndex::instantiations_of`]), which records a site whose + /// reference resolved to nothing and therefore has no posting; + /// * **every file whose `` `define`` table names `N` or spells it in a + /// macro body**, walked over the tables the index already holds, for + /// the two `` `define`` warnings; + /// * **the units that export `N` as a member**, and every file + /// declaring, referring to or instantiating one of those — how a third + /// file's `.N(...)` connection or `u::N` is reached. + /// * and, for the **new** name only, **every file that spells it in a use + /// this workspace had to look outside that file to answer, including + /// the uses it could not answer at all** + /// ([`WorkspaceIndex::files_spelling`]). + /// + /// **Why that last rung is the new name's alone.** It exists because a + /// rename can give a name that meant *nothing* a meaning: `import + /// taken_pkg::*` in a file with no other tie to the rename resolves to + /// nothing today and to the renamed package tomorrow, which the + /// whole-workspace verifier refuses over and the first five rungs cannot + /// see. The old name has no such case, because a rename only ever + /// **removes** declarations of it: a use of the old name that resolves is + /// in that declaration's postings (rung 2, which walks *every* declaration + /// of the name, not only the target's), and one that resolves to nothing + /// still resolves to nothing afterwards — a lookup cannot start + /// succeeding because a candidate was taken away. So the old name's uses + /// are either already in the set or provably unmoved, and scanning for + /// them would buy nothing. + /// + /// One escape hatch, and it is the honest one: when the index says a + /// declaration of `N` is named by an **ambiguous** use + /// ([`WorkspaceIndex::references_are_ambiguous`]), the file holding that + /// use is in no posting table, and the whole-workspace rename refuses + /// because of it. Rather than lose that refusal, this hands back + /// `sources()` and the slow path answers. + pub fn rename_sources( + &self, + file: &Path, + name: &str, + new_name: Option<&str>, + ) -> Vec<(PathBuf, String)> { + let mut wanted: BTreeSet = BTreeSet::new(); + wanted.insert(file.to_path_buf()); + for spelling in [Some(name), new_name].into_iter().flatten() { + if !self.fan_out_of(spelling, &mut wanted) { + return self.sources(); + } + } + // The sixth rung, and the **new** name's alone. See the doc comment + // above for why the old name does not need it. + if let Some(new_name) = new_name { + self.want_spellers(new_name, &mut wanted); + } + wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone())); + wanted + .into_iter() + .filter_map(|path| { + let text = self.current_text(&path)?; + Some((path, text)) + }) + .collect() + } + + /// Add one spelling's fan-out to `wanted`. `false` means the index cannot + /// bound it — see [`Workspace::rename_sources`]'s escape hatch. + fn fan_out_of(&self, name: &str, wanted: &mut BTreeSet) -> bool { + // Every declaration of the name, wherever it is written. `units` alone + // would miss a port, a parameter or a package member, and those are + // exactly the declarations a `.port` connection or a `pkg::x` reaches + // across files for. + let mut containers: BTreeSet<&str> = BTreeSet::new(); + for symbol in self.index.workspace_symbols(name) { + if symbol.name != name { + continue; + } + if self.index.references_are_ambiguous(symbol.def) { + return false; + } + containers.extend(symbol.container); + self.want_declaration(symbol.def, wanted); + } + self.want_sites(name, wanted); + self.want_macro_text(name, wanted); + for unit in containers { + for def in self.index.units(unit) { + self.want_declaration(def, wanted); + } + self.want_sites(unit, wanted); + } + true + } + + /// One declaration's own file, and every file the index recorded a use of + /// it in. + fn want_declaration(&self, def: &Def, wanted: &mut BTreeSet) { + wanted.extend(self.index.path(def.file).map(Path::to_path_buf)); + for site in self.index.references_to(def) { + wanted.extend(self.index.path(site.file).map(Path::to_path_buf)); + } + } + + /// Every file that instantiates a name — the census the reference postings + /// cannot speak for, because an instantiation of something the workspace + /// does not declare resolves to nothing and is posted nowhere. + fn want_sites(&self, name: &str, wanted: &mut BTreeSet) { + for edge in self.index.instantiations_of(name) { + wanted.extend(self.index.path(edge.file).map(Path::to_path_buf)); + } + } + + /// Every file that spells a name in a use the index had to look outside + /// that file to answer, **including the uses it could not answer at all** + /// ([`WorkspaceIndex::files_spelling`]). + /// + /// The rung that closes the rename's one lost refusal (QA, 2026-08-28). + /// A file whose only tie to the new name is `import new_name::*` of a + /// package nothing declares yet holds no declaration, no posting, no + /// instantiation edge and no macro entry — and the rename is exactly what + /// gives that import a meaning, which the whole-workspace verifier refuses + /// over. Only the postings' *keys* miss it; the per-file records keep every + /// external use by the name it spells, so this reads it back. + fn want_spellers(&self, name: &str, wanted: &mut BTreeSet) { + for file in self.index.files_spelling(name) { + wanted.extend(self.index.path(file).map(Path::to_path_buf)); + } + } + + /// Every file whose `` `define`` table names the name or spells it in a + /// macro **body** — the two warnings `Scope::define_sites` produces. + /// + /// The index holds every file's `DefineTable` already, so this is a walk + /// over tables in memory: no file is read and nothing is parsed. The + /// question is asked with `vlog_refactor::contains_word`, which is the + /// function `define_sites` itself decides with, so the fan-out and the + /// warning cannot disagree about which files carry one. + fn want_macro_text(&self, name: &str, wanted: &mut BTreeSet) { + for id in 0..self.index.files().len() { + let file = FileId(id as u32); + let Some(defines) = self.index.defines(file) else { continue }; + let touched = defines.entries().iter().any(|define| { + define.name == name || vlog_refactor::contains_word(&define.body, name) + }); + if touched { + wanted.extend(self.index.path(file).map(Path::to_path_buf)); + } + } + } + + /// The in-scope files a `workspace/willRenameFiles` can rewrite: the ones + /// the include graph recorded a resolving `` `include`` in, plus every open + /// buffer. + /// + /// `will_rename` reads a file only to scan its `` `include``s and asks the + /// graph where each one lands; a file whose includes all resolve to nothing + /// — or that has none — contributes neither an edit nor a warning, and the + /// graph's edge table is exactly the set of files that have at least one + /// resolving include. So reading the rest was reading the whole workspace + /// to answer "nothing" 3 900 times. Open buffers are added whatever the + /// graph holds: the graph is rebuilt on save, so an `` `include`` typed and + /// not yet saved is in the buffer and not in the edges. + pub fn include_sources(&self) -> Vec<(PathBuf, String)> { + let mut wanted: BTreeSet = self.includes.includers().cloned().collect(); + wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone())); + wanted + .into_iter() + .filter_map(|path| { + let text = self.current_text(&path)?; + Some((path, text)) + }) + .collect() + } + /// Read every in-scope file, with open buffers overriding disk. /// /// This is where `lucisv.index.maxFileSize` applies, and it applies to the diff --git a/crates/vlog_refactor/src/lib.rs b/crates/vlog_refactor/src/lib.rs index 6e26f76..bc1b49f 100644 --- a/crates/vlog_refactor/src/lib.rs +++ b/crates/vlog_refactor/src/lib.rs @@ -43,7 +43,9 @@ pub use ports::{ add_port, enclosing_module, may_have_port_action, port_action_modules, port_actions, propagate_ports, remove_port, ModuleRef, PortAction, }; -pub use rename::{prepare_rename, rename, RenameTarget}; +pub use rename::{ + contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget, +}; use std::path::PathBuf; diff --git a/crates/vlog_refactor/src/rename.rs b/crates/vlog_refactor/src/rename.rs index 52121f2..efbc59f 100644 --- a/crates/vlog_refactor/src/rename.rs +++ b/crates/vlog_refactor/src/rename.rs @@ -15,7 +15,7 @@ use vlog_parser::token::{is_keyword, TokenKind}; use vlog_parser::{parse_source_tolerant, tokenize, LineIndex}; use vlog_semantic::{ analyze, resolve_external, Def, ExternalResolutions, ExternalTarget, FileId, ReferenceId, - Resolution, Semantics, SymbolId, WorkspaceIndex, + Resolution, Semantics, Symbol, SymbolId, WorkspaceIndex, }; use crate::{check, RefactorEdit, TextEdit}; @@ -44,6 +44,93 @@ pub fn prepare_rename( Ok(RenameTarget { range: target.cursor, name: target.name }) } +/// [`prepare_rename`] answered from one buffer's finished analysis and the +/// workspace index, reading no file at all. +/// +/// `textDocument/prepareRename` fires the instant the rename key is pressed, +/// and its whole answer — the identifier's range and its placeholder — is in +/// the buffer already. Answering it through [`prepare_rename`] meant reading, +/// parsing and indexing every in-scope file first: 2.5–3.0 s on OpenTitan, on +/// a keypress that has committed to nothing, with a single-threaded server +/// answering nothing else meanwhile. +/// +/// Every refusal [`prepare_rename`] can reach without the *declaring file's* +/// own text is reached here too, in the same words. The ones that need that +/// text are deferred to [`rename`], which reads it — LSP allows an optimistic +/// `prepareRename` whose rename then refuses, and never the other way round. +/// The refusal-by-refusal table is in `docs/features/refactor-rename/README.md`. +pub fn prepare_rename_here( + semantics: &Semantics, + external: &ExternalResolutions, + index: &WorkspaceIndex, + offset: u32, +) -> Result { + let found = + semantics.reference_id_at(offset).and_then(|id| Some((id, semantics.reference(id)?))); + let Some((id, reference)) = found else { + // The cursor is on a declaration, or on nothing at all. + let here = semantics.symbol_at(offset).and_then(|symbol| semantics.symbol(symbol)); + let Some(declaration) = here else { return Err(NOTHING_HERE.to_string()) }; + renameable_here(semantics, index, declaration)?; + return Ok(RenameTarget { range: declaration.name_span, name: declaration.name.clone() }); + }; + let cursor = reference.name_span; + match &reference.resolution { + Resolution::Resolved(symbol) => { + let Some(declaration) = semantics.symbol(*symbol) else { + return Err(NOTHING_HERE.to_string()); + }; + renameable_here(semantics, index, declaration)?; + Ok(RenameTarget { range: cursor, name: declaration.name.clone() }) + } + Resolution::NotFound => Err(unresolved(&reference.name)), + Resolution::InheritedCandidate { base, .. } => Err(from_base(&reference.name, base)), + // The overlay is `resolve_external` against this very index, which is + // the same call `Scope::declaration_across_files` makes — so which + // declaration the use names, and whether several do, is settled here. + // What is *not* settled is anything about that declaration's own file. + Resolution::ExternalCandidate { .. } => match external.get(id) { + Some(ExternalTarget::Resolved(_)) => { + Ok(RenameTarget { range: cursor, name: reference.name.clone() }) + } + Some(ExternalTarget::Ambiguous(_)) => Err(ambiguous(&reference.name)), + _ => Err(declared_outside(&reference.name)), + }, + } +} + +/// The two refusals [`Scope::declaration`] applies to a declaration written in +/// the file the request named, asked of that buffer and the index. +fn renameable_here( + semantics: &Semantics, + index: &WorkspaceIndex, + declaration: &Symbol, +) -> Result<(), String> { + if declaration.name_span.is_empty() { + return Err(unspelled(&declaration.name)); + } + if declaration.scope == semantics.file_scope() && index.units(&declaration.name).len() > 1 { + return Err(ambiguous(&declaration.name)); + } + Ok(()) +} + +/// The identifier a rename at `offset` would act on, read from one buffer's +/// analysis alone: the name, with no opinion on whether it may be renamed. +/// +/// What the server needs to ask the index for the rename's fan-out. Every +/// refusal stays with [`rename`], which is the call that sees the files — a +/// second opinion here could only disagree with it. +pub fn rename_name_at(semantics: &Semantics, offset: u32) -> Option { + match semantics.reference_id_at(offset).and_then(|id| semantics.reference(id)) { + Some(reference) => Some(reference.name.clone()), + None => semantics + .symbol_at(offset) + .and_then(|symbol| semantics.symbol(symbol)) + .map(|declaration| declaration.name.clone()), + } +} + /// Rename the symbol at `offset` in `file` to `new_name`, across every file in /// `files`. /// @@ -230,12 +317,10 @@ impl<'a> Scope<'a> { let (name, cursor) = (reference.name.clone(), reference.name_span); match &reference.resolution { Resolution::Resolved(symbol) => Found::Here(*symbol, cursor), - Resolution::NotFound => return Err(format!( - "`{name}` is not resolved to any declaration, so lucisv cannot tell what renaming it would mean." - )), - Resolution::InheritedCandidate { base, .. } => return Err(format!( - "`{name}` could only come from the base class `{base}`, which lucisv does not resolve; renaming it would be a guess." - )), + Resolution::NotFound => return Err(unresolved(&name)), + Resolution::InheritedCandidate { base, .. } => { + return Err(from_base(&name, base)) + } Resolution::ExternalCandidate { .. } => { Found::Elsewhere(name, cursor, analysis.external.get(id).cloned()) } @@ -282,9 +367,7 @@ impl<'a> Scope<'a> { ) }; if name_span.is_empty() { - return Err(format!( - "lucisv cannot find where `{name}` is spelled in its declaration, so it will not edit it." - )); + return Err(unspelled(&name)); } if at_file_scope && self.index.units(&name).len() > 1 { return Err(ambiguous(&name)); @@ -302,11 +385,7 @@ impl<'a> Scope<'a> { let def = match target { Some(ExternalTarget::Resolved(def)) => def, Some(ExternalTarget::Ambiguous(_)) => return Err(ambiguous(name)), - _ => { - return Err(format!( - "`{name}` is declared outside the files lucisv indexes, so a rename here would only be half a rename." - )) - } + _ => return Err(declared_outside(name)), }; let Some(file) = self.index.path(def.file).and_then(|p| self.index_of(p)) else { return Err(format!("`{name}`'s declaring file is not in scope.")); @@ -631,12 +710,41 @@ pub(crate) struct ArgumentSite { const NOTHING_HERE: &str = "there is no symbol to rename at this position."; +// The refusal sentences, each written once. Two callers reach four of them +// now: the whole-workspace `Scope::locate` and the buffer-and-index +// `prepare_rename_here`, which must refuse in exactly the same words or the +// user gets two different explanations for one situation. + fn ambiguous(name: &str) -> String { format!( "`{name}` is declared in more than one indexed file; lucisv will not guess which declaration this rename means." ) } +fn unresolved(name: &str) -> String { + format!( + "`{name}` is not resolved to any declaration, so lucisv cannot tell what renaming it would mean." + ) +} + +fn from_base(name: &str, base: &str) -> String { + format!( + "`{name}` could only come from the base class `{base}`, which lucisv does not resolve; renaming it would be a guess." + ) +} + +fn declared_outside(name: &str) -> String { + format!( + "`{name}` is declared outside the files lucisv indexes, so a rename here would only be half a rename." + ) +} + +fn unspelled(name: &str) -> String { + format!( + "lucisv cannot find where `{name}` is spelled in its declaration, so it will not edit it." + ) +} + /// Why an identifier spelling the name is not a reference lucisv can edit, /// read off its neighbours in the token stream. Naming the actual construct /// is the difference between a warning the user can act on and one they have @@ -679,7 +787,12 @@ pub(crate) fn display(path: &Path) -> String { /// True when `needle` occurs in `haystack` as a whole identifier — the test /// macro text and the verification pass's file filter get, where there is no /// token stream to consult (or where the token is opaque). -pub(crate) fn contains_word(haystack: &str, needle: &str) -> bool { +/// +/// Public because the server asks the same question of a `` `define`` body it +/// reads out of the index, to put that macro's file in a rename's fan-out: +/// [`Scope::define_sites`] decides with this function, so the fan-out must +/// decide with it too or the two disagree about which files carry a warning. +pub fn contains_word(haystack: &str, needle: &str) -> bool { if needle.is_empty() { return false; } @@ -719,6 +832,185 @@ mod tests { assert!(check_new_name("a ").is_err(), "trailing space"); } + /// A `(path, text)` list from `(name, text)` pairs, the shape both entry + /// points take. + fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> { + files.iter().map(|(name, text)| (PathBuf::from(name), (*text).to_string())).collect() + } + + /// [`prepare_rename_here`] and [`prepare_rename`] asked the same question + /// at **every byte** of one file, with the parity contract asserted at + /// each: a refusal is never invented and never reworded, and an answer is + /// never a different answer. The one asymmetry the contract allows is the + /// deferral — the cheap path saying yes where the whole-workspace path + /// refuses for a reason only the declaring file's own text carries. + /// + /// Returns how many offsets were deferrals, so a test can assert it found + /// the case it was built to find. + fn parity_at_every_offset(files: &[(&str, &str)], file: &str) -> usize { + let sources = workspace(files); + let path = PathBuf::from(file); + let text = sources + .iter() + .find(|(p, _)| *p == path) + .map(|(_, text)| text.clone()) + .expect("the file is in the workspace"); + + let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str()))); + let semantics = analyze(&parse_source_tolerant(&text).0, &text); + let external = resolve_external(&semantics, &index); + + let mut deferred = 0usize; + for offset in 0..=text.len() as u32 { + let whole = prepare_rename(&sources, &path, offset); + let here = prepare_rename_here(&semantics, &external, &index, offset); + match (&whole, &here) { + (Ok(whole), Ok(here)) => { + assert_eq!(whole, here, "at byte {offset} of {file}"); + } + (Err(whole), Err(here)) => { + assert_eq!(whole, here, "refusal reworded at byte {offset} of {file}"); + } + // Allowed, and only in this direction: the buffer said yes, + // the workspace refused for something only the declaring + // file's own analysis knows. `rename` still delivers it. + (Err(_), Ok(_)) => deferred += 1, + (Ok(whole), Err(here)) => panic!( + "a refusal was invented at byte {offset} of {file}: the workspace answered {whole:?}, the buffer refused with {here:?}" + ), + } + } + deferred + } + + const SUB: &str = "module sub #(parameter int W = 1) (input logic clk, output logic q);\n wire local_net;\n assign q = clk & local_net;\nendmodule : sub\n"; + const TOP: &str = "module top;\n logic c, d;\n sub #(.W(2)) u_sub (.clk(c), .q(d));\n sub u_two (.clk(c), .q(d));\nendmodule\n"; + const PKG: &str = + "package cfg_pkg;\n parameter int DEPTH = 4;\n typedef logic [1:0] mode_t;\nendpackage\n"; + const USER: &str = "module user;\n import cfg_pkg::*;\n cfg_pkg::mode_t m;\n localparam int D = cfg_pkg::DEPTH;\nendmodule\n"; + + #[test] + fn the_buffer_answers_a_prepare_exactly_as_the_workspace_does() { + let files = [("sub.sv", SUB), ("top.sv", TOP)]; + parity_at_every_offset(&files, "top.sv"); + parity_at_every_offset(&files, "sub.sv"); + } + + #[test] + fn a_prepare_over_packages_and_qualified_names_keeps_parity() { + let files = [("pkg.sv", PKG), ("user.sv", USER)]; + parity_at_every_offset(&files, "user.sv"); + parity_at_every_offset(&files, "pkg.sv"); + } + + #[test] + fn a_prepare_keeps_parity_where_the_workspace_declares_a_name_twice() { + // Two modules called `sub`, so every route to that declaration must + // refuse — from the use in `top.sv`, and from either declaration. + let files = + [("a.sv", SUB), ("b.sv", SUB), ("top.sv", TOP), ("pkg.sv", PKG), ("user.sv", USER)]; + parity_at_every_offset(&files, "top.sv"); + parity_at_every_offset(&files, "a.sv"); + + let sources = workspace(&files); + let path = PathBuf::from("top.sv"); + let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str()))); + let semantics = analyze(&parse_source_tolerant(TOP).0, TOP); + let external = resolve_external(&semantics, &index); + let at = TOP.find("sub #").expect("the instantiation") as u32; + let refusal = + prepare_rename_here(&semantics, &external, &index, at).expect_err("declared twice"); + assert_eq!(refusal, ambiguous("sub"), "the index-shaped refusal, in its own words"); + assert_eq!(refusal, prepare_rename(&sources, &path, at).expect_err("declared twice")); + } + + #[test] + fn a_prepare_keeps_parity_where_nothing_resolves() { + // `missing` is instantiated and declared nowhere; `base_t` comes from + // a base class this workspace does not hold. + const STRAY: &str = "class kid extends absent_base;\n function void go();\n inherited_thing = 1;\n endfunction\nendclass\nmodule holder;\n missing u_missing (.a(b));\nendmodule\n"; + parity_at_every_offset(&[("stray.sv", STRAY), ("sub.sv", SUB)], "stray.sv"); + } + + #[test] + fn a_prepare_keeps_parity_through_generate_blocks_and_macros() { + const GEN: &str = "`define BUMP(x) x + 1\n`define WIDTH 8\nmodule gen_holder;\n genvar i;\n generate\n for (i = 0; i < 2; i++) begin : lane\n sub u_lane (.clk(1'b0), .q());\n end\n endgenerate\n wire [`WIDTH-1:0] w;\n assign w = `BUMP(sub);\nendmodule\n"; + parity_at_every_offset(&[("gen.sv", GEN), ("sub.sv", SUB)], "gen.sv"); + } + + #[test] + fn a_prepare_on_an_unparseable_buffer_keeps_parity() { + const BROKEN: &str = + "module broken (input logic clk;\n wire a\n assign a = clk\nendmodule\n"; + parity_at_every_offset(&[("broken.sv", BROKEN), ("sub.sv", SUB)], "broken.sv"); + } + + // ------------------------------------------------------------------ + // QA, 2026-08-28: prepare parity fuzz beyond the dev's six buffers + // ------------------------------------------------------------------ + // + // Same contract, hostile shapes the dev's suite didn't try: a valid head + // followed by garbage (as opposed to garbage throughout), CRLF line + // endings (byte offsets a naive line-based tool would get wrong), and + // multi-byte UTF-8 text sitting before the identifiers being probed. + + #[test] + fn a_prepare_keeps_parity_with_a_valid_head_and_an_unparseable_tail() { + const HEAD_THEN_GARBAGE: &str = "module ok_head;\n wire a;\n assign a = 1'b0;\nendmodule\n\n)}]224$@#(garbage tail not even lexable as verilog{{{\n"; + parity_at_every_offset(&[("tail.sv", HEAD_THEN_GARBAGE), ("sub.sv", SUB)], "tail.sv"); + } + + #[test] + fn a_prepare_keeps_parity_over_crlf_line_endings() { + const CRLF: &str = "module crlf_mod;\r\n wire local_net;\r\n sub u_inst (.clk(1'b0), .q());\r\n assign local_net = 1'b0;\r\nendmodule\r\n"; + parity_at_every_offset(&[("crlf.sv", CRLF), ("sub.sv", SUB)], "crlf.sv"); + } + + #[test] + fn a_prepare_keeps_parity_with_multi_byte_text_before_the_identifiers() { + const MULTI_BYTE: &str = "// \u{00e9}\u{00e9} \u{1f389} a comment with accents and an emoji before anything else\nmodule multi_byte_mod;\n // \u{4e2d}\u{6587}\u{6ce8}\u{91ca} more non-ascii, mid-file\n wire local_net;\n sub u_inst (.clk(1'b0), .q());\n assign local_net = 1'b0;\nendmodule\n"; + parity_at_every_offset(&[("multibyte.sv", MULTI_BYTE), ("sub.sv", SUB)], "multibyte.sv"); + } + + #[test] + fn a_prepare_keeps_parity_over_a_macro_heavy_buffer() { + const MACRO_HEAVY: &str = "`define WIDTH 8\n`define BUMP(x) x = x + 1\n`ifdef NEVER_DEFINED\n `define shadow_sub sub\n`else\n module macro_heavy;\n wire [`WIDTH-1:0] w;\n sub u_real (.clk(1'b0), .q());\n initial `BUMP(w);\n endmodule\n`endif\n"; + parity_at_every_offset(&[("macro.sv", MACRO_HEAVY), ("sub.sv", SUB)], "macro.sv"); + } + + #[test] + fn the_cheap_prepare_reads_nothing_but_the_buffer_and_the_index() { + // The declaring file is *not* in the index, so nothing about it can be + // consulted — and the answer is still the refusal that says so. + let sources = workspace(&[("top.sv", TOP)]); + let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str()))); + let semantics = analyze(&parse_source_tolerant(TOP).0, TOP); + let external = resolve_external(&semantics, &index); + let at = TOP.find("sub #").expect("the instantiation") as u32; + assert_eq!( + prepare_rename_here(&semantics, &external, &index, at).expect_err("not indexed"), + declared_outside("sub") + ); + } + + #[test] + fn the_name_a_fan_out_is_built_from_is_the_name_the_engine_acts_on() { + let files = [("sub.sv", SUB), ("top.sv", TOP), ("pkg.sv", PKG), ("user.sv", USER)]; + let sources = workspace(&files); + for (path, text) in &sources { + let semantics = analyze(&parse_source_tolerant(text).0, text); + for offset in 0..=text.len() as u32 { + let Ok(target) = prepare_rename(&sources, path, offset) else { continue }; + assert_eq!( + rename_name_at(&semantics, offset).as_deref(), + Some(target.name.as_str()), + "at byte {offset} of {}", + path.display() + ); + } + } + } + #[test] fn whole_word_search_ignores_substrings() { assert!(contains_word("a + WIDTH - 1", "WIDTH")); diff --git a/crates/vlog_semantic/src/workspace.rs b/crates/vlog_semantic/src/workspace.rs index fb729c1..de4d916 100644 --- a/crates/vlog_semantic/src/workspace.rs +++ b/crates/vlog_semantic/src/workspace.rs @@ -333,6 +333,37 @@ impl WorkspaceIndex { self.ambiguous_references.contains(&DefinitionKey::of(def)) } + /// Every file holding a use spelled `name` that this index had to look + /// **outside that file** to answer — whether or not it found anything. + /// + /// [`WorkspaceIndex::references_to`] is keyed by the declaration a use + /// landed on, so a use that landed on nothing is in no posting at all. + /// That is the right shape for "who refers to this declaration" and the + /// wrong shape for "which files would notice if this name suddenly + /// started meaning something" — the question a rename has to ask about + /// the name it is renaming *to*, because an `import p::*` of a package + /// that does not exist yet changes meaning the moment a package `p` + /// appears. Answered from the per-file records, which keep every external + /// reference by its spelled name; a resolved one is here too, since a use + /// that already means something can equally start meaning something else. + /// + /// A linear walk over the records, in [`FileId`] order and deduplicated: + /// no source is read and nothing is parsed. See + /// `docs/features/refactor-rename/README.md` for the rename's use of it + /// and the measurement. + pub fn files_spelling(&self, name: &str) -> impl Iterator + '_ { + let name = name.to_string(); + self.facts.iter().enumerate().filter_map(move |(id, facts)| { + let spelled = facts.references.iter().any(|reference| match reference { + ReferenceFact::External { name: spelled, .. } => *spelled == name, + // A local fact resolved inside its own file, so that file + // declares the name and every caller already has it. + ReferenceFact::Local { .. } => false, + }); + spelled.then_some(FileId(id as u32)) + }) + } + /// Every indexed name containing `query`, case-insensitively — LSP's /// `workspace/symbol`. An empty query matches everything; the result is /// sorted by name and is not truncated, so a caller with a result limit diff --git a/crates/vlog_semantic/tests/workspace.rs b/crates/vlog_semantic/tests/workspace.rs index ca7e4de..c2d4c9f 100644 --- a/crates/vlog_semantic/tests/workspace.rs +++ b/crates/vlog_semantic/tests/workspace.rs @@ -790,6 +790,37 @@ fn reference_postings_point_from_a_declaration_to_every_cross_file_use() { assert!(!ws.references_are_ambiguous(definition)); } +/// `files_spelling` is the postings table asked the other question: not "who +/// refers to this declaration" but "who would notice if this name started +/// meaning something". The difference is a use that resolved to **nothing**, +/// which no posting can be keyed by — and which is exactly what a rename onto +/// that name would give a meaning. +#[test] +fn files_spelling_finds_the_uses_no_posting_can_be_keyed_by() { + let sources = [ + ("dangling.sv", "module strayer;\n import absent_pkg::*;\nendmodule\n"), + ("resolved.sv", "module holder;\n sub u0 ();\nendmodule\n"), + ("quiet.sv", "module quiet;\n wire absent_pkg;\n assign absent_pkg = 1'b0;\nendmodule\n"), + ("sub.sv", "module sub; endmodule\n"), + ]; + let ws = index(&sources); + let named = |name: &str| -> Vec<&Path> { + ws.files_spelling(name).filter_map(|file| ws.path(file)).collect() + }; + + // Nothing declares `absent_pkg`, so it is in no posting at all … + assert!(ws.units("absent_pkg").is_empty()); + // … but the file importing it is found, and the file that merely declares + // a local wire of the same name is not: a local declaration resolves + // inside its own file and the workspace was never asked about it. + assert_eq!(named("absent_pkg"), vec![Path::new("dangling.sv")]); + + // A use that *did* resolve is here too — a name that already means + // something can equally start meaning something else. + assert_eq!(named("sub"), vec![Path::new("resolved.sv")]); + assert!(named("nobody_spells_this").is_empty()); +} + #[test] fn replacing_one_file_rebuilds_reference_postings_without_reparsing_the_others() { let declaration = "module sub; endmodule\n"; diff --git a/docs/features/file-operations/README.md b/docs/features/file-operations/README.md index 3a6ecf6..8218b14 100644 --- a/docs/features/file-operations/README.md +++ b/docs/features/file-operations/README.md @@ -145,6 +145,16 @@ invariant #4 is not in play. The formatter is not involved in this path at all. 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. + - **`IncludeGraph::includers()`** (added 2026-08-28) — a read-only accessor + over the edge table's keys, which is what lets the sweep read the files + that write a resolving `` `include`` instead of every file in scope. The + property it stands on is `resolve`'s agreement with the `found` the edges + were built from; it is written out under "The sweep reads the includers, + not the workspace", and a change to either half must re-read it. + **Scope note for the lead:** `includes.rs` is outside the Lane A file + list this round was scoped to. The accessor is four lines, purely + additive, and there is no second way to ask the graph this question + without a second copy of the include scan — flagged rather than smuggled. - **`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 @@ -212,6 +222,47 @@ 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 sweep reads the includers, not the workspace (2026-08-28) + +The prefilter above still cost a *read* of every file to run. On OpenTitan +(3 976 files) that is 249 ms of `sources()` per gesture, and the server +advertises `willRename` with a `**` folder filter, so **renaming any folder in +the explorer paid it**. + +The include graph already holds the answer. `IncludeGraph`'s edge table is +built as `scan(text).filter_map(|include| self.found(Some(path), include))` +over every in-scope file, and `resolve` is exactly `found` followed by the +index's own spelling of the result — so `resolve` answers `Some` for an +include if and only if `found` did. Therefore: + +> **A file with no entry in the edge table writes no `` `include`` this +> workspace can resolve, so every iteration of `will_rename`'s inner loop over +> it hits `let Some(old) = graph.resolve(…) else { continue }`.** It can +> produce neither an edit nor a warning, and reading it is reading the +> workspace to answer "nothing". + +`Workspace::include_sources` is that set — `IncludeGraph::includers()` — plus +every **open buffer**, because the graph is rebuilt on save and an `` `include`` +typed and not yet saved is in the buffer and in no edge +(`an_unsaved_include_is_still_rewritten`). The one-directional property is +asserted directly over a hostile tree rather than argued +(`nothing_skipped_has_an_include_to_rewrite`: every in-scope file the sweep +skips is checked to have no resolving include, and the tree is asserted to +actually exercise the skip). + +Measured, `--release`: + +| | before | after | +|---|---:|---:| +| synthetic 506 files, 1 of them including anything | reading the scope **16.1 ms** | reading the includers **18.9 µs**; whole answer **35.4 µs** | +| OpenTitan, 3 976 files, 331 of them includers | `sources()` **249 ms** | whole answer **14.1 ms** | + +Same staleness premise the rename family adopted the same day +(`docs/features/refactor-rename/README.md`): the graph is the server's +authority on who includes what, a file changed on disk with nothing telling +this server is a file the sweep does not read, and open buffers are the +exemption. + The notifications cost one `reindex()` each, which is the cost a save has. ## Status / TODO @@ -230,6 +281,10 @@ The notifications cost one `reindex()` each, which is the cost a save has. 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] The sweep reads the include graph's includers plus the open buffers + rather than `sources()` (2026-08-28): `IncludeGraph::includers`, + `Workspace::include_sources`, the one-directional property asserted over + a hostile tree, and a before/after probe. - [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, @@ -327,6 +382,45 @@ target/debug/lucisv-server` → OK, 9 messages, unchanged from `bf17ddd` JSON and adds no message). Perf measured as above. No new dependency, no version bump, no other crate touched. +**2026-08-28 — dev agent (performance wave, Lane A).** The sweep stops reading +the workspace. `performance.md` §6e flagged `file_ops.rs:120`'s `ws.sources()` +as the same shape as the rename family's, unmeasured; it is 249 ms of file +reading per gesture on OpenTitan, and the server advertises `willRename` with +a `**` folder filter, so **renaming any folder in the explorer paid it** to +learn that 3 645 of 3 976 files write no `` `include`` that resolves. + +The include graph already holds that fact. `IncludeGraph::includers()` — four +lines, the edge table's keys — is the new accessor, `Workspace::include_sources` +is the set (includers plus every open buffer, because the graph is rebuilt on +save and an unsaved `` `include`` is in neither `raw` nor `edges`), and +`will_rename`'s loop is otherwise untouched. The argument is one sentence long +and is written up under "The sweep reads the includers, not the workspace": +`resolve` is `found` plus a re-spelling, and `raw` is built from `found`, so a +file with no edge has no include `resolve` answers — every iteration of the +inner loop over it hits its first `continue`. + +Rather than argue that by inspection alone it is asserted over a hostile tree: +`nothing_skipped_has_an_include_to_rewrite` walks every in-scope file the sweep +skips and checks each of its `` `include``s resolves to nothing, and asserts +the tree exercises the skip at all. Two behaviour tests beside it — +`the_narrowed_sweep_reads_the_includers_and_answers_the_same` (24 files, 1 +includer, 2 with dangling includes) and `an_unsaved_include_is_still_rewritten`. + +Measured, `--release`: synthetic 506 files, reading the scope **16.1 ms** → +reading the includers **18.9 µs**, whole answer **35.4 µs** +(`perf::a_will_rename_before_and_after`). OpenTitan, 3 976 files with 331 +includers: `sources()` **249 ms** → whole answer **14.1 ms** (throwaway probe +against the local checkout, deleted; no test depends on it). + +**One scope deviation, flagged not smuggled:** `includes.rs` is outside the +file list this lane was scoped to, and the accessor was added there anyway. +The alternative was a second copy of the include scan inside `state.rs`, which +is the one thing this module's Handshakes section already says must not +happen. Recorded in Handshakes above and in the round's report. + +Gates: `cargo fmt --all -- --check` clean, `cargo clippy --all-targets` clean, +`cargo test --workspace` green, `node editors/vscode/smoke.js` OK. + ## QA log ### 2026-08-27 — QA agent, file operations (TODO.md §9c) @@ -514,8 +608,86 @@ 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. +**2026-08-28 — QA agent (performance wave, Lane A).** Verified the round that +moves `will_rename`'s sweep off `ws.sources()` onto +`Workspace::include_sources()` (the include graph's `includers()`, plus open +buffers). Worked alongside the rename-family QA pass in the same worktree; +see `docs/features/refactor-rename/README.md`'s QA log for the shared gate +run. + +### Gates + +`cargo fmt`, `cargo clippy --all-targets`, `cargo test --workspace` (0 +failures workspace-wide) and `node editors/vscode/smoke.js` all pass — see the +refactor-rename QA entry for the exact run, which covered this round's diff +in the same pass. `file_ops::tests::perf::one_rename_sweeps_the_whole_corpus_in_milliseconds` +and `includes::tests::perf::building_the_graph_over_the_whole_corpus_is_milliseconds` +fail in this worktree because `corpus/` is not checked out here; confirmed +pre-existing (unchanged by this diff, present at `HEAD` before it) and +unrelated. + +### Attacks + +The safety-net argument this narrowing rests on ("a file with no entry in the +edge table writes no `` `include`` this workspace can resolve") is +mechanical and did not need attacking on its own terms — `nothing_skipped_ +has_an_include_to_rewrite` already asserts it directly over whatever tree a +test builds. What was worth attacking is whether `includers()` narrows in +**every** file that matters, not just the ones the dev's own tree happened to +build: + +- **An include chain, `a.svh -> b.svh`, with a third file `c.sv -> a.svh` + never spelling `b.svh` at all.** Renaming `b.svh` must narrow to `a.svh` + (its direct includer) and rewrite only it; `c.sv` must not be mistaken for a + candidate even though it transitively depends on the moved file through + `a.svh`. Added `an_include_chain_narrows_to_the_direct_includer_of_the_moved_file` + — passes: `will_rename` only ever rewrites a *direct* include of the moved + file, which is exactly what `includers()` (a flat key set, not a + reachability walk) bounds. +- **A case-mismatched include spelling** — `` `include "DEFS.svh"`` written + against a real `defs.svh` on disk, which macOS's default case-insensitive + filesystem (confirmed case-insensitive on this machine) resolves silently. + `IncludeGraph::found`/`found_as_if` key `raw` by the **includer's own path**, + not the target's spelling, so the case mismatch does not stop the includer + from landing in `includers()`. Added + `a_case_mismatched_include_spelling_still_narrows_in_and_rewrites` — passes, + narrows in and rewrites correctly. +- **Unsaved includer, and the property test's own coverage** — re-read + `an_unsaved_include_is_still_rewritten` and + `nothing_skipped_has_an_include_to_rewrite`; both hold and both are + exercised (`assert!(skipped > 0, ...)` in the property test actually forces + the tree to have skippable files, so the property is not vacuously true). + +No divergence found: every file `will_rename` would have read under the old +`ws.sources()` sweep and actually needed (an includer of something that +resolves) is still read under `include_sources()`, and no file that used to +be read-and-skipped is now silently mis-included either. The `includes.rs` +scope deviation the dev flagged (a four-line, purely additive accessor, +outside Lane A's stated file list) is accepted as argued — the only +alternative was a second copy of the include scan, which the feature's own +Handshakes section already forbids. + +### Summary + +| Claim | Verdict | +|---|---| +| Gates | **Pass** | +| `includers()` narrows in every file that can produce an edit or a warning | **Holds** under an include-chain attack and a case-mismatched-spelling attack, beyond the dev's own tree | +| Scope deviation (`includes.rs::includers`) | Accepted, correctly flagged, minimal | + +**Verdict: ship.** No findings against this round's diff. (The rename family's +own residue finding, which needs the lead's ruling, is filed in +`docs/features/refactor-rename/README.md` and does not touch this feature.) + ## Review +**2026-08-29 — lead, performance-wave Lane A (willRenameFiles).** The +includers() narrowing is the same discipline as the rename fan-out +applied to the include graph, QA's chain/case-spelling/unsaved attacks +all pinned, and the property test ("nothing skipped has an include to +rewrite") is the right shape of guarantee. Accepted; merged by the +lead. + ### 2026-08-27 — lead Reviewed the diff, the work log and the QA log; re-ran all gates myself diff --git a/docs/features/refactor-rename/README.md b/docs/features/refactor-rename/README.md index 73e84ba..b577eb9 100644 --- a/docs/features/refactor-rename/README.md +++ b/docs/features/refactor-rename/README.md @@ -29,6 +29,12 @@ pub fn prepare_rename(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Result; pub fn rename(files: &[(PathBuf, String)], file: &Path, offset: u32, new_name: &str) -> Result; + +// Added 2026-08-28 (the performance wave). Same question, no file set. +pub fn prepare_rename_here(semantics: &Semantics, external: &ExternalResolutions, + index: &WorkspaceIndex, offset: u32) + -> Result; +pub fn rename_name_at(semantics: &Semantics, offset: u32) -> Option; ``` `files` is **the boring option**: the in-scope files as `(path, text)` pairs — @@ -47,6 +53,15 @@ Deviations from the milestone sketch, and why: parameter would be cast at both ends of every call. - **`prepare_rename` returns a `RenameTarget`**, not a bare range: the editor wants the placeholder too, and it is the identifier's own text. +- **`prepare_rename_here` takes an analysis rather than a file set** (added + 2026-08-28). The server already holds every argument it needs for the open + buffer, so this asks nothing of the filesystem; `prepare_rename` stays as + the whole-workspace oracle the parity tests measure it against. See "The + file set a rename reads" below. +- **`rename_name_at` decides nothing.** It answers only "which identifier is + under this cursor", which is what the server needs to ask the index for the + fan-out. Every refusal stays with `rename`, which is the call that has the + files; a second opinion here could only disagree with it. ## What can be renamed @@ -131,6 +146,300 @@ shape for refactorings). needs to decide whether to open the rename box at all: everything else needs a new name to judge. +## The file set a rename reads (2026-08-28) + +Until this round both entry points were handed `Workspace::sources()` — every +in-scope file, read from disk — and built a whole `WorkspaceIndex` over it +before answering anything. On OpenTitan (3 976 files) that cost **1.7–3.0 s +for `prepareRename`** and **3.2–8.7 s for `rename`**, on a single-threaded +server where everything the editor sent next waited behind it. `prepareRename` +is what the rename key sends *before the box opens*, so those seconds were a +frozen editor on a keypress that had committed to nothing. + +Two different fixes, because they are two different questions. + +### `prepareRename`: the buffer already holds the answer + +The question is "is this a renameable symbol, and what are its range and +placeholder". `prepare_rename_here` answers it from the open buffer's own +`Semantics`, the `ExternalResolutions` overlay the server keeps beside it, and +the index — **no file is read and nothing is parsed**. Measured: 238 ms → +**200 ns** on the synthetic 504-file workspace, 1.604 s → **135 ns** on +OpenTitan. + +#### Refusal-by-refusal parity + +Every refusal `prepare_rename` can produce, and what the cheap path does with +it. Deferring a refusal to `rename` is allowed — LSP explicitly permits an +optimistic `prepareRename` — and losing one is not: a deferred refusal is +still delivered, in the same words, by the `rename` that follows. + +| # | Refusal (its own sentence) | Where it comes from | Cheap path | +|---|---|---|---| +| 3 | *"… is not one of the files lucisv indexes …"* | the request's file absent from `files` | **unreachable either way.** `sources()` contains every open buffer with a path, and this handler is only reached for one; a fast-path (large) buffer is refused by `server.rs` before it gets here. | +| — | *"the file could not be analyzed."* | `Scope::analysis` of an in-range index | **dead code in both**: the index came from `index_of`, so the lookup cannot miss. | +| 4 | *"there is no symbol to rename at this position."* | no reference and no symbol at the offset | **reproduced** — `reference_id_at` / `symbol_at` on the buffer. | +| 5 | *"… is not resolved to any declaration …"* | `Resolution::NotFound` | **reproduced** — single-file resolution, in the buffer. | +| 6 | *"… could only come from the base class `B` …"* | `Resolution::InheritedCandidate` | **reproduced** — same. | +| 7 | *"… is declared outside the files lucisv indexes …"* | `ExternalTarget::StillUnresolved` / absent | **reproduced** — the overlay is `resolve_external` against this same index, which is the call `Scope::declaration_across_files` makes. | +| 8 | *"… is declared in more than one indexed file …"* (from a cross-file use) | `ExternalTarget::Ambiguous` | **reproduced** — same overlay. | +| 9 | *"… is declared in more than one indexed file …"* (from the declaration) | `declaration.scope == file_scope && index.units(name).len() > 1` | **reproduced** — the buffer knows the scope, the index knows the count. | +| 11a | *"lucisv cannot find where `x` is spelled in its declaration …"*, declaration **in this buffer** | empty `name_span` | **reproduced.** | +| 11b | the same sentence, declaration in **another** file | that file's fresh `name_span` | **deferred.** The index only ever records a non-empty span, so this can only fire on a file whose analysis disagrees with the index — which means reading it. | +| — | *"`x`'s declaring file is not in scope."* | `index_of` on the declaring path | **deferred** (and unreachable in practice: `sources()` is a superset of the index's files). | +| — | *"the declaring file could not be analyzed."* / *"lucisv cannot locate the declaration of `x`."* | the declaring file's own analysis | **deferred**, same reason. | +| 1, 2, 10, 12, 13 | new-name validity, same name, ambiguous use onto this declaration, capture, token drift | — | **not `prepare_rename`'s at all**; they always were `rename`'s. | + +Pinned by `rename::tests::the_buffer_answers_a_prepare_exactly_as_the_workspace_does` +and its five siblings, which ask both entry points the same question at **every +byte** of hostile buffers — packages and qualified names, a name declared +twice, nothing resolving, generate blocks and macros, a file that does not +parse — and fail on any reworded refusal, any different answer, and any +refusal the cheap path *invents*. Deferrals are counted, never asserted away. + +**The one divergence, stated exactly.** Rule 9's count comes from the index, +and the index is rebuilt on save, not on keystroke (`state.rs`), so an unsaved +edit that adds or removes a file-scope declaration of the name is not in it. +`prepare_rename` counts the same declarations over the *current* texts. Both +directions are possible in principle; both are the ordinary index-staleness +window every other index-backed answer in this server lives in, and the +sentence itself says "indexed file". `rename` re-derives the count from the +current texts and is the authority. + +### `rename`: the symbol's fan-out, and why it is enough + +`Workspace::rename_sources` (state.rs) builds the file set from what the index +already holds. Its rungs, for the request's file, every open buffer, and each +spelling `N` in `{old_name, new_name}`: + +1. **every file declaring `N`** — `WorkspaceIndex::workspace_symbols(N)` + filtered to the exact name, which covers units *and* members (ports, + parameters, package and class members); +2. **every file the index recorded a use of one of those declarations in** — + `references_to(def)`, for **every** such declaration, not only the target's; +3. **every file instantiating `N`** — `instantiations_of(N)`; +4. **every file whose `` `define`` table names `N` or spells it in a macro + body** — a walk over the `DefineTable`s the index already holds (no file is + read), asking the same `vlog_refactor::contains_word` that + `Scope::define_sites` decides with, so the fan-out and the warning cannot + disagree about which files carry one; +5. **the units that export `N` as a member**, and every file declaring, + referring to or instantiating one of them — how a third file's `.N(...)` + connection or `u::N` is reached. + +and, for the **new name only**, a sixth: + +6. **every file that spells the new name in a use this workspace had to look + outside that file to answer — including the uses it could not answer at + all** — `WorkspaceIndex::files_spelling(N)`, a walk over the per-file + records (no file is read, nothing is parsed). Rungs 1–5 are all keyed by a + *declaration*, and a use that resolved to nothing has no declaration to be + keyed by; this is the rung that finds it. Why only the new name needs it is + argued under "The dangling-use case" below. + +Rung 6 is the only one whose cost grows with the workspace rather than with +the symbol, so it is measured on its own: **852 µs on OpenTitan's 3 976 files +in the worst case** — a name nothing spells, where the walk cannot +short-circuit — and 402 µs for `clk_i`, which 681 files spell. Building the +whole file set is 4.75 ms, most of it the other five rungs' +`workspace_symbols` scan and `` `define`` walk. Against a rename that costs +105 ms and used to cost 3.5 s, a sub-millisecond linear scan is the boring +implementation and stays one; a name-keyed side map is the fallback if a +workspace ever makes it visible, and nothing measured here comes close. + +#### The sufficiency argument + +**Lemma (name-locality of resolution).** A reference spelling `N` is resolved +by `vlog_semantic::follow_paths`, which tries the reference's recorded paths in +order and, for each, calls `follow_one` — and `follow_one` returns either +`index.units(N)` or `index.member(u, N)` for some unit name `u`. **Both are +keyed by `N`, and both are contributed only by files that declare the name +`N`** (as a unit, or as a member of some unit). Rung 1 puts every one of those +files in the set. Therefore, for every path list and every unit name, +`follow_one(subset, N, ·) == follow_one(whole, N, ·)`, so +`follow_paths(subset, N, ·) == follow_paths(whole, N, ·)`: **every reference +spelling `N` resolves in the subset exactly as it resolves in the whole +workspace.** ∎ + +Three consequences, which are the three things that could have gone wrong: + +- **No missed edit.** `Scope::collect_occurrences` emits a span in file *i* + only when *i* is the declaring file, or when a reference in *i* spelling the + old name resolves to the target declaration. The declaring file is rung 1. + A file with such a reference resolves the same way in the whole workspace + (Lemma), so the index recorded a posting for it — rung 2. Hence every file + the whole-workspace rename would edit is in the set. This is the + invariant-1 claim, and it is asserted directly, not only through an + equality, by `every_file_the_workspace_rename_edits_is_in_the_fan_out`. +- **No extra edit.** The converse of the same Lemma: a file in the subset + cannot resolve a reference *onto* the target that the whole workspace + resolves elsewhere. Without rung 1 this was a live corruption route — drop + the file declaring `p::x` and a `p::x`/`q::x` reference would fall through + to `q::x` and be renamed — which is why rung 1 is `workspace_symbols` and + not `units`. +- **The verifier keeps its reach.** `check::watched_files` watches every file + spelling the old *or the new* name. In the subset it can only watch what it + was given, so the new name gets rungs 1–6 of its own — which is what keeps + refusal 12 (capture) alive: `the_fan_out_still_refuses_a_rename_that_would_capture_a_name_elsewhere` + builds exactly the third file whose existing reference the rename would make + ambiguous, and the subset holds it because it is in the *new* name's + postings. + +#### The dangling-use case, and why the sixth rung is the new name's alone + +The Lemma settles what a name *resolves to*. It does not by itself settle +which files hold a use of that name, and rungs 1–5 answer that question only +through declarations: a file is in the set because it declares the name, +because a posting keys it to a declaration of the name, because it +instantiates the name, because a macro table mentions it, or because it names +the unit that exports it. **A use that resolved to nothing is keyed by +nothing.** `merge_references` drops a `StillUnresolved` result rather than +posting it, which is correct for `references_to` — there is no declaration to +post it against — and is exactly the hole. + +That hole is real and it costs a *refusal*, not a warning. Take +`import taken_pkg::*` in a file with no other tie to the rename: today it +resolves to nothing, and `check::print` records `Anchor::Unresolved`. Rename a +package to `taken_pkg` and the same use resolves — `Anchor::External` — which +is a changed meaning in a file the rename never edits, and refusal 12 exists +to refuse exactly that. QA found this on 2026-08-28 and reproduced it; the +lead ruled it not shippable, and rung 6 is the fix. + +**The old name has no analogous case, and this is why.** A rename only ever +*removes* declarations of the old name — it renames them away — and never adds +one. So for a use spelling the old name: + +- if it **resolves**, its declaration is one of the declarations of the old + name, so the file is in `references_to` of that declaration — and rung 2 + walks *every* declaration of the name, not only the target's. Already in the + set. +- if it **resolves to nothing**, it still resolves to nothing afterwards. + `follow_one` looks the name up in `units(old)` and `member(u, old)`; the + rename only takes entries out of those, and a lookup cannot start succeeding + because a candidate was taken away. `Anchor::Unresolved` before, + `Anchor::Unresolved` after — nothing for the verifier to see, so nothing + lost by not reading the file. +- if it **resolves ambiguously**, the escape hatch below fires and the whole + scope is handed over anyway. + +Pinned from both ends: `a_dangling_import_of_the_new_name_is_refused_by_both_paths` +(the new name's case, now parity rather than a disclosed gap) and +`a_dangling_use_of_the_old_name_needs_no_rung_of_its_own` (the old name's, +which asserts both that the new-name rung fires when the dangling spelling is +the *destination* and that nothing is pulled in when it is merely a bystander). + +#### The escape hatch + +Refusal 10 — *some other reference resolves ambiguously onto this +declaration* — is the one the postings cannot locate: an ambiguous use is +recorded against the declarations it could name (`references_are_ambiguous`) +and **not** against the file that writes it. Rather than lose that refusal, +`rename_sources` hands back the whole `sources()` the moment the index says +**any** declaration of either spelling is ambiguously referenced. Correct and +slow beats fast and silent. Pinned by +`an_ambiguously_referenced_declaration_falls_back_to_the_whole_scope`. + +**How often it fires, measured.** On OpenTitan the `aes` and `clk_rst_if` +cursors narrow to 7 and 114 files of 3 976; a cursor on a `.clk_i` port +connection falls back to all 3 976 — some declaration named `clk_i` somewhere +in the checkout is ambiguously referenced, and the hatch is deliberately +asked about *every* declaration of the name rather than about the target +alone. The answer is still right there (edits identical, all 652 warnings +identical); it is simply not faster. **The obvious narrowing — ask only about +the declaration the cursor resolves to, which is the only one refusal 10 +tests — is left for a later round on purpose**: it needs the target `Def` +identified server-side, which reintroduces the buffer-staleness question the +rest of this design keeps on one side of a line. Filed, not guessed at. + +#### The staleness premise, stated exactly + +> The index is the server's authority on which files declare a name and which +> files use it. A file changed on disk with nothing telling this server — no +> save, no watcher event, no rescan — or a file a startup scan has not reached +> yet, is a file a rename does not read. **Open buffers are the one exemption: +> every open buffer is in the set whatever the index holds, and the engine +> re-analyzes it from its current text, so unsaved edits are seen in full.** + +This is the same rule definition, hover, references, the code lens and the +call hierarchy already live by, and the file watcher is what keeps it true. It +is what the port refactorings adopted on 2026-08-28, one round earlier. What +it costs a rename specifically: a reference living only in a file whose disk +copy moved unseen is a reference the rename does not rewrite **and cannot +refuse over** — `check::verify` re-analyzes the subset, so a file outside it +is not compared before and after. Before this round `rename` was, with +`prepareRename` and the port actions, one of the few answers in this server +that could see *further* than the index; it no longer is. + +#### The residue — what the subset cannot see + +Written out rather than argued away. Each of these is a file whose only +mention of a name is something the index records no declaration, posting, +instantiation edge, macro definition or external-reference fact for. **After +the 2026-08-28 rework there is exactly one, and it costs a warning — no edit +and no refusal:** + +- **One warning flavour, and it is the loudest item on this page — measured, + not hypothetical.** `Scope::warnings` produces three sentences. Two are read + off a file's `` `define`` table (*"`x` is also a macro defined at …"* and + *"`x` appears in the body of macro `M` …"*) and **both survive**: the index + holds every file's table, and rung 4 walks it + (`the_fan_out_keeps_the_define_warnings_of_files_it_would_not_otherwise_read`). + The third comes from a **macro invocation whose arguments spell the name**, + and that one needs the file's token stream. A file outside the fan-out no + longer produces it. + + On the real OpenTitan checkout, at two cursors, with **no edit lost at + either**: + + ``` + aes -> aes_core_top edits identical (7 files, 7 edits) + warnings 7 -> 0, every one of them a + macro-invocation sentence: + `aes` in the arguments of `CONNECT_TL_DEVICE_IF` + at tb__xbar_connect.sv:30 and :47 (twice), + `DRIVE_CHIP_TL_DEVICE_IF` at :97, :140, :161, + `uvm_error` at keymgr_dpe_scoreboard.sv:644 + + clk_rst_if -> clk_rst_thing edits identical (114 files, 275 edits) + warnings 64 -> 61, the three lost being + `uvm_fatal` invocations + ``` + + Those macro invocations really do still spell the old name after the + rename, and saying so is the whole point of the warning. + `tb__xbar_connect.sv` mentions `aes` **only** inside macro-invocation + tokens, and the index models those in no table at all: a macro invocation is + one opaque token, contributing no declaration, no reference, no + instantiation edge and no define entry, so nothing short of reading and + lexing the file can find it. + + **This is a lead decision, and it is stated here rather than buried.** The + narrowing costs no edit and no refusal — the same runs assert the edit sets + byte-identical — but it costs the user a real piece of news. Recovering it + as things stand means running the warning pass over `sources()` while the + edits and the verification run over the fan-out: at least the 200–241 ms + workspace read plus a `tokenize` of every file spelling the name, which is + most of the win this round is for. The right answer is a + **macro-invocation census in `FileFacts`**, which would make this rung an + index lookup like the other five; that is a `vlog_semantic` change, and it + is filed as a request below rather than guessed at here. +- **No lost refusal.** The first draft of this round had one — a file whose + only mention of the new name was a use that resolved to nothing — and it is + **closed**, by rung 6. See "The dangling-use case" above for the argument + and the two tests. It is recorded here rather than deleted because the + shape is worth remembering: every rung keyed by a *declaration* is blind to + a use that has none, and a rename's whole job is to change which + declarations exist. +- **Nothing else.** A file whose occurrences of either name are strays — a + comment, a string, a local declaration inside a module, a hierarchical tail + — resolves identically before and after the edit, so the whole-workspace + verifier had nothing to say about it either. + +The alternative considered and not taken: hand the engine the whole file list +but a *prebuilt* index, which narrows nothing and would still cost the +`sources()` read (200–241 ms on OpenTitan) plus an index clone. It is recorded +here so the choice is visible rather than implied. + ## The verification story Two independent checks, both run in memory on the edited text, before @@ -230,7 +539,18 @@ implemented: the index's `FileId`s describe the same texts. - A rename is a rare, user-initiated request, so re-analyzing candidate files twice (once before the edit, once after) is affordable. No caching, no - incrementality. + incrementality. **Amended 2026-08-28**: a *prepareRename* is not rare — it + is what the rename key sends before the box opens — and "the candidate + files" is now the symbol's fan-out through the index rather than the whole + scope. See "The file set a rename reads". +- **The index is the server's authority on where a name is declared and + used** (2026-08-28). The fan-out is read from it, so a rename sees the + workspace as far as the index describes it: a file changed on disk with + nothing telling this server, or one a startup scan has not reached, is a + file the rename does not read. Open buffers are exempt — every one of them + is in the set whatever the index holds. The exact premise, what it costs and + what it does not, is written out under "The staleness premise, stated + exactly". - Refactored output is *edited source*, not reformatted source (umbrella Handshakes): the edits are minimal, and the user runs the formatter separately. @@ -256,10 +576,64 @@ implemented: ranges that slice back to the name — every edit span is one of these, and the engine re-checks the slice before emitting it. +**Consumed from `vlog_semantic`, added 2026-08-28** (no change required): +`WorkspaceIndex::{workspace_symbols, references_to, references_are_ambiguous, +instantiations_of, defines}` — the posting, edge and macro tables — are what make +the rename's file set a lookup instead of a workspace read. The sufficiency +argument leans on one published property of theirs, and it is worth naming so +it moves under supervision: **`references_to`'s postings are built by +`merge_references`, which resolves each recorded reference with the same +`follow_paths` `resolve_external` uses.** If those two ever stop being the one +function, the postings stop being a superset of the files a rename must edit. +The same goes for `workspace_symbols` covering both the `units` and the +`members` tables: rung 1 of the fan-out *is* that coverage. + +**Changed in `vlog_semantic`** (lead-authorized 2026-08-28 after QA, strictly +additive — the second such change this feature has made, the first being M2's +`Target::Declaration`): + +- **`WorkspaceIndex::files_spelling(name) -> impl Iterator`** — + every file holding an external reference *fact* spelling `name`, resolved or + not. New query, no new state, no format change: it reads the + `FileFacts::references` records the index already keeps, and + `FACTS_FORMAT` is untouched. Logged in `docs/features/vlog-semantic/README.md`'s + work log, as M2's change was. +- **Why it had to live there.** The records are `pub(crate)`, and the question + — "which files hold a use spelled `N` that this index had to look outside + that file to answer" — is a question about the index's own tables. The + alternative was for the server to re-derive it by reading and analyzing + files, which is the workspace read this whole round removes. +- **The contract it carries:** `references_to` is keyed by the declaration a + use *landed on*, so a use that landed on nothing is in no posting. + `files_spelling` is the same records asked by spelling instead, which is + what makes it answer for the unresolved ones. If `facts_from_analysis` ever + stops recording an unresolved external candidate — today it records every + `ExternalCandidate`/`InheritedCandidate` with a non-empty path list — rung 6 + stops closing the dangling-use case and this section must be re-read. + **Promised to `lucisv_server`** (and to any future CLI): - `rename` never panics and never returns a partial edit: `Ok` means every edit in it verified together, `Err` means nothing at all is to be applied. +- `prepare_rename_here` refuses in the *same sentences* `prepare_rename` does, + or defers to `rename`; it never invents a refusal `prepare_rename` would + not have made. The parity table above is the contract, and the byte-by-byte + parity tests are the enforcement. +- `rename_name_at` names the identifier `prepare_rename`'s `RenameTarget` + would name, at every offset where `prepare_rename` answers at all + (`the_name_a_fan_out_is_built_from_is_the_name_the_engine_acts_on`). + +**Requested of `vlog_semantic` (filed 2026-08-28, not taken):** a +**macro-invocation census in `FileFacts`** — per file, the macro invocations +it writes and the identifier-shaped words in their arguments. It is the one +piece of the rename's warning set the index cannot answer, and its absence is +the measured residue above: on OpenTitan, renaming `aes` loses seven +"`aes` appears in the arguments of the macro invocation …" warnings because +the files holding them contribute nothing else about `aes`. The census would +be one more `Vec` on a record `FACTS_FORMAT` already versions, read off the +token stream the parse already produced, and it would turn +`Scope::macro_use_warnings` from a workspace lex into a lookup — for the port +refactorings' identical scan as much as for this one. - `RefactorEdit.edits` is sorted by path; each file's edits are sorted by start offset, non-overlapping and non-empty. - `warnings` are informational only — an `Ok` result with warnings is still @@ -312,6 +686,19 @@ a much larger change than an end label and is not part of M2. - [x] Tests: 64 in `vlog_refactor` (14 unit incl. 8 masked-corruption attacks, 48 behavior, 2 corpus), 3 new in `vlog_semantic`, 8 in `lucisv_server` (7 in `rename.rs`, 1 capability), 1 e2e session +- [x] `prepareRename` answered from the open buffer and the index rather than + from `sources()` (2026-08-28): `prepare_rename_here` in the engine, the + refusal-by-refusal parity table above, and six byte-by-byte parity + suites against `prepare_rename` as the oracle +- [x] `rename` computed over the symbol's fan-out rather than the whole scope + (2026-08-28): `Workspace::rename_sources` in the server, + `rename_name_at` in the engine, the sufficiency argument above, the + ambiguity escape hatch, and equivalence tests over hostile workspaces +- [x] The dangling-use rung (2026-08-28, QA-driven rework): + `WorkspaceIndex::files_spelling` and rung 6 of the fan-out, applied to + the new name, which closes the one refusal the first draft lost. The + old name's exemption is argued under "The dangling-use case" and pinned + by its own test - [ ] Deferred: rename in comments and strings (rope's `docs=True`) — the umbrella lists it as an option, off by default, "until asked for" - [ ] Deferred: renaming a module together with its file @@ -473,6 +860,158 @@ Checks after the rework: `cargo fmt --all -- --check` clean, `cargo clippy --all-targets` zero warnings workspace-wide, `cargo test --workspace` green at 1085 tests (was 1072). +**2026-08-28 — dev agent (performance wave, Lane A).** The rename family stops +reading the workspace. `performance.md`'s two worst rows were +`textDocument/rename` (3.6–8.7 s) and `textDocument/prepareRename` +(2.5–3.0 s), both of them `ws.sources()` followed by a whole `WorkspaceIndex` +build; the measurer's own push-back — that `prepareRename` is what the rename +key sends *before the box opens*, not a rare user gesture — is the framing +this round took. + +Everything argued under "The file set a rename reads" above. The decisions +worth repeating here: + +- **`prepare_rename_here` takes an analysis, not a file set.** The server + already holds the buffer's `Semantics`, its `ExternalResolutions` overlay + and the index, and the overlay is `resolve_external` against that same + index — which is the exact call `Scope::declaration_across_files` makes. So + every refusal that depends on *which* declaration a use names is reproduced + rather than approximated, and only the four that need the declaring file's + own text are deferred. `prepare_rename` stays, as the oracle the parity + tests measure against; the refusal sentences were factored into five + functions so the two paths cannot word one situation two ways. +- **The fan-out's first rung is `workspace_symbols`, not `units`.** This is + the rung the whole equality argument turns on and the one that was easy to + get wrong: `follow_paths` looks a reference's *own* name up, in `units(N)` + or `member(u, N)`, and both tables are contributed only by files that + declare the name `N`. Drop the file declaring `p::x` from the set and a + reference with paths `[p::, q::]` falls through to `q::x` and is renamed — + an *over*-edit, corruption in the direction nobody looks. With rung 1 in + place the Lemma makes the subset's resolution of every reference spelling + either name identical to the workspace's, which is what buys "no missed + edit" and "no extra edit" at once. +- **The new name gets the whole fan-out too**, or refusal 12 (capture) dies: + the file whose existing reference a rename would make ambiguous is in the + *new* name's postings and in nothing of the old name's. +- **The ambiguity escape hatch.** An ambiguous use is recorded against the + declarations it could name, never against the file that writes it, so + refusal 10 cannot be reached from a subset. `rename_sources` hands back + `sources()` when the index reports one. Slow and correct beats fast and + silent. +- **`willRenameFiles`** got the same treatment through the include graph — + written up in `docs/features/file-operations/README.md`, including the + four-line `IncludeGraph::includers` accessor, which is the one file this + round touched outside its stated scope and is flagged there for the lead. + +Measured, `--release`, and the equality checked as well as the clock: + +| | before | after | +|---|---:|---:| +| OpenTitan (3 976 files), `prepareRename` on the `aes` instantiation | 1.663 s | **139 ns** | +| OpenTitan, `rename` of `aes` (7 files edited) | 3.467 s | **105.5 ms** (7-file fan-out) | +| synthetic 504 files, `prepareRename` on a module name | 251 ms | **212 ns** | +| synthetic 504 files, `rename` (4 files edited) | 486 ms | **370 µs** | + +(All four re-taken after the 2026-08-28 rework below, so the table describes +the shipped code. The earlier round measured 1.604 s → 135 ns, 3.284 s → +103.6 ms, 238 ms → 200 ns and 465 ms → 294 µs on the same corpus: the sixth +rung is inside the noise, which is what the separate rung measurement above +says directly.) + +The OpenTitan numbers were taken with throwaway probes against the local +checkout and deleted — no test may depend on it. The reproducible probe is +`perf::a_rename_before_and_after`. The throwaway also swept **every 7th byte +of `tb.sv`** comparing `prepare_rename_here` against `prepare_rename`: **564 +offsets, all identical, zero deferrals** — the parity table's contract holding +over real code, not only over the six synthetic buffers in the suite. + +**What the OpenTitan sweep found, and it is not nothing.** At the `aes` cursor +the two edit sets are byte-identical (7 files) and the *warnings* are 7 → 0: +`tb__xbar_connect.sv` and `keymgr_dpe_scoreboard.sv` spell `aes` only inside +macro-invocation tokens, which the index does not model in any table. Written +up in full under "The residue", with the cost of recovering it and a filed +request for the `FileFacts` macro-invocation census that would make it a +lookup. **It is a lost warning, never a lost edit or a lost refusal, and it is +the lead's call at review** — the honesty gate the brief asked for. + +Deliberately not done: `check::watched_files` still sweeps the file list it is +given with `contains_word`, which is now the fan-out rather than the +workspace; no attempt was made to narrow it further, because it is O(files in +the set) over text already in memory. + +Gates: `cargo fmt --all -- --check` clean, `cargo clippy --all-targets` clean +workspace-wide, `cargo test --workspace` green, `node editors/vscode/smoke.js` +OK against the release binary. + +**2026-08-28 — dev agent (QA-driven rework: the lost refusal is closed).** The +lead ruled the round's "one lost refusal" residue not shippable — *a silently +weaker refusal is not a residue we ship* — and directed the fix. QA had found +it, reproduced it and pinned it as +`known_residue_a_dangling_import_of_the_new_name_is_a_lost_refusal`; that test +is now `a_dangling_import_of_the_new_name_is_refused_by_both_paths` and +asserts parity through `same_answer` instead of pinning the divergence. + +The diagnosis, which is what makes the fix a rung rather than a patch: **rungs +1–5 are every one of them keyed by a declaration.** A file is in the set +because it declares the name, because a posting keys it to a declaration of +it, because it instantiates it, because a macro table mentions it, or because +it names the unit exporting it. A use that resolved to *nothing* has no +declaration to be keyed by — `merge_references` drops a `StillUnresolved` +result rather than posting it, correctly, since there is nothing to post it +against — and a rename's whole job is to change which declarations exist. So +`import taken_pkg::*` of a package nobody declares yet was invisible to the +fan-out and became meaningful the moment the rename landed, which is exactly +what capture rule 12 refuses over. + +What changed: + +- **`WorkspaceIndex::files_spelling(name)`** — one additive, lead-authorized + `vlog_semantic` query: every file holding an external reference *fact* + spelling the name, resolved or not. No new state, no new field, + `FACTS_FORMAT` untouched; it reads the `FileFacts::references` records the + index already keeps, which is the only reason the answer is available at all + without reading files. Logged in `docs/features/vlog-semantic/README.md`'s + work log as M2's `Target::Declaration` was, and the recording rule it rests + on is written into both Handshakes sections so it moves under supervision. +- **Rung 6 of `Workspace::rename_sources`**, `want_spellers`, applied to the + **new name only**. The old name provably needs nothing: a rename only ever + *removes* declarations of it, a resolving use of it is already in rung 2 + (which walks every declaration of the name, not only the target's), and a + non-resolving one cannot start resolving because a candidate was taken away. + That argument is written out under "The dangling-use case" and pinned from + the other side by `a_dangling_use_of_the_old_name_needs_no_rung_of_its_own`, + which checks both that the new-name rung fires when the dangling spelling is + the destination and that nothing is pulled in when it is a bystander. +- The Lemma is unchanged — it was always about what a name *resolves to*, and + it was always sound. What it never claimed, and what the sufficiency + argument now says out loud, is which files *hold* a use. Rung 6 is that + second question's answer. + +**The rung's cost, measured** (the lead asked for the number, and for a +name-keyed side map as the fallback if it were large — it is not). On +OpenTitan's 3 976 files: **852 µs** for a name nothing spells, which is the +worst case because `any()` cannot short-circuit, and **402 µs** for `clk_i`, +which 681 files spell. The whole file-set build is 4.75 ms, most of it the +other rungs. `rename` itself went 103.6 ms → 105.5 ms, i.e. unchanged against +a 3.5 s baseline. On the synthetic 504-file corpus the rung is 49.8 µs of a +128.7 µs set build; both are printed by `perf::a_rename_before_and_after`, +which grew two lines for them. + +Re-verified after the rework, against the real OpenTitan checkout: all four +cursors still byte-identical (`aes` 7 files, `clk_rst_if` 114 files, `.clk_i` +4 files), the capture refusal on `aes` → `prim_fifo_sync` still verbatim, the +warning counts unmoved. The refusal parity table is unaffected — it is +`prepareRename`'s, and neither entry point's refusal set changed; what changed +is which files `rename` reads before producing rule 12's. + +**The macro-invocation warning residue stands as documented** — the lead +accepted it on the record, and the `FileFacts` macro-invocation census remains +filed as the real fix. + +Gates after the rework: `cargo fmt --all -- --check` clean, +`cargo clippy --all-targets` clean workspace-wide, `cargo test --workspace` +green, `node editors/vscode/smoke.js` OK against the release binary. + ## QA log **2026-08-24 — QA agent.** @@ -883,8 +1422,336 @@ surface (hierarchical tails, `defparam` paths, mismatched/redeclared end labels) is honestly disclosed and consistent with the "lucisv does not preprocess / does not elaborate" boundary the umbrella already draws. +**2026-08-28 — QA agent (performance wave, Lane A).** Verified the round that +moves `prepareRename` and `rename` off `ws.sources()`. Adversarial charter: +find a rename that edits, warns or refuses differently than the +whole-workspace path would, or a `prepareRename` that lies. Worked in +`.claude/worktrees/agent-a2cccf825469bf247`. + +### Gates + +- `cargo fmt --all -- --check` — clean, after fixing formatting in QA's own + additions (`cargo fmt --all`; the dev's diff itself was already clean). +- `cargo clippy --all-targets` — clean, zero warnings, forced re-check after + `touch`ing every file this round changed. +- `cargo test --workspace` — green, 0 failures, across every crate (doc-tests + included). +- `node editors/vscode/smoke.js target/release/lucisv-server` — OK, 10 + messages, against a freshly built release binary carrying this round's diff + plus QA's added tests. +- Numbers reproduced against the actual code under review (not trusted from + the Work log), `cargo test --release -p lucisv_server --bin lucisv-server + perf:: -- --ignored --nocapture --test-threads=1`: `prepareRename` 238.29 ms + → **179 ns**; `rename` 466.54 ms → **294.9 µs**; `willRenameFiles` scope-read + 11.39 ms → includers-read **15.1 µs**. All within noise of the Work log's + claims. (Two unrelated corpus-dependent perf tests failed in this worktree + because `corpus/` is not checked out here — pre-existing, unaffected by this + diff, confirmed present in `HEAD` before this round's changes.) +- Real OpenTitan checkout (`/Users/guoliangchen/repo/opentitan` @ `0098135264`, + 3979 files, matching `performance.md`'s provenance), driven over real LSP/ + stdio with a client pointed at this worktree's own `target/release/ + lucisv-server` (not the dev's throwaway probes, and not the earlier + "instrumented" binary from the measurer's session): cold workspace scan + settled in 2 940.7 ms; six repeated `rename`s of `aes` averaged **~104 ms** + and all edited exactly the 7 files the Work log names (`tb.sv`, `aes.sv`, + `aes_wrap.sv`, `aes_tb.sv`, and the three `*_pd_main.sv` top-level + instantiation sites); four repeated `prepareRename`s on the same cursor + averaged **~0.05 ms** client-observed (the LSP round trip, not the dev's + in-process 135 ns — consistent with `performance.md`'s own 0.02–0.33 ms + transport floor: the request now costs essentially nothing but the pipe). + **All three gates and the numbers: pass, claims confirmed.** + +### Confirmed finding (HIGH, disclosed by the dev, verified real and exactly +as bounded) — the residue's "one lost refusal" + +The README's own "The residue" section names a case the fan-out cannot catch: +a file whose only mention of the **new** name is a bare reference that +resolves to nothing today (an `import new_name::*` of a package that does not +exist yet, or a type spelled `new_name`). The whole-workspace verifier refuses +such a rename (capture rule 12: the import would start meaning something); +the fan-out never reads that file, so it returns `Ok` instead — a materially +weaker answer, not merely a lost warning like the macro-invocation case below +it. I built the minimal repro and pinned it as a permanent regression test, +`crates/lucisv_server/src/rename.rs`, +`known_residue_a_dangling_import_of_the_new_name_is_a_lost_refusal`: package +`cfg_pkg` renamed to `taken_pkg`, with a third file `module strayer; import +taken_pkg::*; endmodule` that declares, references (under the old name) and +instantiates nothing. `vlog_refactor::rename` over the whole scope refuses +(`"...would change what taken_pkg means in stray.sv..."`); over +`Workspace::rename_sources`'s real output, it succeeds silently. Confirmed +this is exactly as narrow as documented — every attack in the next section +(new-name declared elsewhere, new-name instantiated elsewhere, new-name +reached via a member connection) is still caught by rungs 1/3/5, so the gap is +precisely "an unresolved bare reference to the new name, nothing else." This +is not a new defect: it is the dev's own disclosed residue, verified to +reproduce exactly as written and correctly bounded. Recorded per CLAUDE.md +invariant 4's spirit (a widened forgiveness needs attack tests proving the +boundary) even though this is a narrowing, not `verify.rs`, because the same +"guilty until proven innocent, with tests" discipline applies to any new gap +between the fast and slow paths. **This is the one item that needs the lead's +explicit ruling** before ship — the brief's own honesty gate. + +### Attacks that held — no divergence found + +All added as permanent regression tests in `crates/lucisv_server/src/rename.rs` +unless noted, run against the real `Workspace::rename_sources`/ +`prepare_rename_here` production code paths, not reimplementations: + +- **Escaped-identifier instantiation** (`\sub u_weird (...)`- a different + name to `vlog_semantic` than `sub`, a pre-existing simplification this round + did not touch): `an_escaped_identifier_instantiation_does_not_break_fan_out_parity`. + Both paths call the identical engine, so the escaped spelling is untouched + by both, byte-identical — the fan-out dropping the file (it posts nowhere) + changes nothing observable, since the whole-workspace run's own watch of it + is also a no-op. +- **Same spelling, different symbol kind** (a module named `sub` vs. an + unrelated wire also named `sub` in a different module): + `a_same_spelling_different_symbol_kind_is_not_captured_by_the_fan_out`. The + unrelated wire's file and declaration are never touched. +- **Escape hatch discovered on the second spelling, not the first** — the + ambiguity is on the *new* name only, so `fan_out_of`'s loop over `[name, + new_name]` must not leak a partially-built, too-narrow `wanted` set when it + bails on the second iteration: + `the_escape_hatch_fires_when_only_the_new_names_posting_is_ambiguous`. Falls + back to the whole scope correctly; `Workspace::rename_sources`'s early + `return self.sources()` on the first ambiguous hit (state.rs, `fan_out_of`) + discards the partial set rather than returning it, exactly as needed. +- **Prepare parity fuzz beyond the dev's six buffers** + (`crates/vlog_refactor/src/rename.rs`): a valid head followed by an + unparseable tail, CRLF line endings, multi-byte UTF-8 text ahead of the + probed identifiers, and a macro-heavy buffer (`` `ifdef``/`` `define``/ + `` `BUMP(x)`` all in one file) — every offset of every buffer, no + divergence, no invented refusal. +- **Include-graph-adjacent attacks on `willRenameFiles`**, in + `crates/lucisv_server/src/file_ops.rs`: an include chain `a.svh -> b.svh` + with a third file `c.sv -> a.svh` (renaming `b.svh` narrows to `a.svh` only, + correctly leaves `c.sv` unedited since it never spells `b.svh`, + `an_include_chain_narrows_to_the_direct_includer_of_the_moved_file`), and a + case-mismatched include spelling (`` `include "DEFS.svh"`` against a real + `defs.svh` on this case-insensitive filesystem, + `a_case_mismatched_include_spelling_still_narrows_in_and_rewrites`) — both + narrow in correctly and rewrite correctly. +- **Deferred-refusal reachability (rule 11b).** Attempted to construct a case + where the declaring file (in another file from the buffer) has an empty + `name_span`, which is the one row the parity table marks "deferred" rather + than "reproduced." Could not construct one through the public parsing API: + the name-span contract (`vlog-semantic`'s Handshakes, and this feature's own + "every edit span originates in a parsed node") guarantees a non-empty span + on every declaring node the binder records, so this refusal looks + unreachable through any real workspace state today, in the same way the two + "—" rows in the parity table are marked unreachable. Not fixed or asserted + either way — flagging for the record rather than claiming coverage the + suite does not have. + +### Not attempted / out of scope for this round + +The end-label, hierarchical-tail, `defparam`, and escaped-identifier +*declaration* findings from the 2026-08-24 rounds above are pre-existing and +untouched by this diff — re-read, not re-attacked. The `willCreateFiles`/ +`willDeleteFiles` non-goals in file-operations are unrelated to this round. + +### Summary + +| Claim | Verdict | +|---|---| +| Gates (fmt/clippy/test/smoke) | **Pass** | +| Numbers (synthetic probes + real OpenTitan, this worktree's own build) | **Pass, reproduced independently** | +| Sufficiency argument (name-locality lemma) | **Holds** under every attack tried: escaped identifiers, same-spelling different symbols, mid-walk ambiguity, prepare-parity fuzz, include-chain/case-mismatch narrowing | +| The residue — macro-invocation warning loss | Reproduces exactly as measured on OpenTitan (7→0, 64→61); no edit or refusal lost, only the one warning flavour; already the lead's disclosed call | +| The residue — "one lost refusal" (dangling import of the new name) | **Confirmed real, reproducible, and exactly as bounded** — a genuinely weaker answer than the whole-workspace path, not just a lost warning. **Needs the lead's explicit ruling before ship.** | + +**Verdict: REWORK-gate, not ship-as-is** — not because anything is broken by +accident, but because the one item the brief calls "gate the subset path +behind that honesty (lead decides at review)" has not yet had that decision +made. Every other attack in the adversarial charter held. My recommendation, +for the lead: this is very likely acceptable to ship (it is a narrowing of a +*refusal*, not an edit — CLAUDE.md invariant 1 is about edits, and none is +lost or wrong here), especially since the parallel macro-invocation-warning +residue was already accepted; but "very likely acceptable" is not the same as +"decided," and the brief was explicit that this exact honesty gate needs a +lead ruling, not a QA one. + +**2026-08-29 — QA agent (re-verification of the rework: rung 6, +`WorkspaceIndex::files_spelling`).** Focused pass, not a full re-run, on the +lead-authorized fix for the HIGH finding above: the flipped test +(`a_dangling_import_of_the_new_name_is_refused_by_both_paths`) and the new +`a_dangling_use_of_the_old_name_needs_no_rung_of_its_own`, plus "The +dangling-use case" section's argument (rung 6 is the new name's alone because +a rename only ever *removes* declarations of the old name). Charter: attack +rung 6's completeness, attack the old-name exemption with a shadowing/ +"unmasking" hunt, verify the tests actually assert what they claim, spot-check +the rung's cost, run the gates. Worked in the same worktree. + +### Rung 6 completeness — three new attacks, all pass + +Read `WorkspaceIndex::files_spelling` (`crates/vlog_semantic/src/workspace.rs`) +and `resolve.rs`'s `Target::{Package,Unit,UnitMember}`/`miss` machinery to find +every way a real reference could spell the new name and end up with a +`Resolution` whose `paths` are empty (invisible to `files_spelling`, since +`facts_from_analysis` only records `ExternalCandidate`/`InheritedCandidate` +with a non-empty path list). The exhaustive case split: **every** miss on +`Target::Package`, `Target::Unit`, `Target::UnitMember` — including the head +of `p::x` and an `extends`/`implements` base — always pushes at least the bare +name onto its paths (`named_at_file_scope`'s `None` arm, `unit()`'s unconditional +`external.push(name.to_string())`, `unit_member`'s two unconditional +`ExternalCandidate` arms), so all of those are recorded regardless of whether +they resolve. The **only** empty-paths cases are `this_member`/`super_member` +(always `paths: Vec::new()`) and a plain `Target::Lexical` miss inside a class +with `extends` when no import in scope supplies anything +(`miss()`'s `InheritedCandidate { base, paths: external }` with `external` +empty) — and for exactly these, `resolve_external` can *never* produce an +overlay entry (`follow_paths` on an empty list is `StillUnresolved` by +construction, unconditionally, both before and after any rename, because the +paths are fixed by the file's own unedited text), so the reference's `Anchor` +is provably invariant and excluding the file costs nothing on either path. + +Three permanent regression tests added to `crates/lucisv_server/src/rename.rs` +to check this empirically rather than trust the proof alone: + +- `a_new_name_spelled_only_as_an_extends_base_is_still_caught_by_rung_6` — a + class `extends taken_base` where `taken_base` is declared nowhere; renaming + a package to `taken_base` is refused by both paths, and rung 6 pulls the + file in via the `Target::Unit` path (a genuinely different resolution + target than the import case rung 6 was built for). Passes. +- `an_unqualified_use_inside_an_extending_class_with_empty_paths_needs_no_rung` + — the one real empty-paths shape (a bare identifier inside a class that + extends an existing, unrelated base, no import in scope). Confirmed + `files_spelling` does **not** pull the file in, and confirmed (via + `same_answer`) that excluding it changes nothing — the rename still + succeeds identically on both paths. Passes, both assertions. +- `a_local_only_symbol_sharing_the_new_names_spelling_is_not_a_bogus_refusal` + — a wire declared and used only locally in a third file, sharing the new + name's spelling. `files_spelling` correctly excludes it (it is a + `ReferenceFact::Local`, which the function's own `match` arm returns + `false` for), and the rename succeeds with no edit to that file. This is + also directly what `files_spelling_finds_the_uses_no_posting_can_be_keyed_by` + in `crates/vlog_semantic/tests/workspace.rs` pins at the query's own level + (`quiet.sv`'s local wire named `absent_pkg` is excluded from + `named("absent_pkg")`) — read and re-run, still passes. + +### Old-name exemption — shadowing/"unmasking" hunt, none found + +Tried to construct exactly the counterexample the charter asked for: two +packages `p_pkg` and `q_pkg` both exporting a member spelled `shared_name`, a +third file importing both (`p_pkg` first, so "first-written import wins" +resolves `shared_name` to `p_pkg`'s declaration today), then renaming *away* +`p_pkg::shared_name` — the hypothesis being that the importer's reference +would silently fall through to `q_pkg`'s pre-existing, unrelated declaration +without the importer's file being in the fan-out. + +It doesn't happen, and reading why is the actual finding: the importer's +`shared_name` reference currently *resolves to the rename target itself*, so +it is not a bystander a removal could silently redirect — it is an edit site. +`Scope::collect_occurrences` rewrites it to the new name along with the +declaration, so the text never says `shared_name` again for `follow_paths` to +re-resolve against `q_pkg`. Generalizing: any reference that could possibly +be affected by removing declarations of the old name must itself spell the +old name (the workspace tables are keyed by literal name string, so a +reference to an unrelated name cannot be touched by removing entries under a +different key), and by the Lemma such a reference either (a) resolves to the +target — edited away, not orphaned — or (b) resolves to a *different* +existing declaration of the same name — already in the set, because rung 1 +(`workspace_symbols`, not `units`) walks *every* declarer of the name and rung +2 posts against each one, not only the target's — or (c) resolves to nothing +— stays resolving to nothing, since removing a candidate cannot manufacture a +new match. There is no fourth case, so there is no shadowing route the old +name needs a rung for. Verified empirically as well as by this argument: +`removing_the_old_names_winning_declaration_does_not_escape_the_fan_out` +(added to `crates/lucisv_server/src/rename.rs`) builds the exact scenario +above and confirms the fan-out includes both `q.sv` (rung 1, every declarer) +and `user.sv` (rung 2, posted against `p_pkg`'s declaration), that the rename +succeeds, edits exactly the declaration and the importer's reference, and +never touches `q_pkg`'s unrelated declaration. **The old-name exemption +argument held under attack — no counterexample found, and the reason none +exists is now written into the test itself, not just asserted.** + +### Tests genuinely assert what they claim — sabotage-verified + +Read every test named above plus the dev's flipped/new ones +(`a_dangling_import_of_the_new_name_is_refused_by_both_paths`, +`a_dangling_use_of_the_old_name_needs_no_rung_of_its_own`) end to end, then +sabotaged rung 6 out (`Workspace::rename_sources`, wrapped the +`want_spellers` call in `if false { … }`) and re-ran the whole +`rename::tests::` module: + +- **Failed, as they must**: `a_dangling_import_of_the_new_name_is_refused_by_both_paths`, + `a_dangling_use_of_the_old_name_needs_no_rung_of_its_own` (the file "the + fan-out lost the refusal … and edited 1 files instead" — exactly the + pre-rework residue, reproduced on demand), and the new + `a_new_name_spelled_only_as_an_extends_base_is_still_caught_by_rung_6`. +- **Still passed, as they must** (they test cases that provably do not + depend on rung 6): the empty-paths test, the local-only-symbol test, the + shadowing/unmasking test, and every pre-existing fan-out test. + +Reverted the sabotage (`git diff crates/lucisv_server/src/state.rs` after +reverting shows zero trace of it) and re-ran — all 26 tests in +`rename::tests::` pass again. This is the strongest confirmation available +short of formal proof: the tests that claim to depend on rung 6 actually do, +and the tests that claim not to actually don't. + +### Numbers, spot-checked + +Release probe (`cargo test --release -p lucisv_server --bin lucisv-server +perf::a_rename_before_and_after -- --ignored --nocapture --test-threads=1`), +against this worktree's own freshly rebuilt binary: file-set build **137.2 +µs**, of which `files_spelling` **52.1 µs**; rename fan-out **396.1 µs**; +`prepareRename` whole-workspace **249.5 ms** → buffer+index **212 ns**. All +within noise of the Work log's 128.7/49.8/370/238/200 µs-and-ns figures. + +Real OpenTitan checkout, over actual LSP/stdio with a client pointed at this +worktree's own rebuilt `target/release/lucisv-server` (not a throwaway +in-process probe): six repeated `rename`s of `aes` on a cold workspace scan +(3 015.7 ms settle) averaged **~118 ms** (107–134 ms), consistent with the +Work log's 105.5 ms and my own prior-round measurement of ~104 ms — the +spread is machine noise, not a regression from rung 6. Re-requested the same +`aes` → `aes_core_renamed_qa2` rename directly (not just repeated identical +renames) and got the **same 7 files, same edit counts** as my prior-round +spot check, confirming rung 6 changes nothing about the real edit set. + +### Gates + +`cargo fmt --all -- --check` clean. `cargo clippy --all-targets` clean (forced +re-check after `touch`ing every file this rework changed, zero warnings — +including in the three new tests, one `unused_must_use` warning caught and +fixed on the way, noted so it isn't mistaken for a dev-side issue). `cargo +test --workspace`: **0 failures**, no panics, workspace-wide (34 test binaries +including doc-tests). `node editors/vscode/smoke.js target/release/lucisv-server` +— OK, 10 messages. + +### Verdict + +**SHIP.** The rework closes the HIGH finding exactly as claimed: rung 6 is +complete under every completeness attack tried (including two shapes — the +extends-base case and the empty-paths InheritedCandidate case — the dev's own +writeup didn't walk through explicitly), the old-name exemption holds under a +genuine shadowing/unmasking attempt (with the reason now understood and +tested, not just asserted), the flipped and new tests are not vacuously +passing (sabotage-confirmed), and the rung's cost is sub-millisecond on +OpenTitan with no measurable end-to-end regression. No new findings. The +macro-invocation warning residue is unchanged and remains the lead's +already-accepted, separately-tracked call. + ## Review +**2026-08-29 — lead, performance-wave Lane A.** Reviewed after QA's +initial REWORK-gate, the fix round, and QA's SHIP on re-verification; +gates re-run on the worktree (fmt clean, clippy silent, 2518 workspace +tests green). The round's spine is the name-locality lemma, and the +rework is what made it whole: rungs 1–5 are all keyed by declarations, +so the dangling-use capture case — a refusal, not a warning — needed +rung 6 (`files_spelling`, over the reference facts the index already +keeps, FACTS_FORMAT untouched), and the lead ruled the residue +unshippable rather than documentable. QA then enumerated resolve.rs's +full miss taxonomy to prove the rung's two blind spots workspace- +invariant, hunted a shadowing counterexample to the old-name exemption +and found the lemma held, and sabotage-verified the parity tests bite. +That is the loop working as designed. prepareRename 1.66 s → 139 ns, +rename 3.47 s → 105 ms with the rung costing 852 µs worst-case, +willRename 249 ms → 14 ms; byte-parity swept at four real cursors and +564 offsets. The accepted macro-invocation warning residue and the +FileFacts macro census stay filed; the includes.rs accessor deviation +was the correct refusal to copy a scan. Accepted; merged by the lead. + **2026-08-24 — lead.** Reviewed the full diff after QA round 2's ship verdict; ran the three gates independently (1085 tests, 0 failures, clippy silent). The two-layer verification in `check.rs` is the right safety story diff --git a/docs/features/vlog-semantic/README.md b/docs/features/vlog-semantic/README.md index 17bebd4..61a9bbd 100644 --- a/docs/features/vlog-semantic/README.md +++ b/docs/features/vlog-semantic/README.md @@ -443,6 +443,39 @@ Checks at the end: `cargo test -p vlog_semantic` 26 tests green (19 + 6 + 1), `cargo clippy -p vlog_semantic --all-targets` silent, `cargo fmt` clean, `cargo test --workspace` green. +**2026-08-28 — `WorkspaceIndex::files_spelling`, lead-authorized, additive.** +One new query, requested by refactor-rename's performance round after QA found +a lost refusal in it; the second authorized cross-module change that feature +has made (M2's `Target::Declaration` was the first). + +```rust +pub fn files_spelling(&self, name: &str) -> impl Iterator + '_ +``` + +Every file holding an **external reference fact** spelling `name`, whether or +not it resolved. Nothing was renamed, removed, re-spanned or re-ordered; no +new state, no new field, and **`FACTS_FORMAT` is untouched** — it reads the +`FileFacts::references` records the index already keeps, which is why it can +answer at all. A linear walk over those records in `FileId` order. + +Why it belongs here rather than in the caller: `reference_sites` is keyed by +`DefinitionKey`, so a use that resolved to **nothing** is in no posting — the +right shape for "who refers to this declaration", the wrong one for "which +files would notice if this name started meaning something". The second +question is what a rename must ask about the name it renames *to*, and the +records that answer it are `pub(crate)`. The alternative was for the server to +re-derive it by reading and analyzing every file, which is the workspace read +that round exists to remove. + +The property callers now depend on, stated so it moves under supervision: +`facts_from_analysis` records a `ReferenceFact::External` for every +`ExternalCandidate`/`InheritedCandidate` with a non-empty path list, +*including the ones the index cannot resolve*. `merge_references` then drops +the unresolvable ones when building postings — that drop is what +`files_spelling` exists to see past. If the recording rule narrows, say so in +`docs/features/refactor-rename/README.md`'s Handshakes, whose rung 6 rests on +it. Tested by `tests/workspace.rs::files_spelling_finds_the_uses_no_posting_can_be_keyed_by`. + ## QA log **2026-08-19 — QA agent.** Verified against `crates/vlog_semantic/src/{lib,model,bind,resolve,scan}.rs` diff --git a/docs/perf/README.md b/docs/perf/README.md index 0229e44..3d7aa4b 100644 --- a/docs/perf/README.md +++ b/docs/perf/README.md @@ -441,6 +441,88 @@ The last row is the follow-up this round did not take: a rename must see every file that could name the symbol, so its subset is a different argument. It is sent when the user presses the rename key, not per cursor move. +## Before / after — round 7, Lane A (2026-08-28) + +`docs/features/refactor-rename/README.md` and +`docs/features/file-operations/README.md`: the three remaining `ws.sources()` +callers, and the two worst rows in `performance.md`'s table. + +The framing round 6 inherited — "a rename is user-initiated, so it may be +slow" — was half wrong. **`prepareRename` is what the rename key sends before +the box opens**, and it was the second-worst number in the whole report: 2.5– +3.0 s of a wholly frozen single-threaded server on a keypress that had +committed to nothing, taking hover, definition and highlight down with it. +Its entire answer — the identifier's range and its placeholder — is in the +open buffer already. + +Three fixes, three shapes: + +- **`prepareRename`** is answered from the buffer's own `Semantics`, the + `ExternalResolutions` overlay beside it and the index. No file is read, + nothing is parsed. The refusal-by-refusal parity table is in the rename + README; four refusals that need the *declaring file's* own text are deferred + to `rename`, which is what LSP's optimistic `prepareRename` is for. +- **`rename`** is computed over the symbol's fan-out through the index — every + declarer of the old *and* the new name (units and members), every reference + posting, every instantiation edge, every macro definition, the containing + units and their fan-out, every file that *spells* the new name in a use the + index had to look outside that file to answer, plus every open buffer. The + sufficiency argument, the escape hatch for an ambiguously-referenced + declaration, and the named residue are in the rename README. +- **`willRenameFiles`** reads the include graph's includers instead of the + workspace: a file with no edge writes no `` `include`` this workspace can + resolve, so its turn in the sweep could only ever `continue`. + +Measured over the real OpenTitan checkout (3 976 files indexed, `--release`, +same machine and corpus as `performance.md`): + +| request | before | after | +|---|---:|---:| +| `textDocument/prepareRename` on the `aes` instantiation | 1.663 s | **139 ns** | +| `textDocument/rename` of `aes` (7 files edited) | 3.467 s | **105.5 ms** (7-file fan-out) | +| `workspace/willRenameFiles` for one header | 249 ms of `sources()` alone | **14.1 ms**, whole answer (331 includers of 3 976) | + +The remaining 105.5 ms is the engine over 7 real files — index build, then an +analysis of each before and after the edit — not the workspace read: +`sources()` alone was 200–241 ms across runs, which is the row with the most +run-to-run spread on a machine that is not quiet. Building the fan-out itself +is **4.75 ms**, of which the one rung that scans the whole index rather than +looking a key up — `WorkspaceIndex::files_spelling`, the dangling-use rung +added in the QA-driven rework — is **852 µs at its worst** (a name nothing +spells, where the walk cannot short-circuit) and 402 µs for `clk_i`, which 681 +files spell. + +Every row was also checked for **equality** against the whole-workspace +computation, which is the point: this is a smaller input to the same engine, +not a cheaper approximation. Four real cursors in `tb.sv`: + +| cursor | fan-out | result | +|---|---:|---| +| `aes` → `aes_core_top` | 7 of 3 976 | edits identical (7 files, 7 edits); **7 macro-invocation warnings lost** — the one accepted residue, see the rename README | +| `aes` → `prim_fifo_sync` | 7 | both refused, verbatim: *"renaming `aes` to `prim_fifo_sync` would change what `prim_fifo_sync` means in tb.sv"* | +| `clk_rst_if` → `clk_rst_thing` | 116 | edits identical (114 files, 275 edits); 64 → 61 warnings | +| `.clk_i` → `clock_in` | **3 976** | edits identical (4 files, 5 edits), all 652 warnings identical — the ambiguity escape hatch fired, so this cursor is correct but not faster | + +and `prepare_rename_here` was swept against `prepare_rename` at every 7th byte +of the same file: **564 offsets, all identical, zero deferrals.** + +Reproducible without that checkout, over 500 generated files of 200 lines plus +a module instantiated in three of them +(`perf::a_rename_before_and_after`, `perf::a_will_rename_before_and_after`): + +| | before | after | +|---|---:|---:| +| `prepareRename` on the module name | 251 ms | **212 ns** | +| `rename` to a new name (4 files edited, 4-file fan-out) | 486 ms | **370 µs** | +| — building that file set | — | 128.7 µs, of which `files_spelling` 49.8 µs | +| `willRenameFiles`, reading the scope vs the includers | 16.1 ms | **18.9 µs** (whole answer 35.4 µs) | + +Every OpenTitan and synthetic figure above was re-taken after the QA-driven +rework, so the tables describe the shipped code. The pre-rework round measured +1.604 s → 135 ns, 3.284 s → 103.6 ms, 238 ms → 200 ns and 465 ms → 294 µs on +the same corpora: the sixth rung is inside the run-to-run noise, which the +separate rung measurement says directly rather than by subtraction. + ## What it would take to go faster Ranked by what the measurements above say is there, with what each would @@ -521,6 +603,12 @@ cost. None of these were attempted; each is a future round. drain can break up (`perf::what_a_scan_does_before_its_first_file`). The e2e probe above was flipped to `a_hover_issued_during_the_initial_scan_is_answered_during_it`. +- [x] **Added in round 7, Lane A (2026-08-28):** the rename family's + before/after, over the same generated corpus round 6 uses + (`perf::a_rename_before_and_after`, + `perf::a_will_rename_before_and_after`), with the OpenTitan column and + the parity/equality sweeps taken by throwaway probes against the local + checkout and deleted. - [ ] **Round 1's second open TODO, restated and still open:** memory. Nothing in the repo measures resident size. Round 2 added no data structure — two free functions and no state — so the figure it would @@ -589,6 +677,47 @@ copy in `tests/e2e.rs` — a binary crate's modules are not reachable from an integration test — and the two must stay the same shape or the in-crate table and the over-the-wire table stop being readable against one another. +**2026-08-28 — dev (round 7, Lane A).** Two probes added, +`a_rename_before_and_after` and `a_will_rename_before_and_after`, both over +the same 500-file generated corpus `a_code_action_at_an_instantiation_before_and_after` +uses — factored into `rename_corpus` so the three read against one another. +Each prints a before column computed the way the handler computed it until +this round (`vlog_refactor::rename` over `ws.sources()`) and an after column +that calls the real handler, so the comparison is one workspace, one cursor, +one run. + +The OpenTitan column of round 7's table came from throwaway probes against +the owner's local checkout, run and deleted — no test may depend on a +checkout this repository does not carry. Three of them: the timings, a +**parity sweep** over every 7th byte of `tb.sv` comparing +`prepare_rename_here` against `prepare_rename` (564 offsets, all identical, +zero deferrals), and an **equality sweep** over four real cursors comparing +the fan-out rename against the whole-workspace one. The last is what earned +its keep: it showed the edit sets byte-identical everywhere (7 files at `aes`, +114 at `clk_rst_if`, 4 at `.clk_i`) and the capture refusal firing verbatim on +`aes` → `prim_fifo_sync`, **and** it found the one thing the synthetic suite +could not — the macro-invocation warnings the fan-out cannot see. That finding +is written up in `docs/features/refactor-rename/README.md`; it is also why the +`` `define`` rung of the fan-out is a walk over the index's tables rather than +a `find_define` lookup, which recovered two of the five warnings the +`clk_rst_if` cursor was losing. + +Note on `a_rename_before_and_after`'s before column: it is ~480 ms rather than +the 249 ms `a_code_action_…` records for `prepare_rename` on the same corpus, +because a rename does the analysis twice — once to collect, once to verify — +where a prepare stops after locating the cursor. Both rows are printed by the +same run so neither has to be trusted from memory. + +**2026-08-28 — dev (round 7 rework).** QA found a lost refusal in the fan-out +and the lead ruled it not shippable; the fix added a sixth rung +(`WorkspaceIndex::files_spelling`) whose cost, unlike the other five, grows +with the workspace rather than with the symbol. So `a_rename_before_and_after` +grew two lines — the whole file-set build, and that rung on its own — because +"the rung is free" is a claim, and a claim in this document needs a number +beside it. Every figure in round 7's tables was re-taken against the reworked +code rather than carried over; the pre-rework numbers are quoted underneath so +the rung's cost can be read as a difference as well as directly. + ## QA log **2026-08-28 — QA.** No findings — every number reproduces within reason.