Files
lucisv/crates/vlog_refactor/tests/rename.rs
T
lucioandClaude Fable 5 24e8eab78b
ci / checks (push) Successful in 42s
ci / corpus (push) Successful in 20s
vlog_parser: a direction-less first ANSI port parses
IEEE 1800 §23.2.2.2 allows an ANSI header's first port to carry no
direction — the normal spelling for interface ports — but
parse_port_list classified any leading identifier as a non-ANSI list
and errored on what followed. One clause fixes it: a leading Ident is
ANSI when the parser's existing type-then-name lookahead
(at_typed_declarator, which already walks pkg:: chains, #() overrides
and packed dims) or the new 4-token modport lookahead (ident.ident
ident) says so; the complement is exactly the old non-ANSI list, and
macro-led lists never enter the clause. bus_if.mp was a second,
independent gap (it parsed in no position before) and is glued into
DataType::name the way pkg::t already was. No AST change — the new
ports are AnsiPort { dir: None }, the shape later ports always had.
Two match-widenings ride along: bind_data_type and type_def's
type_span read the pre-dot half as the type, and the modport half is
bindable by nothing — pinned for rename by QA.

The safety case, established twice (dev, then QA independently via a
worktree build): corpus 813/820 both sides, TSVs byte-identical, and
all 820 formatted outputs SHA-256-identical across the change; zero
snapshot churn; verify.rs untouched. QA's boundary AST-diff harness
(~20 shapes at the classification edge) and a 50-file
direction-stripping fuzz sweep found no misfire. The
previously-blocked fixtures flipped to first-port order; instantiate
now plans interface-typed port lists instead of refusing. The two
remaining unsupported shapes (generic interface ports, virtual
modport declarations) are pinned by a lead-added test so a future
round changes them on purpose.

24 tests added (dev 21 + QA 2 + lead 1).

docs/features/ansi-first-port/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 20:49:16 -07:00

915 lines
37 KiB
Rust

//! What rename does, and — more importantly — what it refuses to do.
//!
//! Every test drives the public API only: a little in-memory workspace of
//! `(path, text)` pairs, a cursor offset, a new name. Cursors are written as
//! `at(text, "after this", "name")` — the first whole-word occurrence of
//! `name` at or after `after this` — so a test says which occurrence it means
//! instead of counting bytes.
use std::path::{Path, PathBuf};
use vlog_refactor::{prepare_rename, rename, RefactorEdit};
/// A workspace of `(file name, text)` pairs, rooted at a fake directory.
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
files.iter().map(|(name, text)| (PathBuf::from("/rtl").join(name), text.to_string())).collect()
}
fn path(name: &str) -> PathBuf {
PathBuf::from("/rtl").join(name)
}
/// The offset of the first whole-word `name` at or after `prefix`.
fn at(text: &str, prefix: &str, name: &str) -> u32 {
let from = match prefix.is_empty() {
true => 0,
false => {
text.find(prefix).unwrap_or_else(|| panic!("`{prefix}` is not in the text"))
+ prefix.len()
}
};
let is_word = |b: Option<&u8>| b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
let bytes = text.as_bytes();
let mut search = from;
while let Some(hit) = text.get(search..).and_then(|s| s.find(name)) {
let start = search + hit;
let end = start + name.len();
if !is_word(start.checked_sub(1).and_then(|i| bytes.get(i))) && !is_word(bytes.get(end)) {
return start as u32;
}
search = start + 1;
}
panic!("`{name}` does not occur after `{prefix}`");
}
/// Rename in a one-file workspace and return the resulting text.
fn rename_one(text: &str, prefix: &str, name: &str, new_name: &str) -> Result<String, String> {
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, prefix, name), new_name)?;
Ok(apply(text, &edit, &path("m.sv")))
}
/// Apply a refactoring's edits for one file.
fn apply(text: &str, edit: &RefactorEdit, file: &Path) -> String {
let mut out = String::new();
let mut cursor = 0usize;
for e in edit.edits_for(file) {
out.push_str(&text[cursor..e.range.start as usize]);
out.push_str(&e.new_text);
cursor = e.range.end as usize;
}
out.push_str(&text[cursor..]);
out
}
// ----------------------------------------------------------------------
// every symbol kind
// ----------------------------------------------------------------------
#[test]
fn a_net_is_renamed_at_its_declaration_and_at_every_use() {
let text = "module m;\n wire a;\n assign a = 1;\n assign b = a & a;\nendmodule\n";
assert_eq!(
rename_one(text, "wire", "a", "sig").expect("renames"),
"module m;\n wire sig;\n assign sig = 1;\n assign b = sig & sig;\nendmodule\n"
);
}
#[test]
fn renaming_from_a_use_is_the_same_as_renaming_from_the_declaration() {
let text = "module m;\n wire a;\n assign a = 1;\nendmodule\n";
let from_declaration = rename_one(text, "wire", "a", "sig").expect("renames");
let from_use = rename_one(text, "assign", "a", "sig").expect("renames");
assert_eq!(from_declaration, from_use);
assert!(from_use.contains("wire sig;"));
}
#[test]
fn a_variable_a_parameter_a_localparam_and_a_genvar_all_rename() {
let text = concat!(
"module m #(parameter int W = 4) ();\n",
" localparam int K = W;\n",
" logic [W-1:0] v;\n",
" genvar g;\n",
" generate for (g = 0; g < K; g = g + 1) begin : b\n",
" assign v[g] = 1'b0;\n",
" end endgenerate\n",
"endmodule\n"
);
let renamed = rename_one(text, "parameter int", "W", "WIDTH").expect("parameter");
assert!(renamed.contains("parameter int WIDTH = 4"), "{renamed}");
assert!(renamed.contains("localparam int K = WIDTH;"), "{renamed}");
assert!(renamed.contains("logic [WIDTH-1:0] v;"), "{renamed}");
let renamed = rename_one(text, "localparam int", "K", "COUNT").expect("localparam");
assert!(renamed.contains("localparam int COUNT = W;"), "{renamed}");
assert!(renamed.contains("g < COUNT;"), "{renamed}");
let renamed = rename_one(text, "logic [W-1:0]", "v", "vec").expect("variable");
assert!(renamed.contains("logic [W-1:0] vec;"), "{renamed}");
assert!(renamed.contains("assign vec[g]"), "{renamed}");
let renamed = rename_one(text, "genvar", "g", "gi").expect("genvar");
assert!(renamed.contains("genvar gi;"), "{renamed}");
assert!(renamed.contains("for (gi = 0; gi < K; gi = gi + 1)"), "{renamed}");
assert!(renamed.contains("assign v[gi]"), "{renamed}");
}
#[test]
fn an_ansi_port_renames_everywhere_it_is_used() {
let text = "module m (input logic clk, output logic q);\n assign q = clk;\nendmodule\n";
let renamed = rename_one(text, "input logic", "clk", "clock").expect("renames");
assert_eq!(
renamed,
"module m (input logic clock, output logic q);\n assign q = clock;\nendmodule\n"
);
}
#[test]
fn a_non_ansi_port_renames_in_the_header_and_in_its_declaration() {
// The body declaration is a *reference* to the header port (the semantic
// layer's redeclaration rule), so both must move together.
let text = "module m (a, b);\n input a;\n output b;\n assign b = a;\nendmodule\n";
let renamed = rename_one(text, "module m (", "a", "in_a").expect("renames");
assert_eq!(
renamed,
"module m (in_a, b);\n input in_a;\n output b;\n assign b = in_a;\nendmodule\n"
);
}
#[test]
fn a_typedef_and_its_enum_variants_rename_independently() {
let text = concat!(
"module m;\n",
" typedef enum logic [1:0] { IDLE, BUSY } state_e;\n",
" state_e s;\n",
" assign s = IDLE;\n",
"endmodule\n"
);
let renamed = rename_one(text, "BUSY }", "state_e", "fsm_state_e").expect("typedef");
assert!(renamed.contains("} fsm_state_e;"), "{renamed}");
assert!(renamed.contains(" fsm_state_e s;"), "{renamed}");
assert!(renamed.contains("IDLE, BUSY"), "the variants are untouched: {renamed}");
let renamed = rename_one(text, "{", "IDLE", "ST_IDLE").expect("enum variant");
assert!(renamed.contains("{ ST_IDLE, BUSY }"), "{renamed}");
assert!(renamed.contains("assign s = ST_IDLE;"), "{renamed}");
}
#[test]
fn a_struct_member_renames_where_it_is_declared() {
let text = concat!(
"module m;\n",
" typedef struct packed { logic valid; logic [7:0] data; } bus_t;\n",
" bus_t b;\n",
"endmodule\n"
);
let renamed = rename_one(text, "packed {", "valid", "vld").expect("struct member");
assert!(renamed.contains("logic vld;"), "{renamed}");
}
#[test]
fn a_function_a_task_and_their_arguments_rename() {
let text = concat!(
"module m;\n",
" function automatic int twice(input int v);\n",
" twice = v + v;\n",
" endfunction\n",
" task do_it(input int n);\n",
" endtask\n",
" initial begin\n",
" do_it(twice(3));\n",
" end\n",
"endmodule\n"
);
let renamed = rename_one(text, "automatic int", "twice", "doubled").expect("function");
assert!(renamed.contains("int doubled(input int v)"), "{renamed}");
assert!(renamed.contains("doubled = v + v;"), "{renamed}");
assert!(renamed.contains("do_it(doubled(3));"), "{renamed}");
let renamed = rename_one(text, "twice(input int", "v", "value").expect("argument");
assert!(renamed.contains("twice(input int value)"), "{renamed}");
assert!(renamed.contains("twice = value + value;"), "{renamed}");
let renamed = rename_one(text, "task", "do_it", "run").expect("task");
assert!(renamed.contains("task run(input int n);"), "{renamed}");
assert!(renamed.contains("run(twice(3));"), "{renamed}");
}
#[test]
fn an_instance_name_renames() {
let text = concat!(
"module sub (input clk);\nendmodule\n",
"module top;\n wire c;\n sub u_sub (.clk(c));\nendmodule\n"
);
let renamed = rename_one(text, "module top", "u_sub", "u_child").expect("instance");
assert!(renamed.contains("sub u_child (.clk(c));"), "{renamed}");
}
#[test]
fn a_class_and_its_members_rename() {
let text = concat!(
"package p;\n",
" class item;\n",
" int count;\n",
" function int get();\n",
" return count;\n",
" endfunction\n",
" endclass\n",
"endpackage\n"
);
let renamed = rename_one(text, "int", "count", "n_items").expect("class member");
assert!(renamed.contains("int n_items;"), "{renamed}");
assert!(renamed.contains("return n_items;"), "{renamed}");
}
#[test]
fn a_named_block_label_renames() {
let text = concat!(
"module m;\n",
" initial begin : setup\n",
" #1;\n",
" end\n",
" initial disable setup;\n",
"endmodule\n"
);
let renamed = rename_one(text, "begin :", "setup", "init_block").expect("block label");
assert!(renamed.contains("begin : init_block"), "{renamed}");
assert!(renamed.contains("disable init_block;"), "{renamed}");
}
// ----------------------------------------------------------------------
// cross-file
// ----------------------------------------------------------------------
#[test]
fn a_module_name_renames_in_every_instantiation_in_every_file() {
let sub = "module sub (input clk);\nendmodule\n";
let top = "module top;\n wire c;\n sub u0 (.clk(c));\n sub u1 (.clk(c));\nendmodule\n";
let other = "module other;\n sub u2 ();\nendmodule\n";
let files = workspace(&[("sub.sv", sub), ("top.sv", top), ("other.sv", other)]);
let edit = rename(&files, &path("sub.sv"), at(sub, "module", "sub"), "child").expect("renames");
assert_eq!(edit.file_count(), 3, "all three files");
assert_eq!(edit.edit_count(), 4, "the declaration and three instantiations");
assert_eq!(apply(sub, &edit, &path("sub.sv")), "module child (input clk);\nendmodule\n");
assert!(apply(top, &edit, &path("top.sv")).contains("child u0 (.clk(c));"));
assert!(apply(other, &edit, &path("other.sv")).contains("child u2 ();"));
// Sorted by path, and each file's edits sorted by offset.
let paths: Vec<_> = edit.edits.iter().map(|(p, _)| p.clone()).collect();
let mut sorted = paths.clone();
sorted.sort();
assert_eq!(paths, sorted, "files come back in path order");
for (_, edits) in &edit.edits {
assert!(edits.windows(2).all(|w| w[0].range.end <= w[1].range.start), "sorted, disjoint");
}
}
#[test]
fn renaming_a_module_from_one_of_its_instantiations_updates_the_declaration_too() {
let sub = "module sub (input clk);\nendmodule\n";
let top = "module top;\n sub u0 (.clk(1'b0));\nendmodule\n";
let files = workspace(&[("sub.sv", sub), ("top.sv", top)]);
let edit = rename(&files, &path("top.sv"), at(top, "", "sub"), "child").expect("renames");
assert_eq!(apply(sub, &edit, &path("sub.sv")), "module child (input clk);\nendmodule\n");
assert!(apply(top, &edit, &path("top.sv")).contains("child u0"));
}
#[test]
fn a_package_member_renames_at_every_import_and_scope_use() {
let pkg = "package p;\n localparam int WIDTH = 8;\nendpackage\n";
let a = "module a;\n import p::*;\n wire [WIDTH-1:0] bus;\nendmodule\n";
let b = "module b;\n wire [p::WIDTH-1:0] bus;\nendmodule\n";
let c = "module c;\n import p::WIDTH;\n wire [WIDTH-1:0] bus;\nendmodule\n";
let files = workspace(&[("p.sv", pkg), ("a.sv", a), ("b.sv", b), ("c.sv", c)]);
let edit = rename(&files, &path("p.sv"), at(pkg, "", "WIDTH"), "BUS_W").expect("renames");
assert!(apply(pkg, &edit, &path("p.sv")).contains("localparam int BUS_W = 8;"));
assert!(apply(a, &edit, &path("a.sv")).contains("wire [BUS_W-1:0] bus;"));
assert!(apply(b, &edit, &path("b.sv")).contains("wire [p::BUS_W-1:0] bus;"));
let c_after = apply(c, &edit, &path("c.sv"));
assert!(c_after.contains("import p::BUS_W;"), "{c_after}");
assert!(c_after.contains("wire [BUS_W-1:0] bus;"), "{c_after}");
}
#[test]
fn a_package_name_renames_at_every_import_site() {
let pkg = "package p;\n localparam int K = 1;\nendpackage\n";
let a = "module a;\n import p::*;\n wire [K-1:0] bus;\nendmodule\n";
let files = workspace(&[("p.sv", pkg), ("a.sv", a)]);
let edit = rename(&files, &path("p.sv"), at(pkg, "package", "p"), "cfg_pkg").expect("renames");
assert!(apply(pkg, &edit, &path("p.sv")).contains("package cfg_pkg;"));
assert!(apply(a, &edit, &path("a.sv")).contains("import cfg_pkg::*;"));
}
#[test]
fn a_port_renames_inside_the_connection_lists_of_other_files() {
let sub = "module sub (input logic clk, input logic rst);\nendmodule\n";
let top = "module top;\n sub u0 (.clk(1'b0), .rst(1'b1));\nendmodule\n";
let files = workspace(&[("sub.sv", sub), ("top.sv", top)]);
let edit =
rename(&files, &path("sub.sv"), at(sub, "input logic", "clk"), "clock").expect("renames");
assert!(apply(sub, &edit, &path("sub.sv")).contains("input logic clock,"));
let after = apply(top, &edit, &path("top.sv"));
assert!(after.contains(".clock(1'b0)"), "{after}");
assert!(after.contains(".rst(1'b1)"), "the other connection is untouched: {after}");
}
#[test]
fn an_interface_renames_from_the_declaration_it_types_in_another_file() {
// Overlay promotion (`docs/features/overlay-promotion/README.md`) made
// this reachable: an unqualified type name nothing in the using file
// binds is now an external candidate the workspace answers, so the two
// halves of the rename are one symbol instead of two unrelated words.
// The interface is written in the body rather than in the header, which
// is the shape this test has always pinned. The header spelling reaches
// the same reference since `docs/features/ansi-first-port/README.md`, and
// is asserted below as its own arm.
let iface = "interface bus_if;\nendinterface\n";
let top = "module top;\n virtual bus_if vif;\n bus_if other ();\nendmodule\n";
let files = workspace(&[("bus_if.sv", iface), ("top.sv", top)]);
let edit = rename(&files, &path("top.sv"), at(top, "virtual", "bus_if"), "fabric_if")
.expect("renames");
assert!(apply(iface, &edit, &path("bus_if.sv")).contains("interface fabric_if;"));
let after = apply(top, &edit, &path("top.sv"));
assert!(after.contains("virtual fabric_if vif;"), "{after}");
assert!(after.contains("fabric_if other ()"), "the instantiation too: {after}");
}
#[test]
fn an_interface_renames_through_a_direction_less_ansi_port() {
// The header spelling of the same rename, which needed
// `docs/features/ansi-first-port/README.md` to parse at all: the port is
// first and carries no direction, and its modport travels with the type.
let iface = "interface bus_if;\n modport mp (input a);\nendinterface\n";
let top = "module top (bus_if.mp bus, input logic clk);\nendmodule\n";
let files = workspace(&[("bus_if.sv", iface), ("top.sv", top)]);
let edit =
rename(&files, &path("top.sv"), at(top, "top ", "bus_if"), "fabric_if").expect("renames");
assert!(apply(iface, &edit, &path("bus_if.sv")).contains("interface fabric_if;"));
let after = apply(top, &edit, &path("top.sv"));
assert!(after.contains("module top (fabric_if.mp bus,"), "{after}");
}
#[test]
fn renaming_the_modport_half_of_a_port_type_is_refused() {
// QA attack (`docs/features/ansi-first-port/README.md`): `bus_if.mp bus`
// glues the modport onto the type name, but only the interface half is
// bound (`ItemKind::Modport` is a leaf in `vlog_semantic`, `bind.rs:364`).
// A rename request on the `mp` half must find nothing to rename — never
// silently rename the interface instead, and never corrupt the modport
// spelling.
let iface = "interface bus_if;\n modport mp (input a);\nendinterface\n";
let top = "module top (bus_if.mp bus);\nendmodule\n";
let files = workspace(&[("bus_if.sv", iface), ("top.sv", top)]);
let offset = at(top, "bus_if.", "mp");
let err = rename(&files, &path("top.sv"), offset, "mp2")
.expect_err("the modport half of the type name is not a bound symbol");
assert!(!err.is_empty());
}
// ----------------------------------------------------------------------
// refusals
// ----------------------------------------------------------------------
/// The refusal message for a rename that must not happen.
fn refusal(text: &str, prefix: &str, name: &str, new_name: &str) -> String {
rename_one(text, prefix, name, new_name).expect_err("this rename must be refused")
}
#[test]
fn an_invalid_or_reserved_new_name_is_refused() {
let text = "module m;\n wire a;\n assign a = 1;\nendmodule\n";
for bad in ["", " ", "2fast", "a b", "a+b", "module", "wire", "`MACRO", "a;"] {
let message = refusal(text, "wire", "a", bad);
assert!(
message.contains("identifier")
|| message.contains("keyword")
|| message.contains("empty"),
"`{bad}` refused with an unhelpful message: {message}"
);
}
}
#[test]
fn renaming_a_name_to_itself_is_refused() {
let text = "module m;\n wire a;\nendmodule\n";
assert!(refusal(text, "wire", "a", "a").contains("already has"));
}
#[test]
fn there_is_nothing_to_rename_on_whitespace_a_keyword_or_a_macro() {
let text = "`define WIDTH 8\nmodule m;\n wire a;\n initial $display(\"a\");\nendmodule\n";
let files = workspace(&[("m.sv", text)]);
for offset in [
at(text, "", "module"),
at(text, "", "WIDTH"),
0, // the backtick of `` `define ``
at(text, "", "initial"),
] {
let message = rename(&files, &path("m.sv"), offset, "renamed")
.expect_err("nothing to rename at {offset}");
assert!(message.contains("no symbol to rename"), "at {offset}: {message}");
}
}
#[test]
fn an_unresolved_name_is_refused_rather_than_guessed() {
// `p` is declared in this file, so `p::MISSING` is `NotFound`, not an
// external candidate: no index could change the answer.
let text = concat!(
"package p;\n localparam K = 1;\nendpackage\n",
"module m;\n wire w = p::MISSING;\nendmodule\n"
);
let message = refusal(text, "", "MISSING", "renamed");
assert!(message.contains("not resolved"), "{message}");
}
#[test]
fn a_bare_value_position_typo_never_reaches_an_unrelated_same_named_module() {
// The regression the overlay-promotion round shipped and this round took
// back (QA finding 1, 2026-08-26). `typo_name` on an assignment's LHS is a
// plain expression identifier — `Target::Lexical` via `ExprKind::Ident`,
// not a type window — so it is never given the bare-name path that would
// make it an external candidate. Without that, `locate` takes the
// `NotFound` arm and refuses, instead of rewriting an unrelated file's
// module declaration on nothing but a name collision.
let unrelated = "module typo_name;\nendmodule\n";
let top = "module top;\n assign typo_name = 1'b1;\nendmodule\n";
let files = workspace(&[("typo_name.sv", unrelated), ("top.sv", top)]);
let message = rename(&files, &path("top.sv"), at(top, "assign", "typo_name"), "fixed_name")
.expect_err("a value-position typo must not be renamable across files");
assert!(message.contains("not resolved to any declaration"), "{message}");
}
#[test]
fn a_name_declared_outside_the_indexed_files_is_refused() {
let text = "module m;\n import other_pkg::*;\n wire w = FROM_ELSEWHERE;\nendmodule\n";
let message = refusal(text, "", "FROM_ELSEWHERE", "renamed");
assert!(message.contains("outside the files lucisv indexes"), "{message}");
}
#[test]
fn a_name_that_could_only_come_from_a_base_class_is_refused() {
let text = concat!(
"package p;\n",
" class child extends uvm_object;\n",
" function void go();\n",
" inherited_thing = 1;\n",
" endfunction\n",
" endclass\n",
"endpackage\n"
);
let message = refusal(text, "", "inherited_thing", "renamed");
assert!(message.contains("base class"), "{message}");
}
#[test]
fn a_module_declared_in_two_files_is_refused_from_both_ends() {
let one = "module dup;\nendmodule\n";
let two = "module dup;\nendmodule\n";
let top = "module top;\n dup u0 ();\nendmodule\n";
let files = workspace(&[("one.sv", one), ("two.sv", two), ("top.sv", top)]);
// From a declaration.
let message = rename(&files, &path("one.sv"), at(one, "", "dup"), "renamed")
.expect_err("ambiguous declarations must be refused");
assert!(message.contains("more than one indexed file"), "{message}");
// And from the use, which the overlay answers ambiguously.
let message = rename(&files, &path("top.sv"), at(top, "", "dup"), "renamed")
.expect_err("an ambiguous use must be refused");
assert!(message.contains("more than one indexed file"), "{message}");
}
#[test]
fn a_file_outside_the_indexed_set_is_refused() {
let text = "module m;\n wire a;\nendmodule\n";
let files = workspace(&[("m.sv", text)]);
let message = rename(&files, &path("elsewhere.sv"), 20, "renamed")
.expect_err("an unindexed file must be refused");
assert!(message.contains("not one of the files lucisv indexes"), "{message}");
}
// ----------------------------------------------------------------------
// collisions — the check that makes the rest safe
// ----------------------------------------------------------------------
#[test]
fn renaming_onto_a_name_declared_in_the_same_scope_is_refused() {
let text = "module m;\n wire a;\n wire b;\n assign a = b;\nendmodule\n";
let message = refusal(text, "wire", "a", "b");
assert!(message.contains("would change what"), "{message}");
}
#[test]
fn renaming_onto_a_name_an_inner_scope_declares_is_refused() {
// The renamed net would be captured by the block's own `tmp` at the use
// inside the block.
let text = concat!(
"module m;\n",
" wire a;\n",
" initial begin : blk\n",
" int tmp;\n",
" tmp = a;\n",
" end\n",
"endmodule\n"
);
let message = refusal(text, "wire", "a", "tmp");
assert!(message.contains("would change what"), "{message}");
}
#[test]
fn renaming_onto_a_name_an_outer_scope_declares_is_refused() {
// The other direction: the module-level `outer` use inside the block
// would start naming the renamed local instead.
let text = concat!(
"module m;\n",
" wire outer;\n",
" initial begin : blk\n",
" int local_v;\n",
" local_v = 1;\n",
" if (outer) local_v = 2;\n",
" end\n",
"endmodule\n"
);
let message = refusal(text, "int", "local_v", "outer");
assert!(message.contains("would change what"), "{message}");
}
#[test]
fn a_collision_in_another_file_is_refused_too() {
// `top` already instantiates a module named `child`; renaming `sub` to
// `child` would make that instantiation ambiguous.
let sub = "module sub;\nendmodule\n";
let child = "module child;\nendmodule\n";
let top = "module top;\n sub u0 ();\n child u1 ();\nendmodule\n";
let files = workspace(&[("sub.sv", sub), ("child.sv", child), ("top.sv", top)]);
let message = rename(&files, &path("sub.sv"), at(sub, "", "sub"), "child")
.expect_err("a cross-file collision must be refused");
assert!(message.contains("would change what"), "{message}");
}
#[test]
fn a_collision_with_a_third_file_that_never_spells_the_old_name_is_refused() {
// QA's reproduction: `top.sv` instantiates `child` and never mentions
// `sub`, so it receives no edit — but after renaming `sub` to `child`
// its instantiation would name two modules. Its bytes are untouched; its
// meaning is not, and that is what the verification pass must see.
let sub = "module sub;\nendmodule\n";
let child = "module child;\nendmodule\n";
let top = "module top;\n child u1 ();\nendmodule\n";
let files = workspace(&[("sub.sv", sub), ("child.sv", child), ("top.sv", top)]);
let message = rename(&files, &path("sub.sv"), at(sub, "", "sub"), "child")
.expect_err("an untouched third file's meaning must still be checked");
assert!(message.contains("would change what"), "{message}");
assert!(message.contains("top.sv"), "the file whose meaning moved is named: {message}");
}
#[test]
fn a_third_file_that_merely_mentions_the_new_name_in_a_comment_is_not_a_collision() {
// The watch list is a text filter, so it pulls in files whose only
// mention is prose. Those must not turn into false refusals.
let sub = "module sub;\nendmodule\n";
let top = "// child is a good name for this\nmodule top;\n sub u0 ();\nendmodule\n";
let files = workspace(&[("sub.sv", sub), ("top.sv", top)]);
let edit = rename(&files, &path("sub.sv"), at(sub, "", "sub"), "child").expect("renames");
assert_eq!(edit.edit_count(), 2, "the declaration and the instantiation");
assert!(apply(top, &edit, &path("top.sv")).contains("// child is a good name"));
}
#[test]
fn a_name_that_only_shadows_somewhere_the_rename_never_reaches_is_allowed() {
// `n` exists inside `other`, but nothing the rename touches is in that
// scope, so there is no capture and no reason to refuse.
let text = concat!(
"module m;\n",
" wire a;\n",
" assign a = 1;\n",
"endmodule\n",
"module other;\n",
" int n;\n",
" initial n = 2;\n",
"endmodule\n"
);
let renamed = rename_one(text, "wire", "a", "n").expect("no collision here");
assert!(renamed.contains("wire n;"), "{renamed}");
assert!(renamed.contains(" int n;\n initial n = 2;"), "the other module is untouched");
}
// ----------------------------------------------------------------------
// preprocessor honesty
// ----------------------------------------------------------------------
#[test]
fn a_macro_of_the_same_name_is_warned_about_and_never_edited() {
let text = "`define a 1\nmodule m;\n wire a;\n assign a = 1;\nendmodule\n";
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, "wire", "a"), "sig").expect("renames");
let after = apply(text, &edit, &path("m.sv"));
assert!(after.starts_with("`define a 1\n"), "the macro is untouched: {after}");
assert!(after.contains("wire sig;"));
assert!(
edit.warnings.iter().any(|w| w.contains("macro")),
"the macro must be reported: {:?}",
edit.warnings
);
}
#[test]
fn the_name_inside_a_macro_body_is_warned_about() {
let text = concat!(
"`define SET_A assign a = 1;\n",
"module m;\n",
" wire a;\n",
" assign a = 0;\n",
"endmodule\n"
);
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, "wire", "a"), "sig").expect("renames");
assert!(apply(text, &edit, &path("m.sv")).contains("`define SET_A assign a = 1;"));
assert!(
edit.warnings.iter().any(|w| w.contains("body of macro `SET_A`")),
"{:?}",
edit.warnings
);
}
#[test]
fn the_name_inside_a_macro_invocations_arguments_is_warned_about() {
// A macro invocation is one opaque token, arguments included, so the `a`
// inside `` `BUMP(a) `` cannot be edited. Silence would be the real
// defect: the expansion still spells the old name.
let text = concat!(
"`define BUMP(x) x = x + 1\n",
"module m;\n",
" int a;\n",
" initial `BUMP(a);\n",
"endmodule\n"
);
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, "int", "a"), "b").expect("renames");
assert!(apply(text, &edit, &path("m.sv")).contains("`BUMP(a);"), "opaque stays opaque");
assert!(
edit.warnings.iter().any(|w| w.contains("arguments of the macro invocation `BUMP`")),
"the macro argument must be reported: {:?}",
edit.warnings
);
}
#[test]
fn a_macro_invocation_in_an_untouched_file_is_warned_about_too() {
let pkg = "package p;\n localparam int WIDTH = 8;\nendpackage\n";
let user = concat!(
"`define DECL(w) logic [w-1:0] bus\n",
"module u;\n",
" import p::*;\n",
" `DECL(WIDTH);\n",
"endmodule\n"
);
let files = workspace(&[("p.sv", pkg), ("u.sv", user)]);
let edit = rename(&files, &path("p.sv"), at(pkg, "", "WIDTH"), "BUS_W").expect("renames");
assert!(apply(user, &edit, &path("u.sv")).contains("`DECL(WIDTH);"), "opaque stays opaque");
assert!(
edit.warnings.iter().any(|w| w.contains("macro invocation") && w.contains("u.sv")),
"{:?}",
edit.warnings
);
}
#[test]
fn a_reference_inside_an_ifdef_arm_is_renamed_because_it_is_just_tokens() {
let text = concat!(
"module m;\n",
" wire a;\n",
"`ifdef SYNTHESIS\n",
" assign a = 1;\n",
"`else\n",
" assign a = 0;\n",
"`endif\n",
"endmodule\n"
);
let renamed = rename_one(text, "wire", "a", "sig").expect("renames");
assert_eq!(renamed.matches("assign sig").count(), 2, "both arms: {renamed}");
}
#[test]
fn every_end_label_is_renamed_with_the_declaration_it_closes() {
// Non-compiling output would be corruption by another name: an end label
// that no longer matches its declaration is illegal SystemVerilog.
let text = concat!(
"package p;\n",
" function automatic int f();\n",
" f = 1;\n",
" endfunction : f\n",
" task t();\n",
" endtask : t\n",
" class c;\n",
" endclass : c\n",
"endpackage : p\n",
"module m;\n",
" initial begin : blk\n",
" end : blk\n",
"endmodule : m\n"
);
let cases = [
("package", "p", "cfg_pkg", "endpackage : cfg_pkg"),
("automatic int", "f", "one", "endfunction : one"),
("task", "t", "run", "endtask : run"),
("class", "c", "item", "endclass : item"),
("begin :", "blk", "setup", "end : setup"),
("module", "m", "top", "endmodule : top"),
];
for (prefix, name, new_name, expected_label) in cases {
let renamed = rename_one(text, prefix, name, new_name).expect("renames");
assert!(renamed.contains(expected_label), "renaming {name}: {renamed}");
assert!(
!renamed.contains(&format!(": {name}\n")),
"no stale `{name}` label may survive: {renamed}"
);
}
}
#[test]
fn a_generate_block_label_renames_with_its_end_label() {
let text = concat!(
"module m;\n",
" generate if (1) begin : gblk\n",
" wire w;\n",
" end : gblk\n",
" endgenerate\n",
"endmodule\n"
);
let renamed = rename_one(text, "begin :", "gblk", "guarded").expect("renames");
assert!(renamed.contains("begin : guarded"), "{renamed}");
assert!(renamed.contains("end : guarded"), "{renamed}");
}
#[test]
fn an_end_label_of_a_different_construct_is_never_edited() {
// Two constructs called `inner`. Renaming the module must leave the
// block's `end : inner` exactly where it is — the label is bound to the
// construct it closes, not matched by text.
let text = concat!(
"module holder;\n",
" initial begin : inner\n",
" end : inner\n",
"endmodule\n",
"\n",
"module inner;\n",
"endmodule : inner\n"
);
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, "\nmodule inner", "inner"), "leaf")
.expect("renames");
let after = apply(text, &edit, &path("m.sv"));
assert!(
after.contains(
"begin : inner
end : inner"
),
"the block is untouched: {after}"
);
assert!(
after.contains(
"module leaf;
endmodule : leaf"
),
"{after}"
);
assert_eq!(edit.edit_count(), 2, "the declaration and its own label only");
}
#[test]
fn a_comment_or_string_that_looks_like_an_end_label_is_never_edited() {
let text = concat!(
"module m;\n",
" // endmodule : m\n",
" initial $display(\"endmodule : m\");\n",
"endmodule : m\n"
);
let renamed = rename_one(text, "module", "m", "top").expect("renames");
assert!(renamed.contains("// endmodule : m"), "the comment stays: {renamed}");
assert!(renamed.contains("$display(\"endmodule : m\")"), "the string stays: {renamed}");
assert!(renamed.ends_with("endmodule : top\n"), "the real label moves: {renamed}");
}
#[test]
fn a_mismatched_end_label_is_left_alone_and_says_which_construct_it_is() {
// `endmodule : wrong` is already illegal; lucisv neither edits it nor
// pretends it is fine.
let text = "module m;\n wire a;\nendmodule : wrong\n";
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, "module", "m"), "top").expect("renames");
assert_eq!(apply(text, &edit, &path("m.sv")), "module top;\n wire a;\nendmodule : wrong\n");
assert!(edit.warnings.is_empty(), "nothing spells `m` there: {:?}", edit.warnings);
}
#[test]
fn a_hierarchical_tail_is_left_alone_and_named_as_such() {
let text = concat!(
"module sub;\n wire sig;\nendmodule\n",
"module top;\n",
" sub u_sub ();\n",
" wire w;\n",
" assign w = u_sub.sig;\n",
"endmodule\n"
);
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, "wire", "sig"), "signal").expect("renames");
let after = apply(text, &edit, &path("m.sv"));
assert!(after.contains("wire signal;"), "{after}");
assert!(after.contains("u_sub.sig;"), "the tail is not resolved, so not edited: {after}");
assert!(
edit.warnings.iter().any(|w| w.contains("hierarchical or member tail")),
"{:?}",
edit.warnings
);
}
// ----------------------------------------------------------------------
// the shape of the result
// ----------------------------------------------------------------------
#[test]
fn renaming_and_renaming_back_gives_the_original_text() {
let text = "module m;\n wire a;\n assign a = 1;\n assign b = a;\nendmodule\n";
let once = rename_one(text, "wire", "a", "sig").expect("renames");
let files = workspace(&[("m.sv", once.as_str())]);
let back = rename(&files, &path("m.sv"), at(&once, "wire", "sig"), "a").expect("renames back");
assert_eq!(apply(&once, &back, &path("m.sv")), text);
}
#[test]
fn every_edit_writes_the_new_name_over_exactly_the_old_one() {
let text = "module m;\n wire aa;\n assign aa = aa & 1;\nendmodule\n";
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, "wire", "aa"), "bbb").expect("renames");
assert_eq!(edit.edit_count(), 3);
for e in edit.edits_for(&path("m.sv")) {
assert_eq!(&text[e.range.as_range()], "aa", "an edit must cover exactly the old name");
assert_eq!(e.new_text, "bbb");
}
}
#[test]
fn a_comment_or_string_mentioning_the_name_is_never_touched() {
let text = concat!(
"module m;\n",
" // a is the signal\n",
" wire a;\n",
" initial $display(\"a\");\n",
" assign a = 1;\n",
"endmodule\n"
);
let renamed = rename_one(text, "wire", "a", "sig").expect("renames");
assert!(renamed.contains("// a is the signal"), "{renamed}");
assert!(renamed.contains("$display(\"a\")"), "{renamed}");
assert!(renamed.contains("wire sig;") && renamed.contains("assign sig = 1;"), "{renamed}");
}
#[test]
fn a_utf8_file_keeps_its_bytes_and_its_spans() {
let text = "module m;\n // é ✓ 🎉\n wire a;\n assign a = 1;\nendmodule\n";
let renamed = rename_one(text, "wire", "a", "senal").expect("renames");
assert!(renamed.contains("// é ✓ 🎉"), "{renamed}");
assert!(renamed.contains("wire senal;") && renamed.contains("assign senal = 1;"), "{renamed}");
}
// ----------------------------------------------------------------------
// prepareRename
// ----------------------------------------------------------------------
#[test]
fn prepare_returns_the_identifier_and_its_current_name() {
let text = "module m;\n wire abc;\n assign abc = 1;\nendmodule\n";
let files = workspace(&[("m.sv", text)]);
let offset = at(text, "assign", "abc");
let target = prepare_rename(&files, &path("m.sv"), offset + 1).expect("ok");
assert_eq!(target.name, "abc");
assert_eq!(&text[target.range.as_range()], "abc");
assert_eq!(target.range.start, offset);
}
#[test]
fn prepare_declines_exactly_what_rename_would_decline() {
let text = "`define WIDTH 8\nmodule m;\n wire a;\n wire w = UNKNOWN_NAME;\nendmodule\n";
let files = workspace(&[("m.sv", text)]);
for offset in [at(text, "", "module"), at(text, "", "WIDTH"), at(text, "", "UNKNOWN_NAME")] {
assert!(
prepare_rename(&files, &path("m.sv"), offset).is_err(),
"prepare must decline at {offset}"
);
}
assert!(prepare_rename(&files, &path("m.sv"), at(text, "wire", "a")).is_ok());
}