Files
lucisv/crates/lucisv_server/src/rename.rs
T

1288 lines
63 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! `textDocument/prepareRename` and `textDocument/rename`.
//!
//! Protocol only: every edit is computed by `vlog_refactor` over the same file
//! set the workspace index was built from, and this module turns the result
//! into a `WorkspaceEdit` (or the refusal into a request error). Nothing here
//! decides what may be renamed — a second opinion would be a second engine.
// A `WorkspaceEdit`'s `changes` map is keyed by `lsp_types::Uri`, and that
// type carries a `Cell` for its own parse cache — interior mutability clippy
// cannot tell apart from a key that can change its hash. The cache does not
// participate in `Hash` or `Eq`, and the map's shape is the protocol's, not
// ours.
#![allow(clippy::mutable_key_type)]
use std::collections::HashMap;
use std::path::PathBuf;
use lsp_types::{PrepareRenameResponse, TextEdit, Uri, WorkspaceEdit};
use vlog_parser::LineIndex;
use vlog_semantic::FileFacts;
use crate::convert::Positions;
use crate::locate::display_name;
use crate::rename_trace::SelectionTrace;
use crate::state::Workspace;
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<PrepareRenameResponse, String> {
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
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,
})
}
/// The whole rename as a `WorkspaceEdit`, plus whatever the engine wants the
/// user told. An `Err` is the engine's own sentence, returned verbatim.
/// `trace` is filled whenever the request got as far as asking the engine,
/// refusals included, because a rename that refuses after 800 ms is exactly
/// the kind this exists to explain (take 5 §P2a). Its two halves are the
/// server's ([`SelectionTrace`]: which rung wanted which file) and the
/// engine's ([`vlog_refactor::RenameTrace`]: where the time and the parses
/// went); it reaches a user only through `--verbose`'s `timing:` channel, and
/// a caller that wants none passes `&mut None`.
pub fn rename_traced(
ws: &Workspace,
uri: &Uri,
offset: u32,
new_name: &str,
trace: &mut Option<String>,
) -> Result<(WorkspaceEdit, Vec<String>), String> {
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
// The engine's own first look at the request, over the buffer it is about
// to be handed anyway. It refuses only what `vlog_refactor::rename` is
// certain to refuse in the same words — so this is still one voice
// deciding, just asked before the workspace is materialized for it. A
// cursor on nothing used to read, parse and index all 3 976 files before
// saying so (take 5 review §3 item 6); now it reads none.
//
// Sound because both selectors below hand the engine this very buffer, so
// the out-of-scope refusal that outranks a cursor refusal cannot fire.
//
// A refusal here still writes a trace, because "where did the time go" is
// a question about the fast refusals too — and the answer, nowhere, is
// only believable if the line says `selected=0` and `parses=0` in the same
// fields the slow road fills.
if let Err(refusal) = vlog_refactor::rename_preflight(&doc.semantics, offset, new_name) {
let (selection, engine) =
(SelectionTrace::default(), vlog_refactor::RenameTrace::default());
*trace = Some(format!("{} {} preflight=true", selection.line(), engine.line()));
return Err(refusal);
}
// 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 old_name = vlog_refactor::rename_name_at(&doc.semantics, offset);
let (sources, selection) = match &old_name {
Some(name) => ws.rename_sources_traced(&path, name, Some(new_name)),
None => {
let all = ws.sources();
let selection = SelectionTrace::whole_scope(all.len(), 0.0);
(all, selection)
}
};
let mut engine = vlog_refactor::RenameTrace::default();
let known = Known(ws);
let outcome =
vlog_refactor::rename_traced_with(&sources, &path, offset, new_name, &known, &mut engine);
*trace = Some(format!("{} {}", selection.line(), engine.line()));
let refactoring = outcome?;
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
for (path, edits) in &refactoring.edits {
// The engine edited the text `sources()` handed it, which is the open
// buffer's when there is one — the same precedence every other
// cross-file answer uses, so the ranges are never computed against
// text nobody has.
let (Some(target), Some(text)) = (path_to_uri(path), ws.text_of(path)) else {
return Err(format!(
"lucisv could not address {} as a document; no edits were made.",
path.display()
));
};
let index = LineIndex::new(&text);
let positions = Positions::new(&text, &index);
changes.insert(
target,
edits
.iter()
.map(|edit| TextEdit {
range: positions.range(edit.range),
new_text: edit.new_text.clone(),
})
.collect(),
);
}
let mut warnings = refactoring.warnings;
if let Some(name) = &old_name {
warnings.extend(unread_macro_warnings(ws, name, &sources));
}
Ok((WorkspaceEdit::new(changes), warnings))
}
/// The workspace answering the engine's `KnownFacts` question, and nothing
/// else: one call, to the one query that ties a record to the bytes it was
/// read off ([`Workspace::known_facts`]).
///
/// A newtype rather than an `impl` on `Workspace` so that the promise this
/// makes to `vlog_refactor` is written where a reader of the rename can see
/// it, and so that no other handler can acquire it by accident — the facts a
/// refactoring may reuse are the facts of the very texts it was handed, which
/// is a property of *this* call site.
struct Known<'a>(&'a Workspace);
impl vlog_refactor::KnownFacts for Known<'_> {
fn facts_for(&self, path: &std::path::Path, text: &str) -> Option<FileFacts> {
self.0.known_facts(path, text)
}
}
/// One sentence per file that writes the old name inside a macro invocation,
/// a directive line or an attribute and was **not** among the files the engine
/// was handed.
///
/// The engine warns about a macro argument in every file it reads, but the
/// fan-out that decides which files those are has no rung for a file whose
/// only relationship to the name is that text — deliberately: the census of
/// every file merely *spelling* `clk` is untagged, and a rung on it would
/// re-read the workspace and bring back the 2.5–3.0 s cost
/// `prepare_rename_here` removed (`docs/topo.md` §2.9-18). So the index
/// answers the narrower question instead — which files name it in text
/// nothing can edit — off a table it already holds, reading no file and
/// parsing nothing. The rename stays as fast as it was and stops being silent
/// about the one shape it cannot see.
///
/// Subtracting the handed set leaves out every open buffer too, because
/// [`Workspace::rename_sources_traced`] puts every open buffer in it.
fn unread_macro_warnings(ws: &Workspace, name: &str, sources: &[(PathBuf, String)]) -> Vec<String> {
let index = ws.index();
index
.files_naming_in_macros(name)
.filter_map(|file| index.path(file))
.filter(|path| !sources.iter().any(|(handed, _)| handed == path))
.map(|path| {
format!(
"`{name}` also appears inside a macro invocation in {}, which this rename did not read; check it by hand — a macro argument cannot be edited.",
display_name(path)
)
})
.collect()
}
const UNSAVED: &str = "lucisv can only rename inside a saved file.";
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::path::{Path, PathBuf};
use std::str::FromStr;
/// [`rename_traced`] with the trace thrown away — what a test that is not
/// about the trace asks.
fn rename(
ws: &Workspace,
uri: &Uri,
offset: u32,
new_name: &str,
) -> Result<(WorkspaceEdit, Vec<String>), String> {
rename_traced(ws, uri, offset, new_name, &mut None)
}
/// A scratch workspace root. Removed on drop.
struct Tree {
path: PathBuf,
}
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("lucisv_server_rename_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
fn write(&self, rel: &str, text: &str) -> PathBuf {
let path = self.path.join(rel);
fs::write(&path, text).expect("write");
path
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
fn at(text: &str, needle: &str) -> u32 {
text.find(needle).expect("needle present") as u32
}
const SUB: &str = "module sub (input logic clk);\nendmodule\n";
const TOP: &str = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n";
/// A two-file workspace with `top.sv` open.
fn opened(tree: &Tree) -> (Workspace, Uri) {
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", TOP);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), TOP.to_string());
(ws, uri)
}
/// A third file that spells nothing this rename is about, kept open so
/// the open-buffer rung selects it: the "container" class in miniature —
/// a file the engine must index and never analyses.
const BYSTANDER: &str = "module bystander;\n logic unrelated;\nendmodule\n";
/// `sub.sv`, `top.sv` and `quiet.sv`, with the last two open and a
/// persistent index store behind the workspace — so a rename is handed
/// records keyed on the very bytes it reads.
fn three_with_store(tree: &Tree, store: Option<&Tree>) -> (Workspace, Uri) {
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", TOP);
let quiet = tree.write("bystander.sv", BYSTANDER);
let mut ws = Workspace::default();
ws.set_client_settings(crate::settings::ClientSettings {
index_cache_path: store.map(|s| s.path.to_string_lossy().into_owned()),
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
});
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), TOP.to_string());
ws.set_document(path_to_uri(&quiet).expect("uri"), BYSTANDER.to_string());
(ws, uri)
}
/// Every edit and every warning one rename produced, with the workspace's
/// own scratch path taken out — the fingerprint the parity proof compares.
fn print(result: &(WorkspaceEdit, Vec<String>), root: &Path) -> String {
let (edit, warnings) = result;
let mut lines: Vec<String> = Vec::new();
for (uri, edits) in edit.changes.iter().flatten() {
for one in edits {
lines.push(format!(
"{} {:?}..{:?} -> {}",
uri.as_str(),
one.range.start,
one.range.end,
one.new_text
));
}
}
lines.sort();
lines.extend(warnings.iter().map(|w| format!("warn {w}")));
lines.join("\n").replace(root.to_str().expect("utf-8"), "")
}
/// **§R3b's server-side proof.** The same rename over the same files, once
/// with a warm index store behind it — where the engine is handed every
/// file's record and stops parsing the ones nothing analyses — and once
/// with no store at all, where it parses them all: byte-identical edits,
/// byte-identical warnings.
///
/// The reuse is asserted to have happened *and* to have removed a parse,
/// so a store that silently stopped answering would fail this rather than
/// pass it for the wrong reason.
#[test]
fn a_rename_over_a_warm_store_says_exactly_what_one_with_no_store_says() {
let tree = Tree::new("reuse_store");
let store = Tree::new("reuse_store_cache");
let (warm, uri) = three_with_store(&tree, Some(&store));
let mut line = None;
let with_store = rename_traced(&warm, &uri, at(TOP, "clk"), "clk_x", &mut line)
.expect("the rename succeeds");
let trace = line.expect("a trace is always written");
assert!(trace.contains("selected=3"), "all three files are selected: {trace}");
assert!(trace.contains("reused_files=3"), "and every record came from the store: {trace}");
assert!(trace.contains("other_files=1"), "bystander.sv is the unread one: {trace}");
assert!(trace.contains("parses{index=2"), "so only the two analysed files: {trace}");
let bare = Tree::new("reuse_none");
let (plain, plain_uri) = three_with_store(&bare, None);
let mut plain_line = None;
let no_store = rename_traced(&plain, &plain_uri, at(TOP, "clk"), "clk_x", &mut plain_line)
.expect("the rename succeeds");
let plain_trace = plain_line.expect("a trace is always written");
assert!(plain_trace.contains("reused_files=0"), "premise: no store, no reuse");
assert!(plain_trace.contains("parses{index=3"), "premise: all three parsed");
assert_eq!(
print(&with_store, &tree.path),
print(&no_store, &bare.path),
"the reuse changed an edit or a warning"
);
}
/// **Unsaved-buffer precedence, for free.** A buffer whose text disagrees
/// with the file on disk is not the bytes any record was written from, so
/// the store answers nothing for it and it is parsed — and the rename acts
/// on the buffer's text, which is the precedence it always had.
///
/// Nothing in the reuse arranges this: the key is the content, so unsaved
/// text misses the same way changed text does.
#[test]
fn an_unsaved_buffer_is_parsed_and_renamed_from_its_own_text() {
let tree = Tree::new("reuse_unsaved");
let store = Tree::new("reuse_unsaved_cache");
let (mut ws, uri) = three_with_store(&tree, Some(&store));
// A signal that exists only in the buffer. Its record cannot be in a
// store keyed on what is on disk.
let edited = "module top;\n logic only_here;\n sub u_sub (.clk(only_here));\nendmodule\n";
ws.set_document(uri.clone(), edited.to_string());
let mut line = None;
let (edit, _) = rename_traced(&ws, &uri, at(edited, "only_here"), "renamed", &mut line)
.expect("the buffer's own declaration renames");
let trace = line.expect("a trace is always written");
assert!(trace.contains("reused_files=1"), "only the untouched buffer's record: {trace}");
assert!(trace.contains("lead=0.0ms") || trace.contains("parses{index=1"), "{trace}");
let edits = edit.changes.as_ref().expect("changes").values().flatten().count();
assert_eq!(edits, 2, "the declaration and its one use, both in the buffer");
}
#[test]
fn prepare_offers_the_identifier_and_its_placeholder() {
let tree = Tree::new("prepare");
let (ws, uri) = opened(&tree);
let response = prepare(&ws, &uri, at(TOP, "u_sub")).expect("renameable");
let PrepareRenameResponse::RangeWithPlaceholder { range, placeholder } = response else {
panic!("a placeholder is what an editor wants");
};
assert_eq!(placeholder, "u_sub");
assert_eq!(range.start.line, 1);
assert_eq!(range.start.character, 6);
assert_eq!(range.end.character, 11);
}
#[test]
fn prepare_declines_where_there_is_nothing_to_rename() {
let tree = Tree::new("prepare_no");
let (ws, uri) = opened(&tree);
let message = prepare(&ws, &uri, at(TOP, "module")).expect_err("a keyword");
assert!(message.contains("no symbol to rename"), "{message}");
}
#[test]
fn prepare_declines_in_an_untitled_buffer() {
let mut ws = Workspace::default();
let uri = Uri::from_str("untitled:Untitled-1").expect("uri");
ws.set_document(uri.clone(), "module m;\n wire a;\nendmodule\n".to_string());
assert_eq!(prepare(&ws, &uri, 16).expect_err("no path"), UNSAVED);
}
#[test]
fn a_rename_edits_every_file_that_names_the_symbol() {
let tree = Tree::new("cross");
let (ws, uri) = opened(&tree);
let (edit, warnings) = rename(&ws, &uri, at(TOP, "sub u_sub"), "child").expect("renames");
assert!(warnings.is_empty(), "{warnings:?}");
let changes = edit.changes.expect("changes");
assert_eq!(changes.len(), 2, "the declaration's file and this one");
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
let sub_edits = changes.get(&sub_uri).expect("sub.sv is edited");
assert_eq!(sub_edits.len(), 1);
assert_eq!(sub_edits[0].new_text, "child");
assert_eq!(sub_edits[0].range.start.line, 0);
assert_eq!(sub_edits[0].range.start.character, 7, "the name `sub`");
let top_edits = changes.get(&uri).expect("top.sv is edited");
assert_eq!(top_edits.len(), 1);
assert_eq!(top_edits[0].range.start.line, 1);
assert_eq!(top_edits[0].range.start.character, 2);
}
#[test]
fn a_refused_rename_returns_the_engines_sentence() {
let tree = Tree::new("refused");
let (ws, uri) = opened(&tree);
let message = rename(&ws, &uri, at(TOP, "u_sub"), "module").expect_err("a keyword");
assert!(message.contains("keyword"), "{message}");
}
#[test]
fn ranges_are_utf16_in_a_file_with_multi_byte_text() {
let tree = Tree::new("utf16");
let text = "module m;\n // é 🎉\n wire a;\n assign a = 1;\nendmodule\n";
let file = tree.write("m.sv", text);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text.to_string());
let (edit, _) = rename(&ws, &uri, at(text, "wire a") + 5, "sig").expect("renames");
let mut changes = edit.changes.expect("changes");
let edits = changes.remove(&uri).expect("this file");
assert_eq!(edits.len(), 2);
assert_eq!(edits[0].range.start.line, 2);
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<PathBuf> {
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_traced(path, &name, Some(new_name)).0,
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<vlog_refactor::RefactorEdit, String> {
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_traced(path, &name, Some(new_name)).0,
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<PathBuf>) {
let paths: Vec<PathBuf> = 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.
///
/// The symbol is a **function's** local, not a module's net: since
/// 2026-09-05 a net is a declaration on the module's hierarchical surface
/// and joins the fan-out by that rung (the test below), which would answer
/// this one for the wrong reason. A name inside a subprogram body is on
/// neither surface, which is what this attack needs.
#[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 function automatic int f();\n int taken_local = 0;\n return taken_local;\n endfunction\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());
}
/// The rung the hierarchical surface added: a module's internal **net**
/// spelled like the new name *is* a declaration the fan-out has to hold,
/// because `assign w = u_unrelated.taken_net;` in a fourth file resolves
/// to it now. So the file is pulled in — and the rename still succeeds
/// and still writes nothing there, because a package name and a net
/// inside a module capture nothing of each other.
#[test]
fn a_module_net_sharing_the_new_names_spelling_joins_the_fan_out_and_refuses_nothing() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const NET_ONLY: &str =
"module unrelated;\n wire taken_net;\n assign taken_net = 1'b0;\nendmodule\n";
let tree = Tree::new("fanout_hierarchical_net");
let files = [("pkg.sv", PKG), ("net.sv", NET_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_net");
assert!(
fan.contains(&tree.path.join("net.sv")),
"a net is a hierarchical declaration of its name: {fan:?}"
);
let edit = same_answer(&ws, &path, at, "taken_net").expect("renames, no capture possible");
assert!(edit.edits_for(&tree.path.join("net.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");
tree.write("sub.sv", SUB);
let top_path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
// The buffer instantiates `sub`; the file on disk does not.
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), TOP.to_string());
let (edit, _) = rename(&ws, &uri, at(TOP, "sub u_sub"), "child").expect("renames");
let changes = edit.changes.expect("changes");
assert_eq!(changes.get(&uri).map(Vec::len), Some(1), "the buffer's instantiation");
}
/// `sub.sv` declares the port, `top.sv` connects it, and `far.svh` names
/// it inside a macro invocation and has no other relationship to anything
/// in the rename — so the fan-out does not hand it to the engine and the
/// engine cannot warn about it. The census does: §2.9-18's server half.
const M_SUB: &str = "module sub (output logic sig);\n assign sig = 1'b0;\nendmodule\n";
const M_TOP: &str = "module top;\n logic w;\n sub u_sub (.sig(w));\nendmodule\n";
const M_FAR: &str = "`uvm_info(\"x\", $sformatf(\"%0d\", sig), UVM_LOW)\n";
/// The workspace of the two pins below, with `top.sv` open. `far` is what
/// `far.svh` holds, which is the only difference between them.
fn macro_workspace(tree: &Tree, far: &str) -> (Workspace, Uri) {
tree.write("sub.sv", M_SUB);
let top = tree.write("top.sv", M_TOP);
tree.write("far.svh", far);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), M_TOP.to_string());
(ws, uri)
}
/// How often a warning naming `far.svh` is in the list.
fn far_warnings(warnings: &[String]) -> usize {
warnings.iter().filter(|w| w.contains("far.svh")).count()
}
#[test]
fn a_file_that_only_names_the_symbol_in_a_macro_is_warned_about_unread() {
let tree = Tree::new("macrocensus");
let (ws, uri) = macro_workspace(&tree, M_FAR);
// The premise: `far.svh` is in no rung of the fan-out, so the engine
// never sees it. Asked of the same function `rename` asks.
let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0;
assert!(
!handed.iter().any(|(path, _)| path.ends_with("far.svh")),
"premise: the engine is not handed far.svh — {handed:?}"
);
let (edit, warnings) = rename(&ws, &uri, at(M_TOP, "sig(w)"), "probe").expect("renames");
let changes = edit.changes.expect("changes");
assert_eq!(changes.len(), 2, "the declaration's file and the connection's");
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
assert_eq!(changes.get(&sub_uri).map(Vec::len), Some(2), "the port and its assignment");
assert_eq!(changes.get(&uri).map(Vec::len), Some(1), "the `.sig(` connection");
assert!(
!changes.contains_key(&path_to_uri(&tree.path.join("far.svh")).expect("uri")),
"a macro argument is never edited"
);
assert_eq!(far_warnings(&warnings), 1, "{warnings:?}");
let warning = warnings.iter().find(|w| w.contains("far.svh")).expect("named");
assert!(warning.contains("`sig`"), "{warning}");
assert!(warning.contains("this rename did not read"), "{warning}");
assert!(warning.contains("a macro argument cannot be edited"), "{warning}");
}
/// The control: give `far.svh` a reason to be read — it instantiates
/// `sub` — and it *is* a source, so the engine's own macro-argument
/// warning covers it and this one must stay quiet. Exactly one warning
/// names the file either way; two would be the bug.
#[test]
fn a_macro_file_the_rename_does_read_is_warned_about_exactly_once() {
let tree = Tree::new("macrocontrol");
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {M_FAR}endmodule\n");
let (ws, uri) = macro_workspace(&tree, &far);
let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0;
assert!(
handed.iter().any(|(path, _)| path.ends_with("far.svh")),
"premise: instantiating `sub` puts far.svh in the source set"
);
let (_, warnings) = rename(&ws, &uri, at(M_TOP, "sig(w)"), "probe").expect("renames");
assert_eq!(far_warnings(&warnings), 1, "no double warning: {warnings:?}");
let warning = warnings.iter().find(|w| w.contains("far.svh")).expect("named");
assert!(
warning.contains("one opaque token"),
"and it is the engine's sentence, not the census's: {warning}"
);
}
// ------------------------------------------------------------------
// The engine-owned preflight (take 5 review §3 item 6, TODO §61.1)
// ------------------------------------------------------------------
/// A cursor on nothing used to select every in-scope file, parse all of
/// them and index them before the engine's 0.1 ms refusal. The preflight
/// is only worth having if that is now literally no parses at all — not
/// fewer, none — so the gate is asserted, not measured.
#[test]
fn a_rename_on_a_cursor_with_no_symbol_parses_nothing() {
let tree = Tree::new("nosymbolparses");
let (ws, uri) = opened(&tree);
let at_comment = TOP.len() as u32 - 1; // the newline after `endmodule`
let before = vlog_parser::stats::parses();
let mut trace = None;
let refusal =
rename_traced(&ws, &uri, at_comment, "probe", &mut trace).expect_err("no symbol there");
let parses = vlog_parser::stats::parses() - before;
assert_eq!(parses, 0, "the refusal parsed {parses} whole files");
assert_eq!(refusal, "there is no symbol to rename at this position.");
// And the `--verbose` channel says so in its own fields, so the phase
// that measures this row reads the parse count instead of trusting it.
let trace = trace.expect("a refusal traces too");
assert!(trace.contains("selected=0"), "{trace}");
assert!(trace.contains("parses=0"), "{trace}");
assert!(trace.contains("preflight=true"), "{trace}");
}
/// …and it is the same sentence the whole workspace produced, taken from
/// the engine over every in-scope file rather than from this module.
#[test]
fn the_preflights_refusal_is_the_whole_workspaces_refusal() {
let tree = Tree::new("preflightparity");
let (ws, uri) = opened(&tree);
let path = tree.path.join("top.sv");
for (case, offset) in [
("past the last item", TOP.len() as u32 - 1),
("on the `module` keyword", at(TOP, "module")),
("on a literal", at(TOP, "1'b0")),
] {
let fast = rename(&ws, &uri, offset, "probe").expect_err(case);
let slow = vlog_refactor::rename(&ws.sources(), &path, offset, "probe")
.expect_err("the whole workspace refuses too");
assert_eq!(fast, slow, "{case}");
}
}
/// Precedence, in the two places the preflight could have disturbed it: an
/// unusable buffer is refused by this module before the engine is asked
/// anything, and an invalid new name outranks whatever the cursor is on.
#[test]
fn the_preflight_does_not_disturb_the_refusal_order() {
let tree = Tree::new("preflightorder");
let (ws, uri) = opened(&tree);
let untitled = Uri::from_str("untitled:Untitled-1").expect("uri");
let mut with_untitled = Workspace::default();
with_untitled.set_document(untitled.clone(), TOP.to_string());
assert_eq!(
rename(&with_untitled, &untitled, at(TOP, "u_sub"), "probe").expect_err("unsaved"),
UNSAVED,
"an untitled buffer is refused before the engine sees the cursor"
);
// A cursor on nothing *and* a keyword for a new name: the name's
// sentence, which is the one `renaming` reaches first.
let refusal = rename(&ws, &uri, TOP.len() as u32 - 1, "module").expect_err("a keyword");
assert_eq!(refusal, "`module` is a Verilog keyword.");
}
/// The one buffer the preflight must never judge: on the large-file fast
/// path every field but the text is the analysis of the *empty* file, so a
/// preflight over it would refuse every cursor as symbolless. The
/// large-buffer gate refuses the whole request first, and this pins that
/// it still does.
#[test]
fn a_large_buffer_is_refused_before_the_preflight_could_see_it() {
let tree = Tree::new("preflightlarge");
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", TOP);
let mut ws = Workspace::default();
ws.set_client_settings(crate::settings::ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
large_file_threshold: 1,
..Default::default()
});
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), TOP.to_string());
let doc = ws.document(&uri).expect("open");
assert!(doc.large, "premise: the buffer took the fast path");
assert!(
vlog_refactor::rename_preflight(&doc.semantics, at(TOP, "u_sub"), "probe").is_err(),
"premise: the empty analysis would refuse a real cursor, which is why \
`server/large_file.rs` must answer this method before we are reached"
);
}
}