Files
lucisv/crates/vlog_refactor/tests/rename_implicit.rs
T
lucioandClaude Fable 5.1 4edada583f Rename keeps implicit connections bound (TODO-MCP M3.5): .name and .* rewritten explicitly, verified by a binding print; the LSP hands the engine one more hop
vlog_refactor: a rename used to cut a `.name` shorthand or a `.*` wildcard binding — port d → din of leaf left `leaf u (.*)` binding nothing and turned `.d` into `.din` against a parent with no net din; renaming the parent's net cut both — and verified clean, because the semantic layer records the port half of `.name` and nothing of `.*` (M3 QA finding 1; the LSP shared it). rename/{connections,sites,layout}.rs: an AST walk over every named connection list finds the implicit bindings and looks each name up the way the language does (nearest declaration outward; a bind's target module; a bare instance name resolved through the instantiation table with the bind's enclosing module's own instances winning, §23.11); `.p` becomes `.q(p)`, a `.*` that bound the name gains `.q(p)` / `.n(m)` appended in the list's own layout (comma before a trailing // comment, CRLF kept); every rewrite listed in warnings; refused by name: a `.*` into a module lucisv cannot read or finds declared twice, a list split by ifdefs or holding unparsed text, a hierarchical bind target, a `.*` that would start binding the new name, a package variable an import might hand to a `.*`. check/implicit.rs: the verifier learns the shape — a file with insertions passes only if every replacement is the old name becoming the new and every insertion is one of four connection templates at the exact slot the rewrite writes (a shorthand's name end; between a `.*` list's last element and its `)`), the comma and its `.X(Y)` only as a pair in one list, no slot at all in a list holding an error element — and every implicit binding (port half and net half) is printed before and after and must match. lucisv_server: rename_sources_traced hands the engine one more hop — the declaring files of every module a handed-over file instantiates (module_select::instantiated_by, index edges only) — so a `.*` into a module declaring neither name is read, not refused. lucisv_mcp: the rename tool's known-limit sentence replaced; the M3 QA finding-1 test un-ignored.

Three QA rounds (Opus) attacked the widened verifier and found, in order, position-blind insertions, a lone trailing comma, and a slot after an error element — each fixed (the last by the lead) and pinned by 40+ qa_* tests incl. masked-corruption pairs; opentitan copies: prim_count err_o/clr_i, aes_core clk_i, entropy_src clk_i, prim_packer_fifo wready_o rename cleanly with their .* cov binds written out; prim_fifo_sync clr_i refused over the FPV binds that really target fifo instances. Accepted gap: a bind onto an instance that exists only inside a generate block of the enclosing module. Filed to vlog_parser: trailing `,` / `{d,, d}` / `type(x)'(y)` in a connection list parse without a diagnostic. Gates through tools/guard.sh: fmt, clippy, workspace 4 762 passed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 11:41:46 -07:00

377 lines
18 KiB
Rust

//! A rename versus the connections that bind by equal names: `.name` and
//! `.*` (M3 QA finding 1, TODO-MCP M3.5).
//!
//! Renaming a port `d` of `leaf` used to leave `leaf u_leaf (.*)` binding
//! nothing and turn `.d` into `.din` against a parent with no net `din`;
//! renaming the parent's net `d` left both bindings dangling — and each one
//! verified clean. Every test here drives the public `rename` over a little
//! in-memory workspace and asserts the whole text of each file afterwards,
//! or the refusal's sentence.
use std::path::{Path, PathBuf};
use vlog_refactor::{rename, RefactorEdit};
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 =
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}`");
}
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
}
/// Rename the `name` after `prefix` in `file`; every file's text afterwards,
/// and the warnings.
fn renamed(
files: &[(&str, &str)],
file: &str,
prefix: &str,
name: &str,
new_name: &str,
) -> Result<(Vec<String>, Vec<String>), String> {
let sources = workspace(files);
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
let edit = rename(&sources, &path(file), at(text, prefix, name), new_name)?;
let texts = files.iter().map(|(n, t)| apply(t, &edit, &path(n))).collect();
Ok((texts, edit.warnings))
}
const LEAF: &str = "module leaf (input logic clk, input logic [7:0] d, output logic [7:0] q);\n always_ff @(posedge clk) q <= d;\nendmodule\n";
const TOP: &str = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
const TOP2: &str = "module top2 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.clk, .d, .q);\nendmodule\n";
fn qa() -> Vec<(&'static str, &'static str)> {
vec![("leaf.sv", LEAF), ("top.sv", TOP), ("top2.sv", TOP2)]
}
#[test]
fn renaming_a_port_writes_out_the_shorthand_and_the_wildcard() {
let (texts, warnings) = renamed(&qa(), "leaf.sv", "[7:0] ", "d", "din").expect("renames");
assert!(texts[0].contains("input logic [7:0] din") && texts[0].contains("q <= din;"));
assert_eq!(texts[1], TOP.replace("(.*)", "(.*, .din(d))"));
assert_eq!(texts[2], TOP2.replace(".d,", ".din(d),"));
assert!(
warnings
.contains(&"`u_leaf` at top.sv:2 bound `d` through `.*`; added `.din(d)`.".to_string()),
"{warnings:?}"
);
assert!(
warnings
.iter()
.any(|w| w.starts_with("`u_leaf` at top2.sv:2 connected `d` by the shorthand `.d`")),
"{warnings:?}"
);
}
#[test]
fn the_shorthand_rewrite_is_one_edit() {
let sources = workspace(&qa());
let edit = rename(&sources, &path("leaf.sv"), at(LEAF, "[7:0] ", "d"), "din").expect("renames");
let top2 = edit.edits_for(&path("top2.sv"));
assert_eq!(top2.len(), 1, "{top2:?}");
assert_eq!(top2[0].new_text, "din(d)");
}
#[test]
fn renaming_the_net_a_wildcard_binds_adds_the_connection() {
let (texts, warnings) = renamed(&qa(), "top.sv", "[7:0] ", "d", "x").expect("renames");
assert_eq!(texts[1], TOP.replace("[7:0] d", "[7:0] x").replace("(.*)", "(.*, .d(x))"));
assert_eq!((texts[0].as_str(), texts[2].as_str()), (LEAF, TOP2));
assert_eq!(
warnings,
vec!["`u_leaf` at top.sv:2 bound `d` through `.*`; added `.d(x)`.".to_string()]
);
}
#[test]
fn renaming_the_net_a_shorthand_binds_writes_it_out() {
let (texts, _) = renamed(&qa(), "top2.sv", "[7:0] ", "d", "x").expect("renames");
assert_eq!(texts[2], TOP2.replace("[7:0] d", "[7:0] x").replace(".d,", ".d(x),"));
assert_eq!((texts[0].as_str(), texts[1].as_str()), (LEAF, TOP));
}
#[test]
fn a_wildcard_beside_an_explicit_connection_of_the_same_port_is_not_added_to() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*, .d(8'h0));\nendmodule\n";
let files = [("leaf.sv", LEAF), ("top.sv", top)];
let (texts, warnings) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
assert_eq!(texts[1], top.replace(".d(8'h0)", ".din(8'h0)"));
assert!(warnings.is_empty(), "{warnings:?}");
let (texts, warnings) = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect("renames");
assert_eq!(texts[1], top.replace("[7:0] d", "[7:0] x"));
assert!(warnings.is_empty(), "{warnings:?}");
}
#[test]
fn a_port_of_a_middle_module_is_rewritten_on_both_sides() {
let mid = "module mid (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n mid u_mid (.*);\nendmodule\n";
let files = [("leaf.sv", LEAF), ("mid.sv", mid), ("top.sv", top)];
let (texts, warnings) = renamed(&files, "mid.sv", "[7:0] ", "d", "din").expect("renames");
assert_eq!(texts[0], LEAF);
assert_eq!(texts[1], mid.replace("[7:0] d", "[7:0] din").replace("(.*)", "(.*, .d(din))"));
assert_eq!(texts[2], top.replace("(.*)", "(.*, .din(d))"));
assert_eq!(warnings.len(), 2, "{warnings:?}");
}
#[test]
fn a_shorthand_whose_port_differs_from_a_net_only_by_case_is_left_alone() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n logic [7:0] D;\n assign D = d;\n leaf u_leaf (.clk, .d, .q);\nendmodule\n";
let files = [("leaf.sv", LEAF), ("top.sv", top)];
let (texts, warnings) = renamed(&files, "top.sv", "logic [7:0] ", "D", "e").expect("renames");
assert_eq!(texts[1], top.replace("[7:0] D", "[7:0] e").replace("assign D", "assign e"));
assert!(warnings.is_empty(), "{warnings:?}");
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
assert!(
texts[1].contains(".din(d), .q);") && texts[1].contains("assign D = d;"),
"{}",
texts[1]
);
}
#[test]
fn a_bind_into_the_declaring_module_is_rewritten() {
let bind = "module binds;\n bind top leaf u_b (.*);\n bind top leaf u_c (.clk, .d, .q);\nendmodule\n";
let files = [("leaf.sv", LEAF), ("top.sv", TOP), ("binds.sv", bind)];
let (texts, warnings) = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect("renames");
assert_eq!(
texts[2],
bind.replace("u_b (.*)", "u_b (.*, .d(x))").replace(".clk, .d,", ".clk, .d(x),")
);
assert_eq!(warnings.len(), 3, "{warnings:?}");
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
assert_eq!(
texts[2],
bind.replace("u_b (.*)", "u_b (.*, .din(d))").replace(".clk, .d,", ".clk, .din(d),")
);
}
#[test]
fn a_hierarchical_bind_is_refused_not_guessed() {
let bind = "module binds;\n bind top.u_x leaf u_b (.*);\nendmodule\n";
let files = [("leaf.sv", LEAF), ("top.sv", TOP), ("binds.sv", bind)];
let refusal = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect_err("refused");
assert!(
refusal.contains("`u_b` at binds.sv:2 is bound into a hierarchical `bind` target"),
"{refusal}"
);
}
#[test]
fn a_wildcard_into_a_module_declared_twice_is_refused() {
let files = [("leaf.sv", LEAF), ("leaf_copy.sv", LEAF), ("top.sv", TOP)];
let refusal = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect_err("refused");
assert!(refusal.contains("`u_leaf` at top.sv:2 connects with `.*` to `leaf`, which is declared in more than one indexed file"), "{refusal}");
}
#[test]
fn a_wildcard_into_a_module_lucisv_cannot_read_is_refused() {
let top = "module top (input logic clk, input logic [7:0] d);\n ghost u_g (.*);\nendmodule\n";
let refusal = renamed(&[("top.sv", top)], "top.sv", "[7:0] ", "d", "x").expect_err("refused");
assert_eq!(
refusal,
"`u_g` at top.sv:2 connects with `.*` to `ghost`, which lucisv cannot read, so it cannot tell whether `d` is bound implicitly; the rename was abandoned."
);
}
#[test]
fn instances_inside_a_generate_for_are_rewritten() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n for (genvar i = 0; i < 2; i++) begin : g\n leaf u_leaf (.*);\n end\nendmodule\n";
let files = [("leaf.sv", LEAF), ("top.sv", top)];
let (texts, _) = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect("renames");
assert_eq!(texts[1], top.replace("[7:0] d", "[7:0] x").replace("(.*)", "(.*, .d(x))"));
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
assert_eq!(texts[1], top.replace("(.*)", "(.*, .din(d))"));
}
#[test]
fn a_crlf_list_one_per_line_keeps_its_layout_and_comment() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\r\n leaf u_leaf (\r\n .clk(clk),\r\n .* // the rest\r\n );\r\nendmodule\r\n";
let files = [("leaf.sv", LEAF), ("top.sv", top)];
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
assert_eq!(
texts[1],
top.replace(" .* // the rest\r\n", " .*, // the rest\r\n .din(d)\r\n")
);
}
#[test]
fn a_wildcard_list_split_by_directives_is_refused() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (\n`ifdef A\n .clk(1'b0),\n`endif\n .*\n );\nendmodule\n";
let refusal = renamed(&[("leaf.sv", LEAF), ("top.sv", top)], "top.sv", "[7:0] ", "d", "x")
.expect_err("refused");
assert!(refusal.contains("split by compiler directives"), "{refusal}");
}
#[test]
fn a_wildcard_that_would_start_binding_the_new_name_is_refused() {
let child = "module child (input logic a, input logic b);\nendmodule\n";
let top = "module top (input logic a);\n child u_c (.*);\nendmodule\n";
let refusal = renamed(&[("child.sv", child), ("top.sv", top)], "top.sv", "logic ", "a", "b")
.expect_err("refused");
assert!(refusal.contains("which would start binding `b`"), "{refusal}");
}
#[test]
fn renaming_a_port_no_wildcard_net_binds_adds_nothing() {
let top = "module top (input logic clk);\n leaf u_leaf (.*);\nendmodule\n";
let files = [("leaf.sv", LEAF), ("top.sv", top)];
let (texts, warnings) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
assert_eq!(texts[1], top, "nothing named `d` or `din` is visible, so `.*` binds neither");
assert!(warnings.is_empty(), "{warnings:?}");
}
#[test]
fn a_port_whose_new_name_a_wildcard_parent_already_has_is_written_out() {
let top = "module top (input logic clk, input logic [7:0] d, input logic [7:0] din, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
let files = [("leaf.sv", LEAF), ("top.sv", top)];
let (texts, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
assert_eq!(texts[1], top.replace("(.*)", "(.*, .din(d))"), "explicit beats the wildcard");
}
#[test]
fn an_escaped_port_is_terminated_where_it_is_written_out() {
let leaf = "module leaf (input logic clk, input logic \\d-x );\nendmodule\n";
let top = "module top (input logic clk, input logic \\d-x );\n leaf u_leaf (.clk, .\\d-x );\nendmodule\n";
let files = [("leaf.sv", leaf), ("top.sv", top)];
let (texts, _) = renamed(&files, "leaf.sv", "logic ", "\\d-x", "din").expect("renames");
// The escaped name keeps the blank that ends it, inside the parens and
// (as the source wrote it) before the list's own `)`.
assert_eq!(texts[1], top.replace(".\\d-x )", ".din(\\d-x ) )"));
}
#[test]
fn an_interface_instance_a_wildcard_binds_is_written_out() {
let bus = "interface bus_if;\n logic v;\nendinterface\n";
let sub = "module sub (bus_if bus, input logic clk);\nendmodule\n";
let top = "module top (input logic clk);\n bus_if bus ();\n sub u_sub (.*);\nendmodule\n";
let files = [("bus_if.sv", bus), ("sub.sv", sub), ("top.sv", top)];
let (texts, _) = renamed(&files, "top.sv", "bus_if ", "bus", "the_bus").expect("renames");
assert_eq!(
texts[2],
top.replace("bus_if bus ()", "bus_if the_bus ()").replace("(.*)", "(.*, .bus(the_bus))")
);
}
#[test]
fn a_package_variable_a_wildcard_might_import_is_refused() {
let pkg = "package p;\n logic [7:0] d;\nendpackage\n";
let top = "module top (input logic clk);\n import p::*;\n leaf u_leaf (.*);\nendmodule\n";
let files = [("p.sv", pkg), ("leaf.sv", LEAF), ("top.sv", top)];
let refusal = renamed(&files, "p.sv", "[7:0] ", "d", "x").expect_err("refused");
assert!(
refusal.contains("`u_leaf` at top.sv:3 may bind `d` implicitly through `.*`"),
"{refusal}"
);
}
#[test]
fn a_rename_no_implicit_connection_can_bind_ignores_the_wildcards() {
// A module, a parameter and a type are never bound by `.*`, so an
// unreadable `.*` beside them refuses nothing.
let top = "module top #(parameter int W = 8) (input logic clk);\n typedef logic [W-1:0] word_t;\n ghost u_g (.*);\nendmodule\n";
for (prefix, name, new) in
[("module ", "top", "top_r"), ("int ", "W", "WIDTH"), ("] ", "word_t", "w_t")]
{
let outcome = renamed(&[("top.sv", top)], "top.sv", prefix, name, new);
assert!(outcome.is_ok(), "{name} -> {new}: {outcome:?}");
}
}
#[test]
fn a_connection_list_holding_unparsed_text_is_refused() {
// `+.d` is an error element spelling the name; the second instance's `.*`
// is what makes the file one an implicit connection could live in.
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.clk, +.d, .q);\n leaf u_two (.*);\nendmodule\n";
let files = [("leaf.sv", LEAF), ("top.sv", top)];
let refusal = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect_err("refused");
assert!(refusal.contains("holds text lucisv could not parse"), "{refusal}");
}
/// A `bind` into a bare **instance** name (IEEE 1800 §23.11) is tied to the
/// modules the index says own an instance of that name. Here `i_x` names an
/// instance of `fifo` in one bench and of `cnt` in another: the bind might
/// reach `cnt`'s scope, so renaming `cnt`'s `err_o` is refused — whereas with
/// `fifo`'s instance alone it is skipped (QA finding 2's own test).
#[test]
fn a_bind_into_an_instance_name_one_of_whose_instances_is_ours_is_refused() {
let cnt =
"module cnt (input logic clk_i, output logic err_o);\n assign err_o = 1'b0;\nendmodule\n";
let fifo =
"module fifo (input logic clk_i, output logic err_o);\n assign err_o = 1'b0;\nendmodule\n";
let check = "module fifo_assert (input logic clk_i, input logic err_o);\nendmodule\n";
let tb = "module tb;\n logic clk_i, err_o;\n fifo i_x (.clk_i, .err_o);\nendmodule\n";
let tb2 = "module tb2;\n logic clk_i, err_o;\n cnt i_x (.clk_i, .err_o);\nendmodule\n";
let bind = "module tb_bind;\n bind i_x fifo_assert u_a (.clk_i, .err_o);\nendmodule\n";
let files = [
("cnt.sv", cnt),
("fifo.sv", fifo),
("check.sv", check),
("tb.sv", tb),
("tb2.sv", tb2),
("bind.sv", bind),
];
let refusal =
renamed(&files, "cnt.sv", "output logic ", "err_o", "error_o").expect_err("refused");
assert!(refusal.contains("`u_a` at bind.sv:2 may bind `err_o` implicitly"), "{refusal}");
let without: Vec<_> = files.iter().filter(|(n, _)| *n != "tb2.sv").copied().collect();
let (texts, _) =
renamed(&without, "cnt.sv", "output logic ", "err_o", "error_o").expect("skipped");
assert_eq!(texts[4], bind);
}
/// A bare instance name resolves upward from the `bind`'s own scope first
/// (IEEE 1800 §23.11): `bind dut … (.*)` written in a bench that declares its
/// own `dut` means that `dut`, whatever other benches call theirs — the
/// opentitan shape of `sram_ctrl`'s and `entropy_src`'s `tb.sv`.
#[test]
fn a_bind_into_the_enclosing_modules_own_instance_is_that_instance() {
let cnt =
"module cnt (input logic clk_i, output logic err_o);\n assign err_o = 1'b0;\nendmodule\n";
let fifo =
"module fifo (input logic clk_i, output logic err_o);\n assign err_o = 1'b0;\nendmodule\n";
let check = "module fifo_assert (input logic clk_i, input logic err_o);\nendmodule\n";
let tb = "module tb;\n logic clk_i, err_o;\n fifo dut (.clk_i, .err_o);\n bind dut fifo_assert u_a (.*);\nendmodule\n";
let tb2 = "module tb2;\n logic clk_i, err_o;\n cnt dut (.clk_i, .err_o);\nendmodule\n";
let files =
[("cnt.sv", cnt), ("fifo.sv", fifo), ("check.sv", check), ("tb.sv", tb), ("tb2.sv", tb2)];
let (texts, _) = renamed(&files, "cnt.sv", "output logic ", "err_o", "error_o")
.expect("tb's own `dut` is a `fifo`");
assert_eq!(texts[3], tb);
assert_eq!(texts[4], tb2.replace(".err_o)", ".error_o(err_o))"));
// And renaming `fifo`'s port is refused: that bind may bind it.
let refusal =
renamed(&files, "fifo.sv", "output logic ", "err_o", "error_o").expect_err("refused");
assert!(refusal.contains("`u_a` at tb.sv:4"), "{refusal}");
}