Files
lucisv/crates/vlog_refactor/src/check/mod.rs
T

1240 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.
mod after;
mod ledger;
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::{
ExternalResolutions, ExternalTarget, ReferenceId, Semantics, SymbolKind, WorkspaceIndex,
};
use crate::rename::{contains_word, display, Scope};
use crate::trace::VerifyTrace;
use crate::{apply, Shift, TextEdit};
use after::{after_index, after_print};
use ledger::{overlaps, pieces_match, region_of, Split, Transit};
/// 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,
trace: &mut VerifyTrace,
) -> 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()) };
trace.tokens.measure(|| 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]);
trace.watched = watched.len();
trace.watched_bytes = watched.iter().filter_map(|&i| scope.text(i)).map(str::len).sum();
let mut before: Vec<Print> = Vec::new();
for &i in &watched {
if !trace.before.measure(|| scope.analysis(i).is_some()) {
return Err(ABANDONED.to_string());
}
}
for &i in &watched {
let (Some(path), Some(analysis)) = (scope.path(i), scope.cached(i)) else {
return Err(ABANDONED.to_string());
};
trace.before.measure(|| {
before.push(print(
&analysis.semantics,
&analysis.external,
scope.index(),
path,
&shifts,
&[],
))
});
}
let (after_index, edited_analyses) = trace.rebuild.measure(|| after_index(scope, &edited));
for (n, &i) in watched.iter().enumerate() {
let Some(path) = scope.path(i) else { return Err(ABANDONED.to_string()) };
let after = trace
.after
.measure(|| after_print(scope, i, path, &after_index, &edited_analyses, &[]));
let (Some(after), Some(before)) = (after, 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 [`ledger::Ledger`].
/// 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> {
verify_move(scope, edits, &[watch_name], what, &[])
}
/// What a move does with one file's bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Origin {
/// The bytes **leave**: the file is edited, its region is deleted, and
/// what was inside it lands in a destination. Extracting a module works
/// this way, and so does the empty region that names a destination.
Moved,
/// The bytes are **copied**: the file is not edited at all, and what its
/// region holds may be written once into the destinations. Inlining a
/// module works this way — `S`'s declaration stays exactly where it is and
/// its items are copied into `M`.
Copied,
}
/// One file a move names, and what it does with that file's bytes.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Moving {
pub(crate) file: usize,
pub(crate) region: TextRange,
pub(crate) origin: Origin,
}
impl Moving {
/// The file a move takes its text **out of**, and the bytes it takes.
pub(crate) fn source(file: usize, region: TextRange) -> Moving {
Moving { file, region, origin: Origin::Moved }
}
/// A file a move **copies** out of, and the bytes it copies. The file
/// itself must come out untouched, which is checked rather than assumed.
pub(crate) fn copy(file: usize, region: TextRange) -> Moving {
Moving { file, region, origin: Origin::Copied }
}
/// A file that only **receives** — named with an empty region, because it
/// sends nothing.
pub(crate) fn destination(file: usize) -> Moving {
Moving { file, region: TextRange::empty(0), origin: Origin::Moved }
}
}
/// [`verify_splice`], for a refactoring that **moves text from one file into
/// another** — which is what extracting a module into its own file is.
///
/// Everything is the same except the accounting of the pieces that are never
/// dropped. Per file, "a comment this edit deletes must be one this edit
/// writes back" is exactly right for every refactoring that stays inside one
/// file, and exactly wrong for a move: the comment is deleted in `M.sv` and
/// written in `N.sv`, so neither file balances on its own.
///
/// **The widening is bound to the bytes that move, not to the files.**
/// `moving` names every file the move touches: a **source**, with the byte
/// range the move takes its text out of (the selection), and a
/// **destination** — a file that only receives — with an empty range. Per file
/// `f` and per never-dropped text `t`, where `before`/`after` are the file's
/// own counts, `gone` the old pieces a non-empty edit range covers, `wrote` the
/// pieces the edits' own text spells, and `out` the pieces of `gone` that sit
/// **inside** `f`'s region — the ones in transit:
///
/// 1. `after_f + out_f >= before_f` — nothing is lost. A file may end up short
/// only by exactly what left through its own region.
/// 2. `wrote_f <= (gone_f - out_f) + in_f`, unless the text is one a
/// refactoring generated itself (`ledger::generated`) — nothing is duplicated. `in_f` is the whole
/// transit (`Σ out`) for a destination and zero for everyone else, so a
/// deletion *outside* the region is an ordinary deletion that has to be
/// written back in its own file exactly as before.
/// 3. `after_f == before_f - gone_f + wrote_f` — the applied text says exactly
/// what the edits say, transit out counted as gone and transit in as wrote.
/// 4. `Σ over destinations of (wrote - gone) == Σ over sources of out` — the
/// transit lands, exactly once, in the files the move named.
///
/// A file `moving` does not name keeps the per-file contract untouched, so a
/// piece in transit to a file the move never named is refused twice over: by
/// that file's own rule 2, and by rule 4. See
/// `docs/features/extract-inline-module/README.md` for the attack pairs.
///
/// **A third kind of file: one the move only *copies* out of**
/// ([`Origin::Copied`]). Inlining a module is the mirror of extracting one —
/// `S`'s items are copied into `M` and `S`'s own file is not touched at all —
/// so the pieces `M` writes have an origin without anything having been
/// deleted anywhere. Such a file sends its region's pieces into the transit
/// exactly as a source does, and is held to one further rule of its own:
///
/// 0. **A copied file is not edited.** It appears in no edit, so its text is
/// the text it had; anything else is a contradiction the move does not get
/// to make, and is refused before the equations are even asked.
///
/// `watched` are the names whose meaning the refactoring changes (the module
/// whose ports moved; both module names, for an extraction), which is what
/// widens the resolution check beyond the edited files.
pub(crate) fn verify_move(
scope: &mut Scope,
edits: &[(usize, Vec<TextEdit>)],
watched_names: &[&str],
what: &str,
moving: &[Moving],
) -> 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);
}
let mut transit = Transit::default();
// Rule 0, and the pieces a copy sends: a file the move only copies out of
// is one it may not have edited, and what its region holds is what the
// destinations are allowed to write.
for copied in moving.iter().filter(|m| m.origin == Origin::Copied) {
let (Some(path), Some(text)) = (scope.path(copied.file), scope.text(copied.file)) else {
return Err(abandoned);
};
if edits.iter().any(|(i, _)| *i == copied.file) {
return Err(format!(
"{what} would edit {}, which it only copies out of; no edits were made.",
display(path)
));
}
transit.copy(&display(path), text, copied.region, what)?;
}
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
let Some(before) = scope.text(*i) else { return Err(abandoned) };
let split = Split::read(before, text, edits, path, what)?;
match region_of(moving, *i) {
// A file the move names balances against the pieces in transit
// rather than on its own; its positional comparison is unchanged.
Some(region) => {
transit.add(&display(path), region, &split, edits);
split.positions_match(edits, path, what)?;
}
None => pieces_match(&split, 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)
));
}
}
transit.check(what)?;
let shifts = Shifts::new(scope, edits, "");
let excluded = Excluded::new(scope, edits);
let watched = watched_files(scope, edits, watched_names);
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, edited_analyses) = after_index(scope, &edited);
for (n, &i) in watched.iter().enumerate() {
let Some(path) = scope.path(i) else { return Err(abandoned) };
let after =
after_print(scope, i, path, &after_index, &edited_analyses, excluded.after(path));
let (Some(after), Some(before)) = (after, 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>)], names: &[&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 names.iter().any(|name| contains_word(text, name)) {
watched.push(i);
}
}
watched.sort_unstable();
watched
}
const ABANDONED: &str = "lucisv could not verify the rename, so it made no edits.";
// ----------------------------------------------------------------------
// 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(())
}
// ----------------------------------------------------------------------
// 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");
}
#[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(()));
}
// ------------------------------------------------------------------
// organize imports: the resolution check as its second net (§52.1)
// ------------------------------------------------------------------
//
// The engine refuses to *judge* an import it cannot be sure about; this
// is what catches a judgement that was wrong anyway. Both pairs below are
// lexically perfect deletions of a whole `import` line — the token stream
// loses exactly the pieces the edit deletes and nothing else — so only the
// resolution half can tell them apart.
/// A package and a module importing it, as two files.
fn imported() -> Vec<(PathBuf, String)> {
vec![
(
PathBuf::from("/rtl/a_pkg.sv"),
"package a_pkg;\n typedef int a_t;\nendpackage\n".into(),
),
(
PathBuf::from("/rtl/m.sv"),
"module m;\n import a_pkg::*;\n a_t sig;\nendmodule\n".into(),
),
]
}
/// The deletion of `m.sv`'s whole `import` line, newline included.
const IMPORT_LINE: &str = " import a_pkg::*;\n";
fn import_deletion(text: &str) -> Vec<(usize, Vec<TextEdit>)> {
let start = text.find(IMPORT_LINE).expect("import") as u32;
let end = start + IMPORT_LINE.len() as u32;
vec![(
1usize,
vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }],
)]
}
#[test]
fn removing_an_import_a_reference_needs_is_rejected() {
// The attack: an honest-looking edit that deletes exactly one import
// line, where `a_t` resolved through it. Nothing lexical objects —
// and afterwards `a_t` names nothing at all.
let files = imported();
let mut scope = Scope::build(&files);
let text = files[1].1.clone();
let outcome =
verify_splice(&mut scope, &import_deletion(&text), "", "organizing the imports");
let message = outcome.expect_err("a needed import is a refusal");
assert!(message.contains("would change what `a_t` means"), "{message}");
}
#[test]
fn removing_an_import_nothing_needs_verifies() {
// The same deletion, of an import the body does not reach through:
// `a_t` is declared here, so every name resolves where it did.
let files = vec![
files_entry("/rtl/a_pkg.sv", "package a_pkg;\n typedef int a_t;\nendpackage\n"),
files_entry(
"/rtl/m.sv",
"module m;\n import a_pkg::*;\n typedef bit a_t;\n a_t sig;\nendmodule\n",
),
];
let mut scope = Scope::build(&files);
let text = files[1].1.clone();
assert_eq!(
verify_splice(&mut scope, &import_deletion(&text), "", "organizing the imports"),
Ok(())
);
}
fn files_entry(path: &str, text: &str) -> (PathBuf, String) {
(PathBuf::from(path), text.to_string())
}
// ------------------------------------------------------------------
// the moved-piece rule, and the attacks on it (CLAUDE.md invariant 4)
// ------------------------------------------------------------------
//
// 2026-09-05: `verify_move` lets a piece that is never dropped travel out
// of the region an extraction moves and into the file that receives it — a
// comment deleted in `m.sv` and written in `sum.sv` balances across the
// move and in neither file alone.
//
// 2026-09-06 rework (QA's finding V1): the allowance is bound to the
// **region**, not to the files, and every attack below goes through the
// production entry point — a real `Scope`, the raw `TextEdit`s and
// `verify_move` itself, positional comparison and all. The pair in
// `a_copy_deleted_outside_the_region_is_not_one_the_move_may_balance` is
// the one the file-scoped pool forgave, and no ledger-only helper could
// have seen it.
/// A module with a comment and an attribute inside the region an
/// extraction moves — the two pieces the ledger is the only guard for.
const EXTRACT: &str = "module m (\n input logic a,\n input logic b,\n output logic q\n);\n logic s;\n (* keep *) assign s = a & b; // the and\n assign q = s | 1'b0;\nendmodule\n";
const MOVED_WHAT: &str = "extracting `sum` out of `m`";
/// One extraction, as the verifier is told about it: the edits per file,
/// and the bytes the move carries out of `m.sv`.
struct Plan {
m: Vec<TextEdit>,
n: Vec<TextEdit>,
region: TextRange,
}
/// The edits the extraction really makes for `source`: one replacement in
/// `m.sv`, one insertion into an empty `sum.sv`.
fn extraction(source: &str) -> Plan {
let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())];
let start = source.find("(* keep *)").expect("attribute") as u32;
let end = source.find("// the and").expect("comment") as u32 + 10;
let edit = crate::extract_module(
&files,
Path::new("/rtl/m.sv"),
start,
end,
"sum",
crate::Home::NewFile,
)
.expect("the extraction the attacks corrupt");
let m = edit.edits_for(&PathBuf::from("/rtl/m.sv")).to_vec();
let n = edit.edits_for(&PathBuf::from("/rtl/sum.sv")).to_vec();
let region = m.first().expect("the replacement").range;
Plan { m, n, region }
}
/// Verify a plan the way the engine does: a real `Scope` over the two
/// files, the raw edits, and the production `verify_move`. `moves` is what
/// the engine passes — `m.sv` as the source of the region and `sum.sv` as
/// the file that receives — or nothing at all, for the opt-in test.
fn verified(source: &str, plan: &Plan, moves: bool) -> Result<(), String> {
let files = vec![
(PathBuf::from("/rtl/m.sv"), source.to_string()),
(PathBuf::from("/rtl/sum.sv"), String::new()),
];
let mut scope = Scope::build(&files);
let at = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (m, n) = (at("/rtl/m.sv"), at("/rtl/sum.sv"));
let edits = vec![(m, plan.m.clone()), (n, plan.n.clone())];
let moving = match moves {
true => vec![Moving::source(m, plan.region), Moving::destination(n)],
false => Vec::new(),
};
verify_move(&mut scope, &edits, &["m", "sum"], MOVED_WHAT, &moving)
}
#[test]
fn the_move_the_engine_actually_produces_verifies() {
let plan = extraction(EXTRACT);
assert_eq!(verified(EXTRACT, &plan, true), Ok(()), "the real output must pass");
let (m, n) = (apply(EXTRACT, &plan.m), apply("", &plan.n));
// The comment *and* the attribute travel, which is the whole of what
// the allowance is for.
assert!(n.contains("// the and") && n.contains("(* keep *)"), "{n}");
assert!(!m.contains("// the and") && !m.contains("(* keep *)"), "{m}");
}
#[test]
fn a_copy_deleted_outside_the_region_is_not_one_the_move_may_balance() {
// QA's V1 pair, and the reason the allowance is bound to the region
// rather than to the files. `m.sv` holds the same comment twice: one
// inside the region, one on a line the extraction never touches. The
// corrupted plan deletes *both* and writes the comment into `sum.sv`
// twice — so a pool kept over the two files balanced two in against
// two out and forgave it, while `m.sv` alone lost a comment nothing
// ever moved.
let source = EXTRACT.replace("assign q = s | 1'b0;", "assign q = s | 1'b0; // the and");
let mut plan = extraction(&source);
let stray = source.rfind("// the and").expect("the untouched copy") as u32;
plan.m.push(TextEdit {
range: TextRange::new(stray - 1, stray + 10),
new_text: String::new(),
});
for edit in &mut plan.n {
edit.new_text = edit.new_text.replace("// the and", "// the and\n // the and");
}
// Each file is honest about its own edits — this is not a positional
// failure — and the counts over the pair really do balance: two copies
// before, two after. Only the region says which of them moved.
let (m, n) = (apply(&source, &plan.m), apply("", &plan.n));
assert_eq!(source.matches("// the and").count(), 2, "two copies to begin with");
assert_eq!(
m.matches("// the and").count() + n.matches("// the and").count(),
2,
"and two after, which is what a pool kept over the files forgave"
);
let message = verified(&source, &plan, true).expect_err("a lost copy is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
assert!(message.contains("m.sv"), "{message}");
}
#[test]
fn a_comment_that_lands_twice_in_the_new_file_is_rejected() {
// The corruption in the *edits* rather than in the application: the
// new file's text carries the comment twice where the region held it
// once. The transit is an allowance for one.
let mut plan = extraction(EXTRACT);
for edit in &mut plan.n {
edit.new_text = edit.new_text.replace("// the and", "// the and\n // the and");
}
let message = verified(EXTRACT, &plan, true).expect_err("a duplicate is a refusal");
assert!(message.contains("never duplicated"), "{message}");
}
#[test]
fn a_comment_left_behind_as_well_as_moved_is_rejected() {
// Deleted once, written twice — once where it belongs and once back
// into the file it came from, above the instantiation.
let mut plan = extraction(EXTRACT);
for edit in &mut plan.m {
edit.new_text = format!("// the and\n {}", edit.new_text);
}
let message = verified(EXTRACT, &plan, true).expect_err("a duplicate is a refusal");
assert!(message.contains("never duplicated"), "{message}");
}
#[test]
fn a_comment_the_move_carries_that_lands_nowhere_is_rejected() {
// The whole hazard of the allowance: the comment leaves `m.sv`
// legitimately, and the corrupted `sum.sv` simply never writes it.
// Per file, both halves look innocent.
let mut plan = extraction(EXTRACT);
for edit in &mut plan.n {
edit.new_text = edit.new_text.replace(" // the and", "");
}
let message = verified(EXTRACT, &plan, true).expect_err("a lost comment is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
assert!(message.contains("write it back nowhere"), "{message}");
}
#[test]
fn an_attribute_the_move_carries_that_lands_nowhere_is_rejected() {
let mut plan = extraction(EXTRACT);
for edit in &mut plan.n {
edit.new_text = edit.new_text.replace("(* keep *) ", "");
}
let message = verified(EXTRACT, &plan, true).expect_err("a lost attribute is a refusal");
assert!(message.contains("attributes are never dropped"), "{message}");
}
#[test]
fn a_comment_the_new_file_invents_with_nothing_in_transit_is_rejected() {
// Nothing deleted it anywhere, and the transit is the only allowance a
// destination has.
let mut plan = extraction(EXTRACT);
for edit in &mut plan.n {
edit.new_text = edit.new_text.replace("endmodule", " // invented\nendmodule");
}
let message = verified(EXTRACT, &plan, true).expect_err("an invented comment is a refusal");
assert!(message.contains("never duplicated"), "{message}");
assert!(message.contains("// invented"), "{message}");
}
#[test]
fn a_generated_placeholder_the_new_file_writes_is_not_a_duplicate() {
// The whitelist is untouched by the rework: `/* TODO: connect */` is
// text a refactoring writes itself, not a piece it moves.
let mut plan = extraction(EXTRACT);
for edit in &mut plan.n {
edit.new_text = edit.new_text.replace("endmodule", " /* TODO: connect */\nendmodule");
}
assert_eq!(verified(EXTRACT, &plan, true), Ok(()), "the whitelist still whitelists");
}
#[test]
fn a_piece_in_transit_to_a_file_the_move_did_not_name_is_rejected() {
// The move names `m.sv` and `sum.sv`; the plan writes the new module
// into a third file instead. That file never asked for an allowance,
// so it keeps the per-file contract and the comment it writes is one
// it never deleted.
let plan = extraction(EXTRACT);
let files = vec![
(PathBuf::from("/rtl/m.sv"), EXTRACT.to_string()),
(PathBuf::from("/rtl/other.sv"), String::new()),
(PathBuf::from("/rtl/sum.sv"), String::new()),
];
let mut scope = Scope::build(&files);
let at = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (m, other, sum) = (at("/rtl/m.sv"), at("/rtl/other.sv"), at("/rtl/sum.sv"));
let edits = vec![(m, plan.m.clone()), (other, plan.n.clone())];
let moving = vec![Moving::source(m, plan.region), Moving::destination(sum)];
let message = verify_move(&mut scope, &edits, &["m", "sum"], MOVED_WHAT, &moving)
.expect_err("a file the move did not name is not a destination");
assert!(message.contains("never duplicated"), "{message}");
}
#[test]
fn a_deletion_wider_than_the_region_is_an_ordinary_deletion() {
// The old fifth attack, through the production entry: a deletion
// widened past the selection swallows `// the rest`, which was never
// the extraction's to move and which nothing writes back. Only the
// pieces *inside* the region are in transit.
let source = EXTRACT.replace("assign q = s | 1'b0;", "assign q = s | 1'b0; // the rest");
let mut plan = extraction(&source);
let end = source.find("// the rest").expect("comment") as u32 + 11;
plan.m[0].range = TextRange::new(plan.m[0].range.start, end);
let message = verified(&source, &plan, true).expect_err("a swallowed comment is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
assert!(message.contains("// the rest"), "{message}");
}
#[test]
fn a_region_that_does_not_cover_what_the_edits_delete_is_rejected() {
// The planner lying about its own region is the same corruption seen
// from the other side: it says the move takes only the `assign`, and
// its edit deletes the trailing comment too.
let mut plan = extraction(EXTRACT);
let comment = EXTRACT.find("// the and").expect("comment") as u32;
plan.region = TextRange::new(plan.region.start, comment);
let message = verified(EXTRACT, &plan, true).expect_err("a lied-about region is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
#[test]
fn the_widening_is_opt_in_and_a_refactoring_that_asked_for_none_still_gets_none() {
// The same honest extraction, verified with an *empty* `moving` list:
// the per-file contract refuses it, which is what says nothing else in
// this crate lost a guard when `verify_move` gained one.
let plan = extraction(EXTRACT);
let message = verified(EXTRACT, &plan, false)
.expect_err("without `moving`, a cross-file move is a dropped piece");
assert!(message.contains("are never dropped"), "{message}");
assert_eq!(verified(EXTRACT, &plan, true), Ok(()), "and with it, the same plan verifies");
}
// ------------------------------------------------------------------
// the copied-piece rule, and the attacks on it (CLAUDE.md invariant 4)
// ------------------------------------------------------------------
//
// 2026-09-06: `Origin::Copied` lets a piece that is never dropped be
// *copied* out of a file the edit does not touch — which is what inlining
// a module is. `S`'s comment arrives in `M` with nothing deleted anywhere,
// so rule 2's `wrote <= gone` has to be widened by exactly the transit;
// every pair below is a crafted corruption that widening could plausibly
// forgive, and every one goes through the production `verify_move` with a
// real `Scope` and the edits `inline_module` really produces.
/// The two files an inline works over: `sub`, with a comment inside the
/// body that is copied, and the `top` that instantiates it.
const SUB: &str =
"module sub (\n input logic a,\n output logic q\n);\n (* keep *) logic s; // the and\n assign s = a;\n assign q = s;\nendmodule\n";
const TOP: &str =
"module top (\n input logic x,\n output logic z\n);\n sub u_sub (.a(x), .q(z));\nendmodule\n";
const INLINED_WHAT: &str = "inlining `sub` into `top`";
fn inline_files() -> Vec<(PathBuf, String)> {
vec![
(PathBuf::from("/rtl/sub.sv"), SUB.to_string()),
(PathBuf::from("/rtl/top.sv"), TOP.to_string()),
]
}
/// The edits `inline_module` really makes in `top.sv`.
fn inline_edits() -> Vec<TextEdit> {
let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2;
crate::inline_module(&inline_files(), Path::new("/rtl/top.sv"), at)
.expect("the inline the attacks corrupt")
.edits_for(&PathBuf::from("/rtl/top.sv"))
.to_vec()
}
/// Verify an inline the way the engine does: `top.sv` receives, `sub.sv`
/// is copied out of over the bytes of its body. `sub` is the text of the
/// file the move copies from — the attacks that edit it pass a different
/// one — and `copies` is what the engine passes, or nothing at all.
fn verified_inline(
sub: &str,
top_edits: &[TextEdit],
sub_edits: &[TextEdit],
copies: bool,
) -> Result<(), String> {
let files = vec![
(PathBuf::from("/rtl/sub.sv"), sub.to_string()),
(PathBuf::from("/rtl/top.sv"), TOP.to_string()),
];
let mut scope = Scope::build(&files);
let at = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (s, t) = (at("/rtl/sub.sv"), at("/rtl/top.sv"));
let mut edits = vec![(t, top_edits.to_vec())];
if !sub_edits.is_empty() {
edits.push((s, sub_edits.to_vec()));
}
edits.sort_by_key(|(i, _)| *i);
let body = TextRange::new(
sub.find("(* keep *)").map_or(0, |at| at as u32),
sub.find("endmodule").map_or(0, |at| at as u32),
);
let moving = match copies {
true => vec![Moving::destination(t), Moving::copy(s, body)],
false => Vec::new(),
};
verify_move(&mut scope, &edits, &["top"], INLINED_WHAT, &moving)
}
#[test]
fn the_inline_the_engine_actually_produces_verifies() {
let edits = inline_edits();
assert_eq!(verified_inline(SUB, &edits, &[], true), Ok(()), "the real output must pass");
let top = apply(TOP, &edits);
// The comment and the attribute are copies: `sub.sv` still has both.
assert!(top.contains("// the and") && top.contains("(* keep *)"), "{top}");
assert_eq!(SUB.matches("// the and").count(), 1, "and `sub.sv` is untouched");
}
#[test]
fn a_copied_comment_written_twice_is_rejected() {
// The transit is an allowance for one copy per copy: the region holds
// the comment once, so `top.sv` may write it once.
let mut edits = inline_edits();
for edit in &mut edits {
edit.new_text = edit.new_text.replace("// the and", "// the and\n // the and");
}
let message = verified_inline(SUB, &edits, &[], true).expect_err("a duplicate is refused");
assert!(message.contains("never duplicated"), "{message}");
}
#[test]
fn a_copied_comment_that_lands_nowhere_is_rejected() {
// The mirror hazard: the piece is in the region the move says it
// copies, and the text written into `top.sv` simply never carries it.
let mut edits = inline_edits();
for edit in &mut edits {
edit.new_text = edit.new_text.replace(" // the and", "");
}
let message = verified_inline(SUB, &edits, &[], true).expect_err("a lost copy is refused");
assert!(message.contains("comments are never dropped"), "{message}");
assert!(message.contains("write it back nowhere"), "{message}");
}
#[test]
fn a_copied_attribute_that_lands_nowhere_is_rejected() {
let mut edits = inline_edits();
for edit in &mut edits {
edit.new_text = edit.new_text.replace("(* keep *) ", "");
}
let message =
verified_inline(SUB, &edits, &[], true).expect_err("a lost attribute is refused");
assert!(message.contains("attributes are never dropped"), "{message}");
}
#[test]
fn a_piece_written_into_the_destination_that_the_region_does_not_hold_is_rejected() {
// The allowance is bound to the copied bytes, not to the copied file:
// a comment `top.sv` invents has no origin at all, and one lifted out
// of `sub`'s *header* — outside the region the move named — has none
// either.
let mut edits = inline_edits();
for edit in &mut edits {
edit.new_text.push_str("\n // invented");
}
let message = verified_inline(SUB, &edits, &[], true).expect_err("an invention is refused");
assert!(message.contains("never duplicated"), "{message}");
assert!(message.contains("// invented"), "{message}");
}
#[test]
fn a_generated_placeholder_the_destination_writes_is_not_a_duplicate() {
// The whitelist is untouched by the widening.
let mut edits = inline_edits();
for edit in &mut edits {
edit.new_text.push_str("\n /* TODO: connect */");
}
assert_eq!(verified_inline(SUB, &edits, &[], true), Ok(()), "the whitelist still holds");
}
#[test]
fn an_edit_to_the_file_the_move_only_copies_out_of_is_rejected() {
// Rule 0. The copy allowance is granted on the strength of `sub.sv`
// coming out of the refactoring unchanged; an edit to it — here the
// deletion of the very comment being copied, which would make the two
// halves balance as a *move* — is a contradiction rather than a plan.
let start = SUB.find(" // the and").expect("the comment") as u32;
let sub_edits = vec![TextEdit {
range: TextRange::new(start, start + " // the and".len() as u32),
new_text: String::new(),
}];
let message = verified_inline(SUB, &inline_edits(), &sub_edits, true)
.expect_err("a copied file that is edited is a refusal");
assert!(message.contains("only copies out of"), "{message}");
assert!(message.contains("sub.sv"), "{message}");
}
#[test]
fn the_copy_allowance_is_opt_in_and_an_inline_that_asked_for_none_gets_none() {
// The same honest inline with an empty `moving` list: `top.sv` writes
// a comment it never deleted, which is what the per-file contract has
// always refused.
let edits = inline_edits();
let message = verified_inline(SUB, &edits, &[], false)
.expect_err("without `moving`, a copy is a duplicated comment");
assert!(message.contains("never duplicated"), "{message}");
assert_eq!(verified_inline(SUB, &edits, &[], true), Ok(()), "and with it, it verifies");
}
#[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", &mut VerifyTrace::default());
assert!(outcome.is_err(), "a half-done rename must not verify: {outcome:?}");
}
}