Files
lucisv/crates/vlog_refactor/src/check.rs
T
lucioandClaude Fable 5.1 aa479cf701 Convert ports to ANSI: a Verilog-2001 header merged with its body declarations, and a verifier that never drops a comment or an attribute
TODO §51 (docs/features/ansi-conversion), the second §8 refactoring.

`vlog_refactor::convert_to_ansi` (ports/ansi.rs, ports/merge.rs): for a
`PortList::NonAnsi` module, each header name gains its direction, net or
variable type, signing and packed dims from the body declarations that
describe it, merged per IEEE 1800 §23.2.2.2 (`output b; reg [7:0] b;`
→ `output reg [7:0] b`), as insertions around the untouched name so no
reference anchor moves; the absorbed declarations are deleted with their
comments carried onto the ports. Twenty-three refusals, each a sentence
(port expressions, disagreeing ranges, initialisers, directives, a
comment that would have to move into a one-line list, an attributed
declaration). Code action `lucisv: convert ports to ANSI (N ports)` and
command `lucisv.convertToAnsi`.

Review rework (QA's two HIGHs, invariant 4): the verifier's comment rule
is now `never_dropped` over comments and attribute instances alike —
`has ≥ had`, `wrote ≤ gone` unless the text is the one generated
placeholder, `has == had − gone + wrote` — with masked-corruption attack
tests, re-attacked by QA (30-plus pairs, a neutering pass).

Neither the corpus nor opentitan holds a non-ANSI module; acceptance is
by round trip (ANSI → 2001 → ANSI, same ports/types in order) over five
corpus modules and 290 of 291 opentitan candidates (the one failure is
kmac_reduced_tb.sv's pre-existing trailing-comma parse error). 0 of 854
corpus files differ from 0.45.0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 18:03:54 -05:00

1277 lines
54 KiB
Rust

//! Whole-edit-or-nothing verification.
//!
//! Two independent checks, both run on the edited text in memory before any
//! edit is returned. **Token identity** catches lexical damage — an edit that
//! landed in a string, ate a comment, merged two tokens. **Resolution
//! identity** catches semantic damage — a name captured by an existing
//! declaration, or a cross-file use that quietly rebound. Neither implies the
//! other, and either one failing fails the entire refactoring.
//!
//! [`verify`] is the *rename* contract: the token stream may not change shape
//! at all. [`verify_splice`] is the same contract for a refactoring that
//! deliberately writes or deletes text (the port ones): the token stream may
//! change only by exactly the pieces the edits spell, no comment and no
//! attribute may be deleted, no file may gain a parse error, and every name
//! *outside* the edited ranges must still resolve to exactly what it did.
//!
//! Nothing here touches `vlog_formatter` or its `verify.rs`: this is the same
//! contract, kept separately, so the formatter's safety net does not widen.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
use vlog_parser::{parse_source_tolerant, tokenize};
use vlog_semantic::{
analyze, resolve_external, ExternalResolutions, ExternalTarget, ReferenceId, Semantics,
SymbolKind, WorkspaceIndex,
};
use crate::rename::{contains_word, display, Scope};
use crate::{apply, Shift, TextEdit};
/// Check the whole edit, or refuse it whole.
pub(crate) fn verify(
scope: &mut Scope,
edits: &[(usize, Vec<TextEdit>)],
old_name: &str,
new_name: &str,
) -> Result<(), String> {
let edited: Vec<(PathBuf, String)> = edits
.iter()
.filter_map(|(i, edits)| {
let path = scope.path(*i)?.to_path_buf();
Some((path, apply(scope.text(*i)?, edits)))
})
.collect();
if edited.len() != edits.len() {
return Err(ABANDONED.to_string());
}
let shifts = Shifts::new(scope, edits, new_name);
// 1. The token stream of every touched file, before and after.
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
let Some(before) = scope.text(*i) else { return Err(ABANDONED.to_string()) };
tokens_match(before, text, &Shift::new(edits), new_name, path)?;
}
// 2. What every name resolves to, before and after — in every file the
// rename could possibly have moved, not only the ones it edited. A file
// that spells neither name cannot change meaning: an edit only adds and
// removes declarations of those two names, and a lookup of any other name
// cannot see them. A file that spells *either* is watched, which is what
// catches a third file whose existing `new_name` reference the rename
// would make ambiguous without touching a byte of it.
let watched = watched_files(scope, edits, old_name, new_name);
for &i in &watched {
if scope.analysis(i).is_none() {
return Err(ABANDONED.to_string());
}
}
let mut before: Vec<Print> = Vec::new();
for &i in &watched {
let (Some(path), Some(analysis)) = (scope.path(i), scope.cached(i)) else {
return Err(ABANDONED.to_string());
};
before.push(print(
&analysis.semantics,
&analysis.external,
scope.index(),
path,
&shifts,
&[],
));
}
let after_index = rebuilt_index(scope, &edited);
for (n, &i) in watched.iter().enumerate() {
let Some(path) = scope.path(i) else { return Err(ABANDONED.to_string()) };
let text = match edited.iter().find(|(edited_path, _)| edited_path == path) {
Some((_, edited_text)) => edited_text.as_str(),
None => match scope.text(i) {
Some(text) => text,
None => return Err(ABANDONED.to_string()),
},
};
let semantics = analyze(&parse_source_tolerant(text).0, text);
let external = resolve_external(&semantics, &after_index);
let after = print(&semantics, &external, &after_index, path, &Shifts::default(), &[]);
let Some(before) = before.get(n) else { return Err(ABANDONED.to_string()) };
if let Some(what) = before.first_difference(&after) {
return Err(format!(
"renaming `{old_name}` to `{new_name}` would change what {what} means in {}; the rename was abandoned.",
display(path)
));
}
}
Ok(())
}
/// Check the whole edit of a refactoring that adds or deletes text, or refuse
/// it whole. `watch_name` is the name whose meaning the refactoring changes —
/// the module whose ports moved — and `what` names the refactoring in the
/// refusal ("adding port `cfg`").
///
/// Four checks, in the order that gives the most useful sentence first:
///
/// 1. **Lexical splice.** Every touched file must lex to exactly the original
/// pieces — code tokens *and* comments — with the edits' own pieces written
/// in at the edits' positions and nothing else moved. An edit that landed
/// in a string, split a token or wrote a `,` into a line comment cannot
/// survive it.
/// 2. **Comments and attributes are never dropped** (CLAUDE.md invariant 3):
/// every comment and every `(* ... *)` the file had it still has, and no
/// more. A deletion may cover one only when the edits write it back — which
/// is how the ANSI conversion moves a body declaration's comment onto the
/// port it becomes; see [`never_dropped`].
/// 3. **The file still parses**: a touched file may not gain a parse
/// diagnostic it did not have.
/// 4. **Resolution identity outside the edits.** Every declaration and every
/// reference whose name span does not overlap an edit must resolve to the
/// same place before and after — in every watched file, edited or not. This
/// is what refuses an added port that captures a body reference, or a
/// removed port some other name silently rebinds.
pub(crate) fn verify_splice(
scope: &mut Scope,
edits: &[(usize, Vec<TextEdit>)],
watch_name: &str,
what: &str,
) -> Result<(), String> {
let abandoned = format!("lucisv could not verify {what}, so it made no edits.");
let edited: Vec<(PathBuf, String)> = edits
.iter()
.filter_map(|(i, edits)| {
let path = scope.path(*i)?.to_path_buf();
Some((path, apply(scope.text(*i)?, edits)))
})
.collect();
if edited.len() != edits.len() {
return Err(abandoned);
}
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
let Some(before) = scope.text(*i) else { return Err(abandoned) };
pieces_match(before, text, edits, path, what)?;
// A tolerant parse of a file that was already broken still reports its
// old diagnostics, so the bar is "no *new* one", not "none".
let (before_count, after_count) =
(parse_source_tolerant(before).1.len(), parse_source_tolerant(text).1.len());
if after_count > before_count {
return Err(format!(
"{what} would leave {} unparseable; no edits were made.",
display(path)
));
}
}
let shifts = Shifts::new(scope, edits, "");
let excluded = Excluded::new(scope, edits);
let watched = watched_files(scope, edits, watch_name, watch_name);
for &i in &watched {
if scope.analysis(i).is_none() {
return Err(abandoned);
}
}
let mut before: Vec<Print> = Vec::new();
for &i in &watched {
let (Some(path), Some(analysis)) = (scope.path(i), scope.cached(i)) else {
return Err(abandoned);
};
before.push(print(
&analysis.semantics,
&analysis.external,
scope.index(),
path,
&shifts,
excluded.before(path),
));
}
let after_index = rebuilt_index(scope, &edited);
for (n, &i) in watched.iter().enumerate() {
let Some(path) = scope.path(i) else { return Err(abandoned) };
let text = match edited.iter().find(|(edited_path, _)| edited_path == path) {
Some((_, edited_text)) => edited_text.as_str(),
None => match scope.text(i) {
Some(text) => text,
None => return Err(abandoned),
},
};
let semantics = analyze(&parse_source_tolerant(text).0, text);
let external = resolve_external(&semantics, &after_index);
let after = print(
&semantics,
&external,
&after_index,
path,
&Shifts::default(),
excluded.after(path),
);
let Some(before) = before.get(n) else { return Err(abandoned) };
if let Some(what_moved) = before.first_difference(&after) {
return Err(format!(
"{what} would change what {what_moved} means in {}; no edits were made.",
display(path)
));
}
}
Ok(())
}
/// The byte ranges each refactoring deliberately changed, in the coordinates
/// of the text before the edits and of the text after them. Names inside them
/// are the ones the user asked to move, so they are the only ones the
/// resolution check does not hold fixed.
#[derive(Default)]
struct Excluded {
before: HashMap<PathBuf, Vec<TextRange>>,
after: HashMap<PathBuf, Vec<TextRange>>,
}
impl Excluded {
fn new(scope: &Scope, edits: &[(usize, Vec<TextEdit>)]) -> Excluded {
let mut out = Excluded::default();
for (i, edits) in edits {
let Some(path) = scope.path(*i) else { continue };
out.before.insert(path.to_path_buf(), edits.iter().map(|e| e.range).collect());
let mut after = Vec::new();
let mut delta: i64 = 0;
for edit in edits {
let start = (edit.range.start as i64 + delta).max(0) as u32;
after.push(TextRange::new(start, start + edit.new_text.len() as u32));
delta += edit.new_text.len() as i64 - i64::from(edit.range.len());
}
out.after.insert(path.to_path_buf(), after);
}
out
}
fn before(&self, path: &Path) -> &[TextRange] {
self.before.get(path).map_or(&[], Vec::as_slice)
}
fn after(&self, path: &Path) -> &[TextRange] {
self.after.get(path).map_or(&[], Vec::as_slice)
}
}
/// Every file whose resolution the rename could move: the ones it edits, plus
/// the ones that spell either name as a whole word. A whole-word text search
/// is a sound *superset* of "has a token spelling the name" — a token spells
/// its name literally, so it is always found — and it errs by watching a few
/// files whose only mention is in a comment.
fn watched_files(
scope: &Scope,
edits: &[(usize, Vec<TextEdit>)],
old_name: &str,
new_name: &str,
) -> Vec<usize> {
let mut watched: Vec<usize> = edits.iter().map(|(i, _)| *i).collect();
for i in 0..scope.len() {
let Some(text) = scope.text(i) else { continue };
if watched.contains(&i) {
continue;
}
if contains_word(text, old_name) || contains_word(text, new_name) {
watched.push(i);
}
}
watched.sort_unstable();
watched
}
const ABANDONED: &str = "lucisv could not verify the rename, so it made no edits.";
/// The workspace index as it would be after the edits, so that a cross-file
/// capture is caught exactly the way an in-file one is.
fn rebuilt_index(scope: &Scope, edited: &[(PathBuf, String)]) -> WorkspaceIndex {
let sources = scope.sources().iter().map(|(path, text)| {
let text = edited
.iter()
.find(|(edited_path, _)| edited_path == path)
.map_or(*text, |(_, edited_text)| edited_text.as_str());
(path.to_path_buf(), text)
});
WorkspaceIndex::build(sources.collect::<Vec<_>>())
}
// ----------------------------------------------------------------------
// token identity
// ----------------------------------------------------------------------
/// The edited file must lex to the same tokens as the original, except that
/// the tokens the edits replaced now spell the new name.
fn tokens_match(
before: &str,
after: &str,
shift: &Shift,
new_name: &str,
path: &Path,
) -> Result<(), String> {
let refusal = |what: &str| {
format!("the rename would change {what} in {}; no edits were made.", display(path))
};
let (Ok(old), Ok(new)) = (tokenize(before), tokenize(after)) else {
return Err(format!(
"{} would no longer lex after the rename; no edits were made.",
display(path)
));
};
if old.len() != new.len() {
return Err(refusal("the token stream's shape"));
}
for (old, new) in old.iter().zip(&new) {
let edited = shift.is_edited(old.span);
let expected_text = if edited { new_name } else { old.text.as_str() };
let expected_kind = if edited { TokenKind::Ident } else { old.kind };
if new.kind != expected_kind || new.text != expected_text {
return Err(refusal(&format!("the token `{}`", old.text)));
}
if new.span != shift.map(old.span) {
return Err(refusal(&format!("where `{}` sits", old.text)));
}
if new.blank_before != old.blank_before {
return Err(refusal("the blank lines"));
}
let comments_kept = old.leading.len() == new.leading.len()
&& old.leading.iter().zip(&new.leading).all(|(a, b)| a.text == b.text)
&& old.trailing.as_ref().map(|c| &c.text) == new.trailing.as_ref().map(|c| &c.text);
if !comments_kept {
return Err(refusal("a comment"));
}
}
Ok(())
}
// ----------------------------------------------------------------------
// lexical splice
// ----------------------------------------------------------------------
/// One lexical piece of a file, in source order: a code token, or a comment.
/// Comments are pieces of their own rather than trivia hanging off a token,
/// because an insertion can legitimately move which token a comment attaches
/// to without moving the comment itself.
#[derive(Debug, PartialEq, Eq)]
enum Piece {
Code(TokenKind, String),
Comment(String),
}
impl Piece {
/// How the piece is named in a refusal.
fn describe(&self) -> String {
match self {
Piece::Code(_, text) => format!("the token `{text}`"),
Piece::Comment(text) => format!("the comment `{text}`"),
}
}
}
/// Every piece of a file with the bytes it occupies, in source order.
fn pieces(text: &str) -> Option<Vec<(TextRange, Piece)>> {
let tokens = tokenize(text).ok()?;
let mut out: Vec<(TextRange, Piece)> = Vec::new();
for token in &tokens {
for comment in &token.leading {
out.push((comment.span, Piece::Comment(comment.text.clone())));
}
if token.kind != TokenKind::Eof {
out.push((token.span, Piece::Code(token.kind, token.text.clone())));
}
if let Some(comment) = &token.trailing {
out.push((comment.span, Piece::Comment(comment.text.clone())));
}
}
out.sort_by_key(|(span, _)| (span.start, span.end));
Some(out)
}
/// The edited file must lex to the original's pieces with the edits' own
/// pieces written in where the edits are — and to nothing else.
fn pieces_match(
before: &str,
after: &str,
edits: &[TextEdit],
path: &Path,
what: &str,
) -> Result<(), String> {
let (Some(old), Some(new)) = (pieces(before), pieces(after)) else {
return Err(format!(
"{} would no longer lex after {what}; no edits were made.",
display(path)
));
};
let mut written: Vec<Vec<(TextRange, Piece)>> = Vec::new();
for edit in edits {
let Some(pieces) = pieces(&edit.new_text) else {
return Err(format!("{what} would write text that does not lex; no edits were made."));
};
written.push(pieces);
}
never_dropped(&old, &new, edits, &written, path, what)?;
let mut expected: Vec<Piece> = Vec::new();
let mut next = 0usize;
for (span, piece) in old {
while let (Some(edit), Some(pieces)) = (edits.get(next), written.get(next)) {
if edit.range.start > span.start {
break;
}
expected.extend(pieces.iter().map(|(_, piece)| match piece {
Piece::Code(kind, text) => Piece::Code(*kind, text.clone()),
Piece::Comment(text) => Piece::Comment(text.clone()),
}));
next += 1;
}
if edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, span)) {
continue;
}
expected.push(piece);
}
while let Some(pieces) = written.get(next) {
expected.extend(pieces.iter().map(|(_, piece)| match piece {
Piece::Code(kind, text) => Piece::Code(*kind, text.clone()),
Piece::Comment(text) => Piece::Comment(text.clone()),
}));
next += 1;
}
let actual: Vec<Piece> = new.into_iter().map(|(_, piece)| piece).collect();
for (n, expected) in expected.iter().enumerate() {
match actual.get(n) {
Some(actual) if actual == expected => {}
Some(actual) => {
return Err(format!(
"{what} would write {} where {} belongs in {}; no edits were made.",
actual.describe(),
expected.describe(),
display(path)
))
}
None => {
return Err(format!(
"{what} would lose {} in {}; no edits were made.",
expected.describe(),
display(path)
))
}
}
}
if actual.len() > expected.len() {
let extra = actual.get(expected.len()).map_or_else(String::new, Piece::describe);
return Err(format!(
"{what} would add {extra} to {}, which is not part of the edit; no edits were made.",
display(path)
));
}
Ok(())
}
/// The pieces an edit may never lose, gain or duplicate: a **comment**
/// (CLAUDE.md invariant 3) and an **attribute instance** `(* ... *)`.
///
/// The piece comparison above cannot see either on its own. A piece inside a
/// deleted range disappears from *both* sides of it — from `expected`, because
/// pieces inside an edit are skipped, and from `actual`, because it is really
/// gone — so a dropped comment, or a dropped `(* keep *)`, would pass
/// unnoticed. An attribute is a code token rather than trivia, but a deletion
/// hides it exactly the way it hides a comment, and losing one changes what a
/// synthesizer does; so both are counted here, by exact text.
///
/// Three equations, over every text that appears on any side. `had` and `has`
/// are the file's counts before and after, `gone` counts the old pieces a
/// non-empty edit range covers, and `wrote` counts the pieces lexed out of the
/// edits' own inserted text.
///
/// 1. **`has >= had`** — nothing is ever lost. This is the whole of invariant
/// 3 and the only half the rule this replaced had.
/// 2. **`wrote <= gone`**, unless the text is one a refactoring
/// [`generated`] itself — a piece is written back *where it was deleted*,
/// and nowhere else. This refuses a planner that takes the comment on
/// `input a, b;` and writes it onto *both* ports (one really did, on the
/// way — see the work log), and equally one that duplicates the text of a
/// comment it never touched.
/// 3. **`has == had - gone + wrote`** — the applied text says exactly what the
/// edits say. An application that grew a second copy of a comment the edits
/// write once is masked corruption the first two equations would forgive.
///
/// Where each piece now *sits* is the piece comparison's business, not this
/// one's; between them a moved comment is verified as exactly as a stationary
/// one.
fn never_dropped(
old: &[(TextRange, Piece)],
new: &[(TextRange, Piece)],
edits: &[TextEdit],
written: &[Vec<(TextRange, Piece)>],
path: &Path,
what: &str,
) -> Result<(), String> {
let covered = |span: TextRange| {
edits.iter().any(|edit| !edit.range.is_empty() && overlaps(edit.range, span))
};
let before = tally(old.iter().map(|(_, piece)| piece));
let after = tally(new.iter().map(|(_, piece)| piece));
let deleted = tally(old.iter().filter(|(span, _)| covered(*span)).map(|(_, piece)| piece));
let writes = tally(written.iter().flatten().map(|(_, piece)| piece));
let mut texts: Vec<&Kept> = before.keys().chain(after.keys()).chain(writes.keys()).collect();
texts.sort_unstable();
texts.dedup();
let count = |tally: &Tally, key: &Kept| tally.get(key).copied().unwrap_or(0);
// Three passes rather than three tests in one pass, so that the sentence
// the user reads is the worst thing wrong with the edit rather than
// whichever text sorted first.
if let Some(Kept(noun, text)) =
texts.iter().find(|key| count(&after, key) < count(&before, key))
{
return Err(format!(
"{what} would delete the {noun} `{text}` in {}; {noun}s are never dropped, so nothing was edited.",
display(path)
));
}
if let Some(key) =
texts.iter().find(|key| count(&writes, key) > count(&deleted, key) && !generated(&key.1))
{
let Kept(noun, text) = key;
let (gone, wrote) = (count(&deleted, key), count(&writes, key));
let deletes = match gone {
0 => "without deleting it".to_string(),
gone => format!("where it deletes it {}", times(gone)),
};
return Err(format!(
"{what} would write the {noun} `{text}` {} in {} {deletes}; {noun}s are never duplicated, so nothing was edited.",
times(wrote),
display(path)
));
}
// `deleted` is a subset of `before`, so the subtraction cannot go under —
// saturating rather than plain because an arithmetic panic is not a
// refusal, and this is a safety net.
let accounted =
|key: &Kept| count(&before, key).saturating_sub(count(&deleted, key)) + count(&writes, key);
if let Some(key) = texts.iter().find(|key| count(&after, key) != accounted(key)) {
let Kept(noun, text) = key;
return Err(format!(
"{what} would leave the {noun} `{text}` in {} {}, where its edits account for it {}; nothing was edited.",
display(path),
times(count(&after, key)),
times(accounted(key))
));
}
Ok(())
}
/// One never-dropped piece, keyed for counting: the noun a refusal calls it by
/// (`comment` or `attribute`) and its exact text.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Kept(&'static str, String);
type Tally = HashMap<Kept, usize>;
/// How many of each never-dropped piece a stream of pieces holds. Every other
/// piece is a code token the comparison above already pins position by
/// position, so it is not counted here.
fn tally<'p>(pieces: impl Iterator<Item = &'p Piece>) -> Tally {
let mut out = Tally::new();
for piece in pieces {
let key = match piece {
Piece::Comment(text) => Kept("comment", text.clone()),
Piece::Code(TokenKind::Attribute, text) => Kept("attribute", text.clone()),
Piece::Code(..) => continue,
};
*out.entry(key).or_insert(0) += 1;
}
out
}
/// The comments a refactoring writes itself rather than moves, which it may
/// therefore write however many times it needs and even where the file already
/// has one. `add_port` and `propagate_ports` both leave
/// `/* TODO: connect */` at a connection they cannot name a signal for, and a
/// module gains its ports one at a time — so the second addition to a file
/// finds the first one's placeholder already sitting there. Everything else a
/// refactoring writes has to be a piece it is deleting somewhere else.
fn generated(text: &str) -> bool {
text == "/* TODO: connect */"
}
/// A count, in prose, so a refusal reads like a sentence.
fn times(n: usize) -> String {
match n {
0 => "never".to_string(),
1 => "once".to_string(),
2 => "twice".to_string(),
n => format!("{n} times"),
}
}
/// Whether two byte ranges share a byte. Empty ranges — the insertions —
/// overlap nothing: they replace no text, so they delete nothing.
fn overlaps(a: TextRange, b: TextRange) -> bool {
a.start < b.end && b.start < a.end
}
// ----------------------------------------------------------------------
// resolution identity
// ----------------------------------------------------------------------
/// Where the edits moved each touched file's bytes, keyed by path, plus the
/// name the edited occurrences now spell. The default value maps nothing,
/// which is what the post-edit side wants.
#[derive(Default)]
struct Shifts {
by_path: HashMap<PathBuf, Shift>,
new_name: String,
}
impl Shifts {
fn new(scope: &Scope, edits: &[(usize, Vec<TextEdit>)], new_name: &str) -> Shifts {
let mut by_path = HashMap::new();
for (i, edits) in edits {
if let Some(path) = scope.path(*i) {
by_path.insert(path.to_path_buf(), Shift::new(edits));
}
}
Shifts { by_path, new_name: new_name.to_string() }
}
fn map(&self, path: &Path, span: TextRange) -> TextRange {
self.by_path.get(path).map_or(span, |shift| shift.map(span))
}
/// The name an occurrence spells after the edits.
fn name(&self, path: &Path, span: TextRange, name: &str) -> String {
match self.by_path.get(path) {
Some(shift) if shift.is_edited(span) => self.new_name.clone(),
_ => name.to_string(),
}
}
}
/// What one name resolves to, said in terms that survive an edit: a file path
/// and a byte span, never a `SymbolId` or a `FileId` (both are positions in
/// tables that a re-analysis rebuilds).
#[derive(Debug, PartialEq, Eq)]
enum Anchor {
/// A declaration in the same file.
Local(u32, u32),
/// Declarations the workspace overlay answered with, in its own order.
External(Vec<(PathBuf, u32, u32)>),
/// Nothing resolves it — `NotFound`, an inherited candidate, or an
/// external candidate the workspace cannot answer.
Unresolved,
}
/// Everything one file declares and everything it names, with the spans and
/// anchors of the *edited* text. Built for the pre-edit analysis (shifted
/// forward) and for the post-edit one (as it is); the two must be equal.
#[derive(Debug, PartialEq, Eq, Default)]
struct Print {
declarations: Vec<(u32, u32, String, SymbolKind)>,
references: Vec<(u32, u32, String, Anchor)>,
}
impl Print {
/// The first entry the two prints disagree on, named for the user.
fn first_difference(&self, other: &Print) -> Option<String> {
if self.declarations.len() != other.declarations.len() {
return Some("the set of declarations".to_string());
}
for (a, b) in self.declarations.iter().zip(&other.declarations) {
if a != b {
return Some(format!("the declaration of `{}`", b.2));
}
}
if self.references.len() != other.references.len() {
return Some("the set of names".to_string());
}
for (a, b) in self.references.iter().zip(&other.references) {
if a != b {
return Some(format!("`{}`", b.2));
}
}
None
}
}
/// Everything one file declares and names, minus whatever sits inside
/// `excluded` — the ranges the refactoring deliberately wrote or deleted.
/// A rename passes no exclusions: it changes a spelling, never a structure.
fn print(
semantics: &Semantics,
external: &ExternalResolutions,
index: &WorkspaceIndex,
path: &Path,
shifts: &Shifts,
excluded: &[TextRange],
) -> Print {
let inside = |span: TextRange| excluded.iter().any(|range| overlaps(*range, span));
let mut declarations: Vec<(u32, u32, String, SymbolKind)> = semantics
.symbols()
.iter()
.filter(|symbol| !inside(symbol.name_span))
.map(|symbol| {
let span = shifts.map(path, symbol.name_span);
(span.start, span.end, shifts.name(path, symbol.name_span, &symbol.name), symbol.kind)
})
.collect();
declarations.sort_by_key(|d| (d.0, d.1));
let mut references: Vec<(u32, u32, String, Anchor)> = semantics
.references()
.iter()
.enumerate()
.filter(|(_, reference)| !inside(reference.name_span))
.map(|(id, reference)| {
let span = shifts.map(path, reference.name_span);
let anchor = anchor_of(semantics, external, index, path, shifts, id, reference);
(span.start, span.end, shifts.name(path, reference.name_span, &reference.name), anchor)
})
.collect();
references.sort_by_key(|r| (r.0, r.1));
Print { declarations, references }
}
fn anchor_of(
semantics: &Semantics,
external: &ExternalResolutions,
index: &WorkspaceIndex,
path: &Path,
shifts: &Shifts,
id: usize,
reference: &vlog_semantic::Reference,
) -> Anchor {
if let Some(symbol) = reference.resolved().and_then(|s| semantics.symbol(s)) {
let span = shifts.map(path, symbol.name_span);
return Anchor::Local(span.start, span.end);
}
let defs = match external.get(ReferenceId(id as u32)) {
Some(ExternalTarget::Resolved(def)) => std::slice::from_ref(def),
Some(ExternalTarget::Ambiguous(defs)) => defs.as_slice(),
_ => &[],
};
if defs.is_empty() {
return Anchor::Unresolved;
}
Anchor::External(
defs.iter()
.map(|def| {
let file = index.path(def.file).unwrap_or(Path::new("?")).to_path_buf();
let span = shifts.map(&file, def.name_span);
(file, span.start, span.end)
})
.collect(),
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rename::Scope;
const SOURCE: &str =
"module m;\n wire a;\n assign a = 1; // a stays\n initial $display(\"a\");\nendmodule\n";
/// The two edits a `a` → `sig` rename of `SOURCE` would produce.
fn rename_edits() -> Vec<TextEdit> {
let declaration = SOURCE.find("wire a").expect("decl") as u32 + 5;
let use_ = SOURCE.find("assign a").expect("use") as u32 + 7;
vec![
TextEdit {
range: TextRange::new(declaration, declaration + 1),
new_text: "sig".into(),
},
TextEdit { range: TextRange::new(use_, use_ + 1), new_text: "sig".into() },
]
}
fn attack(corrupted: &str) -> Result<(), String> {
let edits = rename_edits();
tokens_match(SOURCE, corrupted, &Shift::new(&edits), "sig", Path::new("/rtl/m.sv"))
}
#[test]
fn the_edit_the_engine_actually_produces_verifies() {
let honest = apply(SOURCE, &rename_edits());
assert_eq!(attack(&honest), Ok(()), "the real output must pass");
assert!(honest.contains("wire sig;") && honest.contains("// a stays"));
}
// The masked-corruption attacks: crafted (input, corrupted output) pairs
// that a sloppier check would forgive.
#[test]
fn an_edit_that_also_rewrote_a_comment_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replace("// a stays", "// sig stays");
assert!(attack(&corrupted).is_err(), "a comment must not change");
}
#[test]
fn an_edit_that_also_rewrote_a_string_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replace("\"a\"", "\"sig\"");
assert!(attack(&corrupted).is_err(), "a string literal must not change");
}
#[test]
fn an_edit_that_dropped_a_comment_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replace(" // a stays", "");
assert!(attack(&corrupted).is_err(), "comments are never dropped");
}
#[test]
fn an_edit_that_lost_or_gained_a_token_is_rejected() {
let dropped = apply(SOURCE, &rename_edits()).replace("assign sig = 1;", "assign sig = 1");
assert!(attack(&dropped).is_err(), "a lost `;`");
let gained = apply(SOURCE, &rename_edits()).replace("wire sig;", "wire sig, extra;");
assert!(attack(&gained).is_err(), "an invented declaration");
}
#[test]
fn an_edit_that_wrote_a_different_name_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replacen("wire sig", "wire other", 1);
assert!(attack(&corrupted).is_err(), "the edited token must spell the new name");
}
#[test]
fn an_edit_that_moved_an_untouched_token_is_rejected() {
// Whitespace only — the token stream is otherwise identical, which is
// exactly what a check comparing texts alone would wave through.
let corrupted = apply(SOURCE, &rename_edits()).replace("assign sig", "assign sig");
assert!(attack(&corrupted).is_err(), "a shifted span must be caught");
}
#[test]
fn an_edit_whose_result_does_not_lex_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replace("endmodule", "/* oops");
assert!(attack(&corrupted).is_err(), "an unlexable result is a failure, not output");
}
// ------------------------------------------------------------------
// the splice verifier, and the attacks on it
// ------------------------------------------------------------------
/// A module whose port list is one per line, with a comment on each port —
/// the shape every one of the attacks below tries to damage.
const PORTS: &str =
"module m (\n input clk, // the clock\n input rst /* sync */\n);\n wire a; // a\nendmodule\n";
/// The edit `add_port` produces for `PORTS`: a `,` before the last port's
/// comment and the new port after it.
fn add_edits() -> Vec<TextEdit> {
let end = PORTS.find("input rst").expect("rst") as u32 + "input rst".len() as u32;
let after_comment = PORTS.find("*/").expect("comment") as u32 + 2;
vec![
TextEdit { range: TextRange::empty(end), new_text: ",".into() },
TextEdit {
range: TextRange::empty(after_comment),
new_text: "\n input logic [7:0] cfg".into(),
},
]
}
fn splice_attack(corrupted: &str) -> Result<(), String> {
pieces_match(PORTS, corrupted, &add_edits(), Path::new("/rtl/m.sv"), "adding port `cfg`")
}
#[test]
fn the_splice_the_engine_actually_produces_verifies() {
let honest = apply(PORTS, &add_edits());
assert_eq!(splice_attack(&honest), Ok(()), "the real output must pass");
assert!(honest.contains("input rst, /* sync */\n input logic [7:0] cfg"), "{honest}");
}
#[test]
fn a_splice_that_wrote_the_comma_into_a_line_comment_is_rejected() {
// The hazard the two-edit shape exists to avoid: a `,` after `//` is a
// `,` nobody will ever see.
let corrupted = PORTS
.replace("// the clock", "// the clock,")
.replace("input rst /* sync */", "input rst /* sync */\n input logic [7:0] cfg");
assert!(splice_attack(&corrupted).is_err(), "a comma inside a comment is not an edit");
}
#[test]
fn a_splice_that_landed_at_the_wrong_place_is_rejected() {
// The same tokens, spliced one port earlier: every piece is accounted
// for, but not in the order the edits promised.
let corrupted = apply(PORTS, &add_edits())
.replace("input clk,", "input clk, input logic [7:0] cfg,")
.replace(",\n input logic [7:0] cfg\n)", "\n)");
assert!(splice_attack(&corrupted).is_err(), "position is part of the promise");
}
#[test]
fn a_splice_that_also_dropped_a_comment_is_rejected() {
let corrupted = apply(PORTS, &add_edits()).replace(" // a", "");
let message = splice_attack(&corrupted).expect_err("a dropped comment is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
#[test]
fn a_splice_that_also_rewrote_an_untouched_token_is_rejected() {
let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire b;");
assert!(splice_attack(&corrupted).is_err(), "nothing outside the edit may move");
}
#[test]
fn a_splice_that_wrote_more_than_it_promised_is_rejected() {
let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire a; wire extra;");
assert!(splice_attack(&corrupted).is_err(), "an invented declaration");
}
#[test]
fn a_splice_that_landed_inside_a_string_is_rejected() {
let text = "module m;\n initial $display(\"hello\");\nendmodule\n";
let at = text.find("hello").expect("string") as u32;
let edits = vec![TextEdit { range: TextRange::empty(at), new_text: "x".into() }];
let corrupted = apply(text, &edits);
let outcome = pieces_match(text, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit");
assert!(outcome.is_err(), "the string's own text is not a token lucisv may write");
}
#[test]
fn a_deletion_that_would_swallow_a_comment_is_refused() {
// The one rule the piece comparison cannot see on its own: a comment
// inside a deleted range disappears from *both* sides.
let start = PORTS.find("input rst").expect("rst") as u32;
let end = PORTS.find("*/").expect("comment") as u32 + 2;
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
let corrupted = apply(PORTS, &edits);
let outcome =
pieces_match(PORTS, &corrupted, &edits, Path::new("/rtl/m.sv"), "removing port `rst`");
let message = outcome.expect_err("a deleted comment is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
#[test]
fn a_splice_whose_result_does_not_lex_is_rejected() {
let corrupted = apply(PORTS, &add_edits()).replace("endmodule", "/* oops");
assert!(splice_attack(&corrupted).is_err(), "an unlexable result is a failure, not output");
}
// ------------------------------------------------------------------
// the moved-comment rule, and the attacks on it (CLAUDE.md invariant 4)
// ------------------------------------------------------------------
//
// 2026-09-05: `comments_kept` replaced "no deletion may cover a comment",
// so that `ports::ansi` can move a body declaration's comment onto the
// ANSI port that declaration becomes. Every attack below is a crafted
// (input, corrupted output) pair the relaxation could plausibly forgive.
/// A Verilog-2001 header whose two declarations each carry a comment —
/// the shape the ANSI conversion has to move a comment out of.
const MOVED: &str =
"module m (\n a,\n b\n);\n input a; // the note\n output b; // the note\nendmodule\n";
/// The edits `convert_to_ansi` really produces for `MOVED`.
fn move_edits() -> Vec<TextEdit> {
let files = vec![(PathBuf::from("/rtl/m.sv"), MOVED.to_string())];
let at = MOVED.find("module m").expect("header") as u32;
let edit = crate::convert_to_ansi(&files, Path::new("/rtl/m.sv"), at)
.expect("the conversion the attacks corrupt");
edit.edits.into_iter().next().expect("one file").1
}
fn move_attack(corrupted: &str) -> Result<(), String> {
pieces_match(
MOVED,
corrupted,
&move_edits(),
Path::new("/rtl/m.sv"),
"converting `m`'s ports to ANSI",
)
}
#[test]
fn the_moved_comments_the_engine_actually_writes_verify() {
let honest = apply(MOVED, &move_edits());
assert_eq!(move_attack(&honest), Ok(()), "the real output must pass");
assert_eq!(honest.matches("// the note").count(), 2, "both comments survive: {honest}");
assert!(honest.contains("input a, // the note"), "{honest}");
}
#[test]
fn a_move_that_kept_only_one_of_two_identical_comments_is_rejected() {
// The exact hole the character budget exists for: one of the two
// `// the note`s is dropped, and a search for its text still finds
// the other one.
let corrupted = apply(MOVED, &move_edits()).replacen(" // the note", "", 1);
let message = move_attack(&corrupted).expect_err("one comment short is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
#[test]
fn a_move_that_dropped_a_comment_and_invented_another_is_rejected() {
// Same character count, different text: the budget alone would
// forgive this one, and the per-comment search does not.
let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the NOTE", 1);
let message = move_attack(&corrupted).expect_err("a rewritten comment is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
#[test]
fn a_move_that_shortened_a_comment_is_rejected() {
let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the", 1);
let message = move_attack(&corrupted).expect_err("a truncated comment is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
#[test]
fn a_move_that_left_the_comment_where_it_was_is_rejected() {
// The deletion really deleted, but the comment was written back into
// the *body* rather than into the header: every comment is still
// there, and the piece order is not what the edits promised.
let honest = apply(MOVED, &move_edits());
let corrupted = honest
.replace("input a, // the note", "input a,")
.replace("endmodule", "// the note\nendmodule");
// `never_dropped` passes this one: every count is equal on both sides
// (the comment really was deleted and really was written back once).
// The *piece comparison* is the guard, because where a comment lands
// is bound to where the edits put it — which is also the answer to
// "a comment deleted here and written back somewhere unrelated".
let message = move_attack(&corrupted).expect_err("a misplaced comment is a refusal");
assert!(message.contains("where the comment `// the note` belongs"), "{message}");
}
#[test]
fn a_move_that_wrote_the_comment_onto_two_ports_is_rejected() {
// The bug this half of the rule was added for, reproduced as the edits
// that caused it: one declaration declares two ports, and its comment
// is written onto *both*. Nothing is dropped, and the piece comparison
// cannot object — it checks the edits against themselves, and the
// duplicate is in the edits. Only counting the file's comments sees it.
const SHARED: &str = "module m (\n a,\n b\n);\n input a, b; // both\nendmodule\n";
let at = |needle: &str| SHARED.find(needle).expect(needle) as u32;
let (a, b) = (at("\n a,") + 3, at("\n b\n") + 3);
let edits = vec![
TextEdit { range: TextRange::empty(a), new_text: "input ".into() },
TextEdit { range: TextRange::empty(a + 2), new_text: " // both".into() },
TextEdit { range: TextRange::empty(b), new_text: "input ".into() },
TextEdit { range: TextRange::empty(b + 1), new_text: " // both".into() },
TextEdit {
range: TextRange::new(at(" input a,"), at("endmodule")),
new_text: String::new(),
},
];
let corrupted = apply(SHARED, &edits);
assert_eq!(corrupted.matches("// both").count(), 2, "the attack really doubles it");
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
.expect_err("a doubled comment is a refusal");
assert!(message.contains("would write the comment"), "{message}");
}
#[test]
fn a_deletion_that_swallows_a_comment_nothing_writes_back_is_still_refused() {
// The old rule's own case, restated: no edit writes the comment, so
// the relaxation must not reach it.
let start = MOVED.find("input a;").expect("a") as u32;
let end = MOVED.find("\n output").expect("output") as u32;
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
let corrupted = apply(MOVED, &edits);
let message = pieces_match(MOVED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
.expect_err("a deleted comment nothing writes back is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
// ------------------------------------------------------------------
// 2026-09-05 rework: the duplication half, the equation, and attributes
// ------------------------------------------------------------------
#[test]
fn an_insertion_that_duplicates_an_untouched_comment_is_rejected() {
// QA's V-1 pair. Nothing deletes — or even overlaps — the body's own
// `// shared`, and two pure insertions each write it again. Every
// count only grows, so "before is a subset of after" forgives it, and
// the piece comparison cannot object because the duplicates are in the
// edits. Only `wrote <= gone` sees it.
const SHARED: &str =
"module m (\n a,\n b\n);\n input a; // shared\n output b;\nendmodule\n";
let at = |needle: &str| SHARED.find(needle).expect(needle) as u32;
let (a, b) = (at("\n a,") + 4, at("\n b\n") + 4);
let edits = vec![
TextEdit { range: TextRange::empty(a), new_text: " // shared".into() },
TextEdit { range: TextRange::empty(b), new_text: " // shared".into() },
];
let corrupted = apply(SHARED, &edits);
assert_eq!(corrupted.matches("// shared").count(), 3, "the attack really triples it");
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
.expect_err("a duplicated comment is a refusal");
assert!(message.contains("comments are never duplicated"), "{message}");
}
#[test]
fn a_generated_placeholder_may_be_written_where_the_file_already_has_one() {
// The whitelist, and the whole of it. `add_port` and
// `propagate_ports` write `/* TODO: connect */` themselves, and a
// module gains its ports one at a time — so the second addition to a
// file finds the first one's placeholder already sitting there and
// writes another. `wrote > gone` with nothing deleted, and legitimate.
let source = "module top;\n sub u1 (.a(/* TODO: connect */));\nendmodule\n";
let at = source.find("))").expect("list") as u32 + 1;
let edits = vec![TextEdit {
range: TextRange::empty(at),
new_text: ", .b(/* TODO: connect */)".into(),
}];
let spliced = apply(source, &edits);
assert_eq!(spliced.matches("TODO").count(), 2, "{spliced}");
let outcome =
pieces_match(source, &spliced, &edits, Path::new("/rtl/top.sv"), "adding port `b`");
assert_eq!(outcome, Ok(()), "a generated placeholder is the engine's own text");
}
#[test]
fn an_application_that_grew_a_copy_the_edits_do_not_write_is_rejected() {
// Masked corruption of the third kind: the edits are honest — they
// delete both `// the note`s and write both back — and the *applied*
// text carries a third. Neither "nothing is lost" nor "written back
// where it was deleted" can see that; only the equation can.
let corrupted = apply(MOVED, &move_edits()).replace("endmodule", "// the note\nendmodule");
let message = move_attack(&corrupted).expect_err("an invented copy is a refusal");
assert!(message.contains("where its edits account for it"), "{message}");
}
#[test]
fn a_comment_written_back_inside_a_string_or_another_comment_is_rejected() {
// A `//` is only a comment where the lexer says it is. Written back
// inside a string literal, or swallowed into the comment next to it,
// the text is present in the file and absent from its pieces — which
// is exactly the substring search this rule refuses to be.
let honest = apply(MOVED, &move_edits());
let in_string = honest
.replacen(" // the note", "", 1)
.replace("endmodule", " initial $display(\"// the note\");\nendmodule");
let message = move_attack(&in_string).expect_err("a string is not a comment");
assert!(message.contains("comments are never dropped"), "{message}");
let nested = honest
.replacen(" // the note", "", 1)
.replace("// the note", "// the note // the note");
let message = move_attack(&nested).expect_err("one comment is not two");
assert!(message.contains("comments are never dropped"), "{message}");
}
/// A body declaration carrying an attribute instance. `Item.span` covers
/// the `(* keep *)`, so a deletion hides it from *both* sides of the piece
/// comparison exactly the way it hides a comment — QA's finding V-2.
const ATTRIBUTED: &str = "module m (\n a\n);\n (* keep *) input a;\nendmodule\n";
/// The edits an absorbing conversion of `ATTRIBUTED` makes: `input ` (plus
/// whatever `written` says) before the header name, and the whole body
/// declaration gone.
fn attribute_edits(written: &str) -> Vec<TextEdit> {
let at = |needle: &str| ATTRIBUTED.find(needle).expect(needle) as u32;
vec![
TextEdit { range: TextRange::empty(at("\n a\n") + 3), new_text: written.into() },
TextEdit {
range: TextRange::new(at(" (* keep *)"), at("endmodule")),
new_text: String::new(),
},
]
}
fn attribute_attack(edits: &[TextEdit]) -> Result<(), String> {
let corrupted = apply(ATTRIBUTED, edits);
pieces_match(
ATTRIBUTED,
&corrupted,
edits,
Path::new("/rtl/m.sv"),
"converting `m`'s ports to ANSI",
)
}
#[test]
fn a_deletion_that_swallows_an_attribute_is_rejected() {
// The planner refuses this one first (`ports::ansi::attributes_clear`,
// pinned in `tests/ansi.rs`); this is the verifier saying so a second
// time, from the edits alone, for whatever writes them next.
let message = attribute_attack(&attribute_edits("input "))
.expect_err("a dropped attribute is a refusal");
assert!(message.contains("attributes are never dropped"), "{message}");
assert!(message.contains("`(* keep *)`"), "{message}");
}
#[test]
fn an_edit_that_moves_an_attribute_verifies() {
// What the refusal above is protecting: an edit that really does carry
// the attribute over is not what this rule is for.
let edits = attribute_edits("(* keep *) input ");
assert_eq!(attribute_attack(&edits), Ok(()), "a moved attribute is a kept attribute");
assert!(apply(ATTRIBUTED, &edits).contains("(* keep *) input a"));
}
#[test]
fn an_edit_that_rewrote_an_attribute_is_rejected() {
// `(* keep *)` and `(* keep=1 *)` are not the same instruction to a
// synthesizer, and an attribute is matched by exact text.
let message = attribute_attack(&attribute_edits("(* keep=1 *) input "))
.expect_err("a rewritten attribute is a refusal");
assert!(message.contains("attributes are never dropped"), "{message}");
}
#[test]
fn a_splice_that_captures_a_name_outside_the_edit_is_rejected() {
// The resolution half: the module already has a net called `cfg`, and
// the added port would take over what the body's `cfg` means.
let source = "module m (\n input clk\n);\n wire cfg;\n assign cfg = clk;\nendmodule\n";
let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())];
let mut scope = Scope::build(&files);
let end = source.find("input clk").expect("clk") as u32 + "input clk".len() as u32;
let edits = vec![(
0usize,
vec![TextEdit { range: TextRange::empty(end), new_text: ",\n input cfg".into() }],
)];
let outcome = verify_splice(&mut scope, &edits, "m", "adding port `cfg`");
assert!(outcome.is_err(), "a captured body reference must refuse: {outcome:?}");
}
#[test]
fn a_splice_that_leaves_a_file_unparseable_is_rejected() {
let source = "module m (\n input clk\n);\nendmodule\n";
let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())];
let mut scope = Scope::build(&files);
let end = source.find("input clk").expect("clk") as u32 + "input clk".len() as u32;
let edits = vec![(
0usize,
vec![TextEdit { range: TextRange::empty(end), new_text: ", input )( x".into() }],
)];
let outcome = verify_splice(&mut scope, &edits, "m", "adding port `x`");
assert!(outcome.is_err(), "a new parse error is a refusal: {outcome:?}");
}
#[test]
fn an_honest_port_addition_verifies() {
let source = "module m (\n input clk\n);\n wire a;\nendmodule\n";
let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())];
let mut scope = Scope::build(&files);
let end = source.find("input clk").expect("clk") as u32 + "input clk".len() as u32;
let edits = vec![(
0usize,
vec![TextEdit { range: TextRange::empty(end), new_text: ",\n input rst".into() }],
)];
assert_eq!(verify_splice(&mut scope, &edits, "m", "adding port `rst`"), Ok(()));
}
#[test]
fn a_rename_that_edited_the_declaration_but_not_its_uses_is_rejected() {
// The whole point of the resolution check: the tokens are perfect, the
// file still parses, and `a` now names nothing.
let files = vec![(PathBuf::from("/rtl/m.sv"), SOURCE.to_string())];
let mut scope = Scope::build(&files);
let declaration = SOURCE.find("wire a").expect("decl") as u32 + 5;
let partial = vec![(
0usize,
vec![TextEdit {
range: TextRange::new(declaration, declaration + 1),
new_text: "sig".into(),
}],
)];
let outcome = verify(&mut scope, &partial, "a", "sig");
assert!(outcome.is_err(), "a half-done rename must not verify: {outcome:?}");
}
}