prepareRename answered F2 by reading every in-scope file (1.6-3.0 s on opentitan, blocking the loop); it now answers from the open buffer and the index in 139 ns, with a refusal-by-refusal parity table (7 reproduced, 4 deferred to rename, none lost). rename computes over rename_sources — declarers, reference postings, open buffers, and, after QA's HIGH finding gated the round, rung 6: files_spelling over the index's reference facts (resolved or not, FACTS_FORMAT untouched), restoring the dangling-new-name capture refusal the first five rungs lost; the old name needs no rung and the argument is written and pinned, QA's shadowing hunt included. 3.47 s -> 105 ms at a 7-file fan-out, rung cost 852 us worst-case, byte-parity swept at four real cursors and 564 offsets, ambiguity escaping to the whole scope. willRenameFiles rides IncludeGraph::includers(): 249 ms -> 14 ms over 331 includers of 3 976 files. Accepted residue, documented: files whose only mention of the name is inside opaque macro tokens lose one warning flavour; the FileFacts macro census is filed as the real fix. Dev Opus + QA Sonnet (REWORK-gate, fix, SHIP on re-verify) in a dedicated worktree. Lead-reviewed and merged. Co-Authored-By: Claude Fable 5 <[email protected]>
1023 lines
44 KiB
Rust
1023 lines
44 KiB
Rust
//! Rename: the first refactoring, and the shape every later one follows.
|
||
//!
|
||
//! Read top-to-bottom, a rename is five steps: check the new name, resolve the
|
||
//! cursor to a *declaration*, collect every reference to that declaration in
|
||
//! the in-scope files, verify the whole edit in memory, and describe what was
|
||
//! deliberately left alone. Any step may refuse, and a refusal is a sentence
|
||
//! for the user, never a partial edit.
|
||
|
||
use std::collections::HashMap;
|
||
use std::path::{Path, PathBuf};
|
||
|
||
use vlog_parser::defines::DefineKind;
|
||
use vlog_parser::span::TextRange;
|
||
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, Symbol, SymbolId, WorkspaceIndex,
|
||
};
|
||
|
||
use crate::{check, RefactorEdit, TextEdit};
|
||
|
||
/// The identifier a rename would act on: where it is, and what it spells.
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
pub struct RenameTarget {
|
||
/// The identifier under the cursor, in the file the request named.
|
||
pub range: TextRange,
|
||
/// Its current name — the editor's rename-box placeholder.
|
||
pub name: String,
|
||
}
|
||
|
||
/// Whether the symbol at `offset` can be renamed, and where its identifier is.
|
||
///
|
||
/// This is LSP's `textDocument/prepareRename`: it applies every refusal that
|
||
/// does not need to know the new name, so an editor never opens a rename box
|
||
/// for a rename [`rename`] would then decline.
|
||
pub fn prepare_rename(
|
||
files: &[(PathBuf, String)],
|
||
file: &Path,
|
||
offset: u32,
|
||
) -> Result<RenameTarget, String> {
|
||
let mut scope = Scope::build(files);
|
||
let target = scope.locate(file, offset)?;
|
||
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<RenameTarget, String> {
|
||
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<String> {
|
||
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`.
|
||
///
|
||
/// `files` is the in-scope set — path and current text, open buffers already
|
||
/// overlaying disk — exactly what the workspace index was built from. Errors
|
||
/// are sentences meant for the user; an `Ok` result is verified and complete.
|
||
pub fn rename(
|
||
files: &[(PathBuf, String)],
|
||
file: &Path,
|
||
offset: u32,
|
||
new_name: &str,
|
||
) -> Result<RefactorEdit, String> {
|
||
check_new_name(new_name)?;
|
||
let mut scope = Scope::build(files);
|
||
let target = scope.locate(file, offset)?;
|
||
if target.name == new_name {
|
||
return Err(format!("`{new_name}` is the name it already has."));
|
||
}
|
||
let edits = scope.collect_edits(&target, new_name)?;
|
||
check::verify(&mut scope, &edits, &target.name, new_name)?;
|
||
|
||
let warnings = scope.warnings(&target, &edits);
|
||
let mut out: Vec<(PathBuf, Vec<TextEdit>)> = edits
|
||
.into_iter()
|
||
.filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), edits)))
|
||
.collect();
|
||
out.sort_by(|a, b| a.0.cmp(&b.0));
|
||
Ok(RefactorEdit { edits: out, warnings })
|
||
}
|
||
|
||
/// A new name must lex as exactly one identifier and must not be a keyword.
|
||
/// Anything else would be a textual edit that happens to look like a rename.
|
||
fn check_new_name(new_name: &str) -> Result<(), String> {
|
||
if new_name.is_empty() {
|
||
return Err("a new name cannot be empty.".to_string());
|
||
}
|
||
// Keywords first: they lex fine, just not as identifiers, and "`module`
|
||
// is a Verilog keyword" is a better sentence than "not an identifier".
|
||
if is_keyword(new_name) {
|
||
return Err(format!("`{new_name}` is a Verilog keyword."));
|
||
}
|
||
let refusal = format!("`{new_name}` is not a valid Verilog identifier.");
|
||
let Ok(tokens) = tokenize(new_name) else {
|
||
return Err(refusal);
|
||
};
|
||
// `tokenize` always ends the stream with an `Eof` token.
|
||
let [name, end] = tokens.as_slice() else {
|
||
return Err(refusal);
|
||
};
|
||
if end.kind != TokenKind::Eof || name.kind != TokenKind::Ident || name.text != new_name {
|
||
return Err(refusal);
|
||
}
|
||
// A macro usage lexes as an identifier that starts with a backtick.
|
||
if new_name.starts_with('`') {
|
||
return Err(refusal);
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// One file's two analysis layers, as `textDocument/definition` uses them.
|
||
pub(crate) struct Analysis {
|
||
pub(crate) semantics: Semantics,
|
||
pub(crate) external: ExternalResolutions,
|
||
}
|
||
|
||
/// What the cursor turned out to sit on, before the scope is borrowed again.
|
||
enum Found {
|
||
/// A declaration in the file the request named.
|
||
Here(SymbolId, TextRange),
|
||
/// A use whose declaration the workspace overlay must supply.
|
||
Elsewhere(String, TextRange, Option<ExternalTarget>),
|
||
}
|
||
|
||
/// The declaration a rename acts on, and where the cursor sat.
|
||
pub(crate) struct Target {
|
||
/// Index into [`Scope::sources`] of the file holding the declaration.
|
||
pub(crate) file: usize,
|
||
pub(crate) symbol: SymbolId,
|
||
pub(crate) name: String,
|
||
/// The identifier under the cursor, in the file the request named.
|
||
pub(crate) cursor: TextRange,
|
||
}
|
||
|
||
/// The in-scope files, the index built from them, and the analyses computed so
|
||
/// far. Analyses are built on demand: a rename usually needs a handful of the
|
||
/// workspace's files, and analyzing the rest would be pure cost.
|
||
pub(crate) struct Scope<'a> {
|
||
/// Path and text, sorted by path and deduplicated the way
|
||
/// `WorkspaceIndex::build` does it, so index `i` and `FileId(i)`'s texts
|
||
/// agree.
|
||
sources: Vec<(&'a Path, &'a str)>,
|
||
index: WorkspaceIndex,
|
||
/// Source index → the index's own file id.
|
||
file_ids: Vec<Option<FileId>>,
|
||
cache: HashMap<usize, Analysis>,
|
||
}
|
||
|
||
impl<'a> Scope<'a> {
|
||
pub(crate) fn build(files: &'a [(PathBuf, String)]) -> Scope<'a> {
|
||
let mut sources: Vec<(&Path, &str)> =
|
||
files.iter().map(|(p, t)| (p.as_path(), t.as_str())).collect();
|
||
// The same normalization `WorkspaceIndex::build` applies: a stable
|
||
// sort by path, then the first copy of a repeated path wins.
|
||
sources.sort_by(|a, b| a.0.cmp(b.0));
|
||
sources.dedup_by(|a, b| a.0 == b.0);
|
||
|
||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.to_path_buf(), *t)));
|
||
let ids: HashMap<&Path, FileId> = index
|
||
.files()
|
||
.iter()
|
||
.enumerate()
|
||
.map(|(i, path)| (path.as_path(), FileId(i as u32)))
|
||
.collect();
|
||
let file_ids = sources.iter().map(|(path, _)| ids.get(path).copied()).collect();
|
||
Scope { sources, index, file_ids, cache: HashMap::new() }
|
||
}
|
||
|
||
pub(crate) fn len(&self) -> usize {
|
||
self.sources.len()
|
||
}
|
||
|
||
pub(crate) fn path(&self, i: usize) -> Option<&'a Path> {
|
||
self.sources.get(i).map(|(path, _)| *path)
|
||
}
|
||
|
||
pub(crate) fn text(&self, i: usize) -> Option<&'a str> {
|
||
self.sources.get(i).map(|(_, text)| *text)
|
||
}
|
||
|
||
pub(crate) fn sources(&self) -> &[(&'a Path, &'a str)] {
|
||
&self.sources
|
||
}
|
||
|
||
fn file_id(&self, i: usize) -> Option<FileId> {
|
||
self.file_ids.get(i).copied().flatten()
|
||
}
|
||
|
||
pub(crate) fn index_of(&self, path: &Path) -> Option<usize> {
|
||
self.sources.iter().position(|(p, _)| *p == path)
|
||
}
|
||
|
||
/// The two analysis layers for one file, computed on first use.
|
||
pub(crate) fn analysis(&mut self, i: usize) -> Option<&Analysis> {
|
||
let Scope { sources, index, cache, .. } = self;
|
||
let text = sources.get(i).map(|(_, text)| *text)?;
|
||
Some(cache.entry(i).or_insert_with(|| {
|
||
let semantics = analyze(&parse_source_tolerant(text).0, text);
|
||
let external = resolve_external(&semantics, index);
|
||
Analysis { semantics, external }
|
||
}))
|
||
}
|
||
|
||
/// One file's analysis, but only if it has already been computed — what
|
||
/// the verification pass reads while it also holds the index.
|
||
pub(crate) fn cached(&self, i: usize) -> Option<&Analysis> {
|
||
self.cache.get(&i)
|
||
}
|
||
|
||
/// Resolve a cursor position to the declaration a rename must act on.
|
||
///
|
||
/// The cursor may sit on the declaration itself, on a use in the same
|
||
/// file, or on a use whose declaration lives in another file — all three
|
||
/// end here, which is what makes renaming from a reference identical to
|
||
/// renaming from the declaration.
|
||
pub(crate) fn locate(&mut self, file: &Path, offset: u32) -> Result<Target, String> {
|
||
let Some(here) = self.index_of(file) else {
|
||
return Err(format!(
|
||
"{} is not one of the files lucisv indexes; nothing outside the project scope can be renamed.",
|
||
display(file)
|
||
));
|
||
};
|
||
// The analysis borrow is confined to this block so the two
|
||
// `declaration*` calls below can take the scope mutably again.
|
||
let found = {
|
||
let Some(analysis) = self.analysis(here) else {
|
||
return Err("the file could not be analyzed.".to_string());
|
||
};
|
||
let semantics = &analysis.semantics;
|
||
match semantics
|
||
.reference_id_at(offset)
|
||
.and_then(|id| Some((id, semantics.reference(id)?)))
|
||
{
|
||
Some((id, reference)) => {
|
||
let (name, cursor) = (reference.name.clone(), reference.name_span);
|
||
match &reference.resolution {
|
||
Resolution::Resolved(symbol) => Found::Here(*symbol, cursor),
|
||
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())
|
||
}
|
||
}
|
||
}
|
||
None => match semantics.symbol_at(offset) {
|
||
Some(symbol) => {
|
||
let cursor = semantics
|
||
.symbol(symbol)
|
||
.map_or_else(|| TextRange::empty(offset), |s| s.name_span);
|
||
Found::Here(symbol, cursor)
|
||
}
|
||
None => return Err(NOTHING_HERE.to_string()),
|
||
},
|
||
}
|
||
};
|
||
match found {
|
||
Found::Here(symbol, cursor) => self.declaration(here, symbol, cursor),
|
||
Found::Elsewhere(name, cursor, target) => {
|
||
self.declaration_across_files(&name, cursor, target)
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A declaration in a known file, once the uniqueness rules have been
|
||
/// applied to it.
|
||
fn declaration(
|
||
&mut self,
|
||
file: usize,
|
||
symbol: SymbolId,
|
||
cursor: TextRange,
|
||
) -> Result<Target, String> {
|
||
let (name, name_span, at_file_scope) = {
|
||
let Some(analysis) = self.analysis(file) else {
|
||
return Err("the declaring file could not be analyzed.".to_string());
|
||
};
|
||
let Some(declaration) = analysis.semantics.symbol(symbol) else {
|
||
return Err(NOTHING_HERE.to_string());
|
||
};
|
||
(
|
||
declaration.name.clone(),
|
||
declaration.name_span,
|
||
declaration.scope == analysis.semantics.file_scope(),
|
||
)
|
||
};
|
||
if name_span.is_empty() {
|
||
return Err(unspelled(&name));
|
||
}
|
||
if at_file_scope && self.index.units(&name).len() > 1 {
|
||
return Err(ambiguous(&name));
|
||
}
|
||
Ok(Target { file, symbol, name, cursor })
|
||
}
|
||
|
||
/// The declaration a cross-file use names, through the workspace overlay.
|
||
fn declaration_across_files(
|
||
&mut self,
|
||
name: &str,
|
||
cursor: TextRange,
|
||
target: Option<ExternalTarget>,
|
||
) -> Result<Target, String> {
|
||
let def = match target {
|
||
Some(ExternalTarget::Resolved(def)) => def,
|
||
Some(ExternalTarget::Ambiguous(_)) => return Err(ambiguous(name)),
|
||
_ => 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."));
|
||
};
|
||
let found = {
|
||
let Some(analysis) = self.analysis(file) else {
|
||
return Err("the declaring file could not be analyzed.".to_string());
|
||
};
|
||
analysis.semantics.symbol_at(def.name_span.start)
|
||
};
|
||
let Some(symbol) = found else {
|
||
return Err(format!("lucisv cannot locate the declaration of `{name}`."));
|
||
};
|
||
self.declaration(file, symbol, cursor)
|
||
}
|
||
|
||
/// Where the target declaration spells its own name.
|
||
pub(crate) fn declaration_span(&mut self, target: &Target) -> Option<TextRange> {
|
||
self.analysis(target.file)
|
||
.and_then(|a| a.semantics.symbol(target.symbol).map(|s| s.name_span))
|
||
}
|
||
|
||
/// Every occurrence of the declaration in every in-scope file: its own
|
||
/// name, its in-file uses, and the cross-file uses the overlay attributes
|
||
/// to it. Per file, in the order the walk found them.
|
||
///
|
||
/// Shared with [`crate::find_references`], which wants the same set
|
||
/// without the edits: an occurrence a rename would change and a reference
|
||
/// list that does not name it would be two answers about one symbol.
|
||
pub(crate) fn collect_occurrences(
|
||
&mut self,
|
||
target: &Target,
|
||
) -> Result<Vec<(usize, Vec<TextRange>)>, String> {
|
||
let Some(def_file) = self.file_id(target.file) else {
|
||
return Err("the declaring file is not indexed.".to_string());
|
||
};
|
||
let Some(def_span) = self.declaration_span(target) else {
|
||
return Err(NOTHING_HERE.to_string());
|
||
};
|
||
let is_ours = |def: &Def| def.file == def_file && def.name_span == def_span;
|
||
|
||
let mut out: Vec<(usize, Vec<TextRange>)> = Vec::new();
|
||
for i in 0..self.len() {
|
||
let Some(text) = self.text(i) else { continue };
|
||
// A file that does not spell the name cannot reference it: the
|
||
// semantic layer promises every `name_span` slices back to its
|
||
// own name. This is the prefilter that keeps a rename cheap.
|
||
if !text.contains(&target.name) {
|
||
continue;
|
||
}
|
||
let Some(analysis) = self.analysis(i) else { continue };
|
||
let mut spans: Vec<TextRange> = Vec::new();
|
||
if i == target.file {
|
||
spans.push(def_span);
|
||
spans.extend(
|
||
analysis.semantics.references_of(target.symbol).iter().map(|r| r.name_span),
|
||
);
|
||
}
|
||
for (id, reference) in analysis.semantics.references().iter().enumerate() {
|
||
if reference.name != target.name {
|
||
continue;
|
||
}
|
||
match analysis.external.get(ReferenceId(id as u32)) {
|
||
Some(ExternalTarget::Resolved(def)) if is_ours(def) => {
|
||
spans.push(reference.name_span)
|
||
}
|
||
Some(ExternalTarget::Ambiguous(defs)) if defs.iter().any(is_ours) => {
|
||
return Err(ambiguous(&target.name))
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
out.push((i, spans));
|
||
}
|
||
Ok(out)
|
||
}
|
||
|
||
/// The rename's own view of [`Scope::collect_occurrences`]: the same
|
||
/// spans, checked and turned into replacements.
|
||
fn collect_edits(
|
||
&mut self,
|
||
target: &Target,
|
||
new_name: &str,
|
||
) -> Result<Vec<(usize, Vec<TextEdit>)>, String> {
|
||
let found = self.collect_occurrences(target)?;
|
||
let mut out: Vec<(usize, Vec<TextEdit>)> = Vec::new();
|
||
for (i, spans) in found {
|
||
let edits = self.edits_from_spans(i, spans, &target.name, new_name)?;
|
||
if !edits.is_empty() {
|
||
out.push((i, edits));
|
||
}
|
||
}
|
||
if out.is_empty() {
|
||
return Err(format!("lucisv found nothing to rename for `{}`.", target.name));
|
||
}
|
||
Ok(out)
|
||
}
|
||
|
||
/// Turn occurrence spans into sorted, non-overlapping edits, refusing any
|
||
/// span that does not slice back to the name it claims.
|
||
fn edits_from_spans(
|
||
&self,
|
||
file: usize,
|
||
mut spans: Vec<TextRange>,
|
||
name: &str,
|
||
new_name: &str,
|
||
) -> Result<Vec<TextEdit>, String> {
|
||
let Some(text) = self.text(file) else { return Ok(Vec::new()) };
|
||
spans.retain(|s| !s.is_empty());
|
||
spans.sort_by_key(|s| (s.start, s.end));
|
||
spans.dedup();
|
||
let mut last_end = 0u32;
|
||
for (n, span) in spans.iter().enumerate() {
|
||
if text.get(span.as_range()) != Some(name) {
|
||
return Err(format!(
|
||
"lucisv found `{name}` recorded at bytes {}..{} of {}, which does not spell it; the rename was abandoned.",
|
||
span.start,
|
||
span.end,
|
||
display(self.path(file).unwrap_or(Path::new("?")))
|
||
));
|
||
}
|
||
if n > 0 && span.start < last_end {
|
||
return Err(
|
||
"two occurrences of the name overlap; the rename was abandoned.".to_string()
|
||
);
|
||
}
|
||
last_end = span.end;
|
||
}
|
||
Ok(spans
|
||
.into_iter()
|
||
.map(|range| TextEdit { range, new_text: new_name.to_string() })
|
||
.collect())
|
||
}
|
||
|
||
/// What the rename could not account for: the name inside `` `define``
|
||
/// text, inside a macro invocation's opaque token, and identifier
|
||
/// occurrences no reference was recorded for.
|
||
fn warnings(&mut self, target: &Target, edits: &[(usize, Vec<TextEdit>)]) -> Vec<String> {
|
||
let mut warnings = self.macro_warnings(&target.name);
|
||
// Macro *invocations* are scanned in every file that spells the name,
|
||
// not only the edited ones: `` `BUMP(a) `` in a file the rename never
|
||
// touches still expands to the old name.
|
||
for i in 0..self.len() {
|
||
warnings.extend(self.macro_use_warnings(i, &target.name));
|
||
}
|
||
for (i, edits) in edits {
|
||
warnings.extend(self.unaccounted_warnings(*i, &target.name, edits));
|
||
}
|
||
warnings.dedup();
|
||
warnings
|
||
}
|
||
|
||
/// lucisv does not preprocess, so a name that is also a macro name, or that
|
||
/// appears in a macro body, is left exactly as written — and said so.
|
||
fn macro_warnings(&self, name: &str) -> Vec<String> {
|
||
let mut out = Vec::new();
|
||
for i in 0..self.len() {
|
||
let where_ = display(self.path(i).unwrap_or(Path::new("?")));
|
||
for site in self.define_sites(i, name) {
|
||
let line = site.line;
|
||
match site.defines_the_name {
|
||
Some(DefineKind::Define) => out.push(format!(
|
||
"`{name}` is also a macro defined at {where_}:{line}; macro names and macro uses are never renamed."
|
||
)),
|
||
Some(DefineKind::Undef) => out.push(format!(
|
||
"`{name}` is also a macro undefined at {where_}:{line}; macro names and macro uses are never renamed."
|
||
)),
|
||
None => out.push(format!(
|
||
"`{name}` appears in the body of macro `{}` at {where_}:{line} and was left unchanged; lucisv does not preprocess.",
|
||
site.macro_name
|
||
)),
|
||
}
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
/// A macro invocation lexes as **one opaque token**, arguments included,
|
||
/// so the name inside `` `BUMP(a) `` is invisible to the semantic layer and
|
||
/// cannot be edited. It can be seen, though — and silence would be worse
|
||
/// than a warning, because the expansion still spells the old name.
|
||
fn macro_use_warnings(&self, file: usize, name: &str) -> Vec<String> {
|
||
let where_ = display(self.path(file).unwrap_or(Path::new("?")));
|
||
self.macro_argument_sites(file, name)
|
||
.into_iter()
|
||
.map(|site| {
|
||
format!(
|
||
"`{name}` appears in the arguments of the macro invocation `{}` at {where_}:{} and was left unchanged; a macro invocation is one opaque token to lucisv, which does not expand macros.",
|
||
site.macro_name, site.line
|
||
)
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// Every `` `define``/`` `undef`` in one file that `name` touches: the macro
|
||
/// whose own name it is, and every macro whose body spells it.
|
||
///
|
||
/// The *scan* is shared with the port refactorings; the sentence is not,
|
||
/// because "was left unchanged" and "no longer exists after the removal"
|
||
/// are different pieces of news.
|
||
pub(crate) fn define_sites(&self, file: usize, name: &str) -> Vec<DefineSite> {
|
||
let (Some(text), Some(id)) = (self.text(file), self.file_id(file)) else {
|
||
return Vec::new();
|
||
};
|
||
if !text.contains(name) {
|
||
return Vec::new();
|
||
}
|
||
let Some(defines) = self.index.defines(id) else { return Vec::new() };
|
||
let lines = LineIndex::new(text);
|
||
let mut out = Vec::new();
|
||
for define in defines.entries() {
|
||
let line = lines.line_col(define.span.start).0;
|
||
if define.name == name {
|
||
out.push(DefineSite {
|
||
macro_name: define.name.clone(),
|
||
line,
|
||
defines_the_name: Some(define.kind),
|
||
});
|
||
} else if contains_word(&define.body, name) {
|
||
out.push(DefineSite {
|
||
macro_name: define.name.clone(),
|
||
line,
|
||
defines_the_name: None,
|
||
});
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
/// Every macro invocation in one file whose *arguments* spell `name`.
|
||
pub(crate) fn macro_argument_sites(&self, file: usize, name: &str) -> Vec<ArgumentSite> {
|
||
let Some(text) = self.text(file) else { return Vec::new() };
|
||
if !text.contains(name) {
|
||
return Vec::new();
|
||
}
|
||
let Ok(tokens) = tokenize(text) else { return Vec::new() };
|
||
let lines = LineIndex::new(text);
|
||
let mut out = Vec::new();
|
||
for token in tokens.iter().filter(|t| t.is_macro()) {
|
||
// The macro's own name is reported by the `` `define`` scan when
|
||
// the workspace defines it; what is new here is the argument text.
|
||
let Some(arguments) = token.text.split_once('(').map(|(_, rest)| rest) else {
|
||
continue;
|
||
};
|
||
if !contains_word(arguments, name) {
|
||
continue;
|
||
}
|
||
out.push(ArgumentSite {
|
||
macro_name: macro_name_of(&token.text).to_string(),
|
||
line: lines.line_col(token.span.start).0,
|
||
});
|
||
}
|
||
out
|
||
}
|
||
|
||
/// Identifier tokens spelling the name that no declaration and no
|
||
/// reference covers — grouped by *why* lucisv could not attribute them, so
|
||
/// the user is told where to look rather than guessing.
|
||
fn unaccounted_warnings(&mut self, file: usize, name: &str, edits: &[TextEdit]) -> Vec<String> {
|
||
let (Some(text), Some(path)) = (self.text(file), self.path(file)) else {
|
||
return Vec::new();
|
||
};
|
||
let Some(analysis) = self.analysis(file) else { return Vec::new() };
|
||
let mut covered: Vec<TextRange> =
|
||
analysis.semantics.symbols().iter().map(|s| s.name_span).collect();
|
||
covered.extend(analysis.semantics.references().iter().map(|r| r.name_span));
|
||
covered.extend(edits.iter().map(|e| e.range));
|
||
|
||
let Ok(tokens) = tokenize(text) else { return Vec::new() };
|
||
let lines = LineIndex::new(text);
|
||
// Reason → the lines it happened on, in source order.
|
||
let mut groups: Vec<(&'static str, Vec<u32>)> = Vec::new();
|
||
for (i, token) in tokens.iter().enumerate() {
|
||
if token.kind != TokenKind::Ident || token.text != name {
|
||
continue;
|
||
}
|
||
if covered.contains(&token.span) {
|
||
continue;
|
||
}
|
||
let reason = stray_reason(&tokens, i);
|
||
let line = lines.line_col(token.span.start).0;
|
||
match groups.iter_mut().find(|(r, _)| *r == reason) {
|
||
Some((_, at)) => at.push(line),
|
||
None => groups.push((reason, vec![line])),
|
||
}
|
||
}
|
||
groups
|
||
.into_iter()
|
||
.map(|(reason, at)| {
|
||
let at = at.iter().map(u32::to_string).collect::<Vec<_>>().join(", ");
|
||
format!(
|
||
"`{name}` also occurs in {} at line(s) {at} as {reason}; lucisv records no reference there, so it was left unchanged.",
|
||
display(path)
|
||
)
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// The workspace index the edits were computed against.
|
||
pub(crate) fn index(&self) -> &WorkspaceIndex {
|
||
&self.index
|
||
}
|
||
}
|
||
|
||
/// A `` `define``/`` `undef`` a name touches, found by [`Scope::define_sites`].
|
||
pub(crate) struct DefineSite {
|
||
pub(crate) macro_name: String,
|
||
/// 1-based line of the directive.
|
||
pub(crate) line: u32,
|
||
/// `Some` when the name *is* this macro's name; `None` when it only
|
||
/// appears in the macro's body.
|
||
pub(crate) defines_the_name: Option<DefineKind>,
|
||
}
|
||
|
||
/// A macro invocation whose arguments spell a name, found by
|
||
/// [`Scope::macro_argument_sites`].
|
||
pub(crate) struct ArgumentSite {
|
||
pub(crate) macro_name: String,
|
||
/// 1-based line the invocation starts on.
|
||
pub(crate) line: u32,
|
||
}
|
||
|
||
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
|
||
/// to decode.
|
||
fn stray_reason(tokens: &[vlog_parser::token::Token], i: usize) -> &'static str {
|
||
let before = i.checked_sub(1).and_then(|n| tokens.get(n));
|
||
if before.is_some_and(|t| t.is_sym(".")) {
|
||
return "a hierarchical or member tail, which lucisv does not resolve";
|
||
}
|
||
if before.is_some_and(|t| t.is_sym(":")) {
|
||
let keyword = i.checked_sub(2).and_then(|n| tokens.get(n));
|
||
// `endmodule : m` / `end : blk` where the label could not be attached
|
||
// to its declaration — a name already bound in the enclosing scope,
|
||
// or a label that does not spell the declared name.
|
||
if keyword.is_some_and(|t| t.kind == TokenKind::Keyword && t.text.starts_with("end")) {
|
||
return "an end label lucisv could not attach to its declaration";
|
||
}
|
||
return "a label lucisv records no declaration for";
|
||
}
|
||
"an occurrence lucisv cannot attribute to any declaration"
|
||
}
|
||
|
||
/// The macro name of an invocation token, as a message spells it:
|
||
/// `` `BUMP(a) `` → `BUMP`. The leading backtick is dropped so the name reads
|
||
/// the same way the `` `define`` warnings spell it.
|
||
fn macro_name_of(invocation: &str) -> &str {
|
||
let name = match invocation.split_once('(') {
|
||
Some((name, _)) => name.trim_end(),
|
||
None => invocation,
|
||
};
|
||
name.strip_prefix('`').unwrap_or(name)
|
||
}
|
||
|
||
/// How a file is named in a message: its file name, because an absolute path
|
||
/// in a rename box is unreadable.
|
||
pub(crate) fn display(path: &Path) -> String {
|
||
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_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).
|
||
///
|
||
/// 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;
|
||
}
|
||
let bytes = haystack.as_bytes();
|
||
let mut from = 0;
|
||
while let Some(hit) = haystack.get(from..).and_then(|s| s.find(needle)) {
|
||
let start = from + hit;
|
||
let end = start + needle.len();
|
||
let before = start.checked_sub(1).and_then(|i| bytes.get(i)).copied();
|
||
let after = bytes.get(end).copied();
|
||
if !before.is_some_and(is_name_byte) && !after.is_some_and(is_name_byte) {
|
||
return true;
|
||
}
|
||
from = start + 1;
|
||
}
|
||
false
|
||
}
|
||
|
||
fn is_name_byte(byte: u8) -> bool {
|
||
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn a_new_name_must_be_one_plain_identifier() {
|
||
assert!(check_new_name("ok_name").is_ok());
|
||
assert!(check_new_name("_x1$").is_ok());
|
||
assert!(check_new_name("").is_err(), "empty");
|
||
assert!(check_new_name("two names").is_err(), "two tokens");
|
||
assert!(check_new_name("a+b").is_err(), "an expression");
|
||
assert!(check_new_name("module").is_err(), "a keyword");
|
||
assert!(check_new_name("1234").is_err(), "a number");
|
||
assert!(check_new_name("`MACRO").is_err(), "a macro use");
|
||
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"));
|
||
assert!(!contains_word("a + MY_WIDTH - 1", "WIDTH"));
|
||
assert!(!contains_word("WIDTHS", "WIDTH"));
|
||
assert!(contains_word("`WIDTH", "WIDTH"), "a macro use of the name still counts");
|
||
assert!(!contains_word("x", ""));
|
||
}
|
||
}
|