//! Refactorings for Verilog/SystemVerilog. //! //! This crate plays the role of [rope](https://github.com/python-rope/rope) in //! ruff's world: it turns "rename this" or "give this module another port" //! into a set of byte edits over the files a workspace is made of. Every edit //! comes from a span `vlog_semantic` resolved or from a node `vlog_parser` //! parsed — there is no textual search-and-replace here — and the whole edit //! is verified in memory before it is handed back: each touched file is //! re-tokenized, re-parsed and re-analyzed, and the *entire* refactoring is //! refused if anything the user did not ask for moved. //! //! The crate does no I/O and speaks no protocol. The caller hands over the //! in-scope files as `(path, text)` pairs — the same shape //! `vlog_semantic::WorkspaceIndex::build` takes — and gets back a //! [`RefactorEdit`] or a sentence explaining the refusal. //! //! See `docs/features/refactor-rename/README.md` and //! `docs/features/refactor-ports/README.md` for the refusal lists and the //! verification stories. //! //! Two members of the crate edit nothing. [`instantiation_plan`] answers "what //! would an instantiation of this module look like here", which is rope's //! type-hinting-drives-completion translated to Verilog; it produces text for //! the caller to offer, never a [`RefactorEdit`], so it needs no verification //! pass — see `docs/features/refactor-instantiate/README.md`. //! [`find_references`] answers "where else is this symbol", which is the //! *first half* of a rename: same cursor resolution, same cross-file walk, //! spans instead of edits — see `docs/features/references-nav/README.md`. mod check; mod instantiate; mod ports; mod references; mod rename; pub use references::find_references; pub use instantiate::{ instantiation_plan, module_definition, module_names, InstantiationPlan, Layout, PlanParam, PlanPort, Site, }; pub use ports::{ add_port, enclosing_module, may_have_port_action, port_action_modules, port_actions, propagate_ports, remove_port, ModuleRef, PortAction, }; pub use rename::{ contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget, }; use std::path::PathBuf; use vlog_parser::span::TextRange; /// One replacement inside one file: the bytes to replace, and what to write. #[derive(Debug, Clone, PartialEq, Eq)] pub struct TextEdit { /// Byte range in the file's current text. pub range: TextRange, /// The text that replaces it. pub new_text: String, } /// Everything a refactoring wants applied, plus what the user must be told /// about what it deliberately left alone. /// /// All-or-nothing: a `RefactorEdit` only ever exists after every one of its /// edits verified *together*, so a caller applies all of them or none. #[derive(Debug, Clone, Default)] pub struct RefactorEdit { /// Per file, sorted by path. Each file's edits are sorted by start /// offset, non-overlapping, and none of them is empty. pub edits: Vec<(PathBuf, Vec)>, /// Sentences for the user: occurrences the refactoring could not account /// for (macro bodies, `endmodule :` labels). Informational only — a /// result with warnings is still safe to apply. pub warnings: Vec, } impl RefactorEdit { /// How many files the refactoring touches. pub fn file_count(&self) -> usize { self.edits.len() } /// How many replacements it makes in total. pub fn edit_count(&self) -> usize { self.edits.iter().map(|(_, edits)| edits.len()).sum() } /// The edits for one file, or nothing when it is untouched. pub fn edits_for(&self, path: &std::path::Path) -> &[TextEdit] { self.edits.iter().find(|(p, _)| p == path).map_or(&[], |(_, edits)| edits.as_slice()) } } /// Apply a file's edits to its text. The edits must be sorted and /// non-overlapping, which is what [`RefactorEdit`] promises. pub(crate) fn apply(text: &str, edits: &[TextEdit]) -> String { let mut out = String::with_capacity(text.len()); let mut cursor = 0usize; for edit in edits { let start = edit.range.start as usize; let end = edit.range.end as usize; if start < cursor || end > text.len() { continue; } out.push_str(text.get(cursor..start).unwrap_or("")); out.push_str(&edit.new_text); cursor = end; } out.push_str(text.get(cursor..).unwrap_or("")); out } /// How an edited file's byte offsets moved. Every edit replaces one /// identifier, so a name span either *is* an edit or is disjoint from all of /// them — which is what makes the mapping exact rather than approximate. #[derive(Debug, Clone, Default)] pub(crate) struct Shift { /// `(original span, replacement length)`, sorted by start. edits: Vec<(TextRange, u32)>, } impl Shift { pub(crate) fn new(edits: &[TextEdit]) -> Shift { Shift { edits: edits.iter().map(|e| (e.range, e.new_text.len() as u32)).collect() } } /// Where a span of the original text lands in the edited text. /// /// **Assumes every span is either identical to one edit's range or fully /// disjoint from all of them** — which is what the callers hand over: /// identifier name spans, and edits that either replace a whole name span /// or insert at a position between tokens. A span that *starts strictly /// inside* a non-empty edit range has no meaningful answer here (those /// bytes were replaced wholesale) and the number this returns for one is /// arbitrary, not a location. Filter such spans out before mapping — /// `check::print`'s `excluded` list is how the port refactorings do it. pub(crate) fn map(&self, span: TextRange) -> TextRange { let mut start = span.start; for (range, new_len) in &self.edits { // `range.end <= span.start` rather than `range.start < span.start` // so that an *insertion* — an empty range — pushes the span that // begins exactly where it was written. For a rename, whose edits // all replace a whole name span, the two say the same thing. if range.end <= span.start { // Add before subtracting: the edits are disjoint and all sit // before `span.start`, so this cannot go negative anyway, but // an unsigned subtraction is not a place to rely on that. start = start.saturating_add(*new_len).saturating_sub(range.len()); } } let len = match self.edits.iter().find(|(range, _)| *range == span) { Some((_, new_len)) => *new_len, None => span.len(), }; TextRange::new(start, start + len) } /// True when this exact span is one of the replacements. pub(crate) fn is_edited(&self, span: TextRange) -> bool { self.edits.iter().any(|(range, _)| *range == span) } } #[cfg(test)] mod tests { use super::*; fn edit(start: u32, end: u32, text: &str) -> TextEdit { TextEdit { range: TextRange::new(start, end), new_text: text.to_string() } } #[test] fn applying_edits_replaces_exactly_the_named_bytes() { assert_eq!(apply("abc def abc", &[edit(0, 3, "xy"), edit(8, 11, "xy")]), "xy def xy"); } #[test] fn a_shift_maps_spans_around_and_onto_the_edits() { let edits = vec![edit(0, 3, "xy"), edit(8, 11, "xy")]; let shift = Shift::new(&edits); // The edited spans themselves take the replacement's length. assert_eq!(shift.map(TextRange::new(0, 3)), TextRange::new(0, 2)); assert_eq!(shift.map(TextRange::new(8, 11)), TextRange::new(7, 9)); // A span between them slides by the first edit's delta only. assert_eq!(shift.map(TextRange::new(4, 7)), TextRange::new(3, 6)); assert!(shift.is_edited(TextRange::new(0, 3))); assert!(!shift.is_edited(TextRange::new(4, 7))); } #[test] fn a_longer_replacement_shifts_forward() { let edits = vec![edit(0, 1, "long")]; let shift = Shift::new(&edits); assert_eq!(shift.map(TextRange::new(0, 1)), TextRange::new(0, 4)); assert_eq!(shift.map(TextRange::new(2, 3)), TextRange::new(5, 6)); } }