//! 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 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)], 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 = 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 are never dropped** (CLAUDE.md invariant 3): no deletion may /// cover a comment. A port or connection with a comment on it is refused, /// not silently un-commented. /// 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)], 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 = 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>, after: HashMap>, } impl Excluded { fn new(scope: &Scope, edits: &[(usize, Vec)]) -> 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)], old_name: &str, new_name: &str, ) -> Vec { let mut watched: Vec = 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::>()) } // ---------------------------------------------------------------------- // 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> { 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) )); }; // Invariant 3, checked here rather than trusted to the planner: a deletion // that covers a comment would delete it from both sides of this comparison // and pass, so it is refused outright. for (span, piece) in &old { let deleted = edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, *span)); if deleted && matches!(piece, Piece::Comment(_)) { return Err(format!( "{what} would delete {} in {}; comments are never dropped, so nothing was edited.", piece.describe(), display(path) )); } } let mut expected: Vec = Vec::new(); let mut next = 0usize; let mut written: Vec> = 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); } 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 = 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(()) } /// 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, new_name: String, } impl Shifts { fn new(scope: &Scope, edits: &[(usize, Vec)], 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 { 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 { 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 { 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", ""); assert!(splice_attack(&corrupted).is_err(), "comments are never dropped"); } #[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"); } #[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:?}"); } }