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]>
This commit is contained in:
lucioandClaude Fable 5.1 committed 2026-09-23 11:41:46 -07:00
1 parent 14b72f2862
commit 4edada583f
21 files changed
+4226 -20

No files matched your search

+3 -3
View File
@@ -163,7 +163,7 @@ known-limit sentence) + `tests/qa_m3.rs` (un-ignore finding 1), `TODO.md`
(one line under the §8 rope-port refactorings noting the fix). An engine
lane: the LSP's rename inherits the fix.
- [ ] `vlog_refactor::rename` rewrites implicit connections: renaming a port
- [x] `vlog_refactor::rename` rewrites implicit connections: renaming a port
`p` → `q` turns `.p` into `.q(p)` and adds `.q(p)` beside a `.*` that
bound it (explicit connections beside `.*` are legal); renaming a net
`n` → `m` in a module whose instantiations bind it through `.n` or `.*`
@@ -173,10 +173,10 @@ lane: the LSP's rename inherits the fix.
one-per-line); every such rewrite listed in `warnings` so the user
sees it; refuse (never guess) when the instantiation's port list
cannot be read (`ifdef`-split, error element)
- [ ] the verifier sees the new edits as intended (no false "moved"
- [x] the verifier sees the new edits as intended (no false "moved"
refusal); attack tests: `.*` + explicit of the same port; nested
instances; a `.name` whose net and port differ; a bind instance
- [ ] QA: attack the rewrite on opentitan copies (`prim_fifo_sync` ports
- [x] QA: attack the rewrite on opentitan copies (`prim_fifo_sync` ports
under `.*` users); LSP parity via `vlog_refactor::rename` directly
+5
View File
@@ -671,6 +671,11 @@ section only tracks the milestones.
- [x] **M2 `refactor-rename`** — new crate `vlog_refactor`; LSP
`prepareRename`/`rename` for every symbol kind `vlog_semantic` resolves,
cross-file, whole-edit-or-nothing verified by re-parse.
**2026-09-23 (TODO-MCP M3.5):** a rename no longer cuts a `.name` or `.*`
connection — the binding is written out explicitly (`.q(p)`, `.n(m)`) and
warned about, the unreadable cases are refused, and the verifier prints
every implicit binding before and after (`docs/features/refactor-rename/README.md`,
"Implicit connections").
- [x] **M3 `refactor-ports`** — add/remove/propagate module ports across
the declaration and every instantiation (named/ordered/`.*`).
**Amended 2026-08-28** (`docs/features/refactor-ports/README.md`): a
+1 -1
View File
@@ -123,7 +123,7 @@ pub const REMOVE_PORT: Tool = Tool {
pub const RENAME: Tool = Tool {
name: "rename",
title: "Rename a symbol",
description: "Rename one declaration and every reference to it across the project, verified before anything is written. Select as for `definition`: `file`+`line`+`col`, `file`+`line`+`name`, `file`+`name`, or `name` (+`unit`). Refuses an invalid or clashing name and a use it cannot account for; a name already `new_name` is `unchanged`. A `.*` or `.name` shorthand connection bound to the renamed name is not rewritten yet (known engine limit, M3.5); check `dry_run` on designs using them.",
description: "Rename one declaration and every reference to it across the project, verified before anything is written. Select as for `definition`: `file`+`line`+`col`, `file`+`line`+`name`, `file`+`name`, or `name` (+`unit`). Refuses an invalid or clashing name and a use it cannot account for; a name already `new_name` is `unchanged`. A `.*` or `.name` connection that bound the renamed name is written out explicitly (listed in `warnings`).",
params: &[
Param { required: false, ..FILE },
Param {
-1
View File
@@ -998,7 +998,6 @@ fn qa_rename_surfaces_the_engines_macro_warning() {
/// "verified" edit that silently changes the connectivity. It must refuse
/// (or rewrite the connection explicitly) — never leave the binding broken.
#[test]
#[ignore = "QA finding 1: engine limit, fixed in M3.5"]
fn qa_rename_never_breaks_an_implicit_port_connection() {
let files: &[(&str, &str)] = &[
(
+34 -1
View File
@@ -40,7 +40,7 @@
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use vlog_semantic::WorkspaceIndex;
use vlog_semantic::{FileId, WorkspaceIndex};
/// The extra reach one refactoring asks for.
///
@@ -80,6 +80,30 @@ pub fn hierarchical_users(index: &WorkspaceIndex, reach: Reach<'_>) -> BTreeSet<
out
}
/// The declaring file of every module instantiated in one of `files` — one
/// hop down the instantiation edges the index already holds (`bind`
/// directives included).
///
/// A rename's own rungs hand over every file declaring either name, so a
/// module a `.*` instantiates is handed over exactly when it declares a port
/// that needs a rewrite. When it declares neither name it is not, and the
/// engine — which cannot tell "not handed over" from "not in the workspace" —
/// refuses the rename as one it cannot check (TODO-MCP M3.5). This rung hands
/// those modules over so the engine can see they bind nothing. It can only
/// add files, so an edit stays the edit it was; nothing is read or parsed.
pub fn instantiated_by(index: &WorkspaceIndex, files: &[&Path]) -> BTreeSet<PathBuf> {
let ids: BTreeSet<FileId> = files.iter().filter_map(|path| index.file_id(path)).collect();
let mut out = BTreeSet::new();
for (module, edges) in index.instantiations() {
if !edges.iter().any(|edge| ids.contains(&edge.file)) {
continue;
}
let declared = index.units(module).iter().filter(|def| def.kind.is_instantiable());
out.extend(declared.filter_map(|def| index.path(def.file)).map(Path::to_path_buf));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
@@ -138,6 +162,15 @@ mod tests {
assert!(hierarchical_users(&index, Reach { scopes: &scopes }).is_empty());
}
#[test]
fn the_modules_a_file_instantiates_are_one_hop_down_and_no_further() {
let index = ladder();
let tb = Path::new("/w/tb.sv");
let below = instantiated_by(&index, &[tb]);
assert_eq!(names(&below), ["wrapper.sv"], "tb instantiates wrapper, and only wrapper");
assert!(instantiated_by(&index, &[Path::new("/w/nowhere.sv")]).is_empty());
}
#[test]
fn no_reach_asked_for_is_no_work_done() {
let index = ladder();
+4 -1
View File
@@ -359,7 +359,10 @@ mod tests {
let (edit, _) = rename_traced(&ws, &uri, at(edited, "only_here"), "renamed", &mut line)
.expect("the buffer's own declaration renames");
let trace = line.expect("a trace is always written");
assert!(trace.contains("reused_files=1"), "only the untouched buffer's record: {trace}");
// Two untouched records: the open `bystander.sv`, and `sub.sv`, which
// the buffer instantiates and the fan-out's instantiation step hands
// over (M3.5) — both reused, and the edited buffer still parsed.
assert!(trace.contains("reused_files=2"), "only the untouched files' records: {trace}");
assert!(trace.contains("lead=0.0ms") || trace.contains("parses{index=1"), "{trace}");
let edits = edit.changes.as_ref().expect("changes").values().flatten().count();
assert_eq!(edits, 2, "the declaration and its one use, both in the buffer");
@@ -58,6 +58,8 @@ mod large_file;
mod lint_snapshot;
mod progress;
mod pull_diagnostics;
mod qa_rename_implicit;
mod rename_implicit;
mod requests;
mod scan;
mod scan_trace;
@@ -0,0 +1,118 @@
//! QA M3.5 (2026-09-23): the LSP's rename against `.*`/`.name`, over the wire,
//! on the engine tests' fixtures — the fan-out must hand the engine every
//! file an implicit connection of the name lives in, open buffer or disk.
use super::*;
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";
/// Rename the name at (`line`, `character`) of `uri`.
fn rename_at(session: &mut Session, uri: &Uri, line: u32, character: u32, new: &str) -> Response {
session.request(
Rename::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": line, "character": character },
"newName": new,
}),
)
}
/// `text` with the LSP edits applied (ASCII fixtures: a character is a byte).
fn applied(text: &str, edits: &[Value]) -> String {
let starts: Vec<usize> =
std::iter::once(0).chain(text.match_indices('\n').map(|(i, _)| i + 1)).collect();
let offset = |p: &Value| {
let line = p["line"].as_u64().expect("line") as usize;
starts[line] + p["character"].as_u64().expect("character") as usize
};
let mut spans: Vec<(usize, usize, String)> = edits
.iter()
.map(|e| {
let range = &e["range"];
let text = e["newText"].as_str().expect("newText").to_string();
(offset(&range["start"]), offset(&range["end"]), text)
})
.collect();
spans.sort_by_key(|(start, end, _)| (*start, *end));
let mut out = String::new();
let mut cursor = 0;
for (start, end, new) in spans {
out.push_str(&text[cursor..start]);
out.push_str(&new);
cursor = end;
}
out.push_str(&text[cursor..]);
out
}
/// The edits for the file named `name` in a rename answer, or none — found
/// by the URI's last segment, so a temp dir's symlinked spelling is moot.
fn edits_for(answer: &Value, name: &str) -> Vec<Value> {
let Some(changes) = answer["changes"].as_object() else { return Vec::new() };
let suffix = format!("/{name}");
let found = changes.iter().find(|(uri, _)| uri.ends_with(&suffix));
found.and_then(|(_, edits)| edits.as_array().cloned()).unwrap_or_default()
}
/// `d`'s column on line 0 of the three fixtures.
fn d_column(text: &str) -> u32 {
text.find("] d").expect("the port") as u32 + 2
}
#[test]
fn qa_lsp_port_rename_matches_the_engine_with_the_users_on_disk() {
let tree = Tree::new("qa_rename_implicit_disk");
tree.write("leaf.sv", LEAF);
tree.write("top.sv", TOP);
tree.write("top2.sv", TOP2);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("leaf.sv"), LEAF);
let answer =
rename_at(&mut session, &uri, 0, d_column(LEAF), "din").response_result.expect("renames");
assert_eq!(applied(TOP, &edits_for(&answer, "top.sv")), TOP.replace("(.*)", "(.*, .din(d))"));
assert_eq!(applied(TOP2, &edits_for(&answer, "top2.sv")), TOP2.replace(".d,", ".din(d),"));
}
#[test]
fn qa_lsp_rename_reads_the_open_buffer_not_the_disk() {
// On disk top.sv connects explicitly; the unsaved buffer uses `.*`.
let tree = Tree::new("qa_rename_implicit_buffer");
tree.write("leaf.sv", LEAF);
let explicit = TOP.replace("(.*)", "(.clk(clk), .d(d), .q(q))");
tree.write("top.sv", &explicit);
let mut session = Session::wide(vec![tree.path.clone()], false);
let top = session.open(&tree.path.join("top.sv"), TOP);
let leaf = session.open(&tree.path.join("leaf.sv"), LEAF);
let answer =
rename_at(&mut session, &leaf, 0, d_column(LEAF), "din").response_result.expect("renames");
let top_edits = answer["changes"][top.as_str()].as_array().cloned().unwrap_or_default();
assert_eq!(applied(TOP, &top_edits), TOP.replace("(.*)", "(.*, .din(d))"), "{answer:#}");
}
#[test]
fn qa_lsp_net_rename_reaches_a_bind_file_spelling_neither_name() {
// binds.sv spells neither `d` nor `x`: only `leaf`'s instantiation sites
// (leaf declares a port `d`) bring it into the fan-out.
let tree = Tree::new("qa_rename_implicit_bind");
let top =
"module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\nendmodule\n";
let bind = "module binds;\n bind top leaf u_b (.*);\nendmodule\n";
tree.write("leaf.sv", LEAF);
tree.write("top.sv", top);
tree.write("binds.sv", bind);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("top.sv"), top);
let answer =
rename_at(&mut session, &uri, 0, d_column(top), "x").response_result.expect("renames");
assert_eq!(
applied(bind, &edits_for(&answer, "binds.sv")),
bind.replace("(.*)", "(.*, .d(x))"),
"{answer:#}"
);
}
@@ -0,0 +1,67 @@
//! A rename against `.*` connections, over the wire (TODO-MCP M3.5).
//!
//! The engine refuses a rename it cannot check against a `.*` whose module it
//! cannot read, and the server hands the engine a *fan-out*, not the
//! workspace. These pin the fan-out's instantiation step: every module a
//! handed-over file instantiates is handed over too, so a `.*` into a module
//! the workspace holds is read, not refused — and one into a module the
//! workspace does not hold is still refused.
use super::*;
/// Rename the `d` at line 0, character `character` of `uri` to `x`.
fn rename_d(session: &mut Session, uri: &Uri, character: u32) -> Response {
session.request(
Rename::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": 0, "character": character },
"newName": "x",
}),
)
}
const TOP: &str = "module top (input logic clk, input logic [7:0] d, output logic q);\n quiet u_quiet (.*);\n leaf u_leaf (.*);\n assign q = d[0];\nendmodule\n";
/// Where the `d` of `input logic [7:0] d` sits on line 0.
fn d_column() -> u32 {
TOP.find("] d").expect("the port") as u32 + 2
}
#[test]
fn a_net_rename_beside_a_wildcard_into_a_module_declaring_neither_name_succeeds() {
let tree = Tree::new("rename_implicit_ok");
// `quiet` declares neither `d` nor `x`, so no rung of the name's own
// fan-out asks for it — only the instantiation step does.
tree.write("quiet.sv", "module quiet (input logic clk);\nendmodule\n");
tree.write("leaf.sv", "module leaf (input logic clk, input logic [7:0] d);\nendmodule\n");
tree.write("top.sv", TOP);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("top.sv"), TOP);
let answer = rename_d(&mut session, &uri, d_column()).response_result.expect("renames");
let edits = answer["changes"][uri.as_str()].as_array().expect("top.sv is edited").clone();
let texts: Vec<&str> = edits.iter().filter_map(|e| e["newText"].as_str()).collect();
assert!(texts.contains(&", .d(x)"), "the explicit connection: {answer:#}");
assert_eq!(texts.iter().filter(|t| **t == "x").count(), 2, "the port and its use: {answer:#}");
assert_eq!(edits.len(), 3, "and nothing for `u_quiet`: {answer:#}");
}
#[test]
fn a_net_rename_beside_a_wildcard_into_a_module_outside_the_workspace_is_refused() {
let tree = Tree::new("rename_implicit_refused");
tree.write("leaf.sv", "module leaf (input logic clk, input logic [7:0] d);\nendmodule\n");
tree.write("top.sv", TOP);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("top.sv"), TOP);
let error = rename_d(&mut session, &uri, d_column()).response_result.expect_err("refused");
assert_eq!(error.code, lsp_server::ErrorCode::RequestFailed as i32);
assert!(
error.message.contains(
"`u_quiet` at top.sv:2 connects with `.*` to `quiet`, which lucisv cannot read"
),
"{}",
error.message
);
}
+7 -1
View File
@@ -1756,7 +1756,13 @@ impl Workspace {
}
wanted.on(Rung::OpenBuffer);
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
let (paths, mut trace) = wanted.finish();
let (mut paths, mut trace) = wanted.finish();
// One hop down: the modules those files instantiate, so a `.*` into
// one is read rather than refused (M3.5). In `selected`, under no rung.
let handed: Vec<&Path> = paths.keys().map(PathBuf::as_path).collect();
for below in module_select::instantiated_by(&self.index, &handed) {
paths.entry(below).or_insert(Rung::Instantiation);
}
// §P2d's census: which rungs asked for files that write neither name
// down, and therefore contribute to this request only by shaping how
// the others resolve. One record lookup per selected file, no read.
+805
View File
@@ -0,0 +1,805 @@
//! What the rename verifier learns about implicit connections (`.name` and
//! `.*`), and why it had to learn it.
//!
//! The rename contract was "the token stream may not change shape", and the
//! resolution print compares references and declarations — and neither sees
//! an implicit binding, because nothing is written for one: `.*` records no
//! reference, and `.d` records only the port half. That is exactly how a
//! rename used to cut `.*`/`.d` bindings and verify clean (M3 QA finding 1).
//! So the fix is in two halves, and this is the second:
//!
//! 1. **The edits may insert, but only connection text.** A rename that
//! rewrites implicit connections writes `(net)` after a shorthand or
//! `.port(net)` into a list — never anything else. [`insertions_match`]
//! holds such a file to the splice contract (the pieces, comments and
//! attributes never dropped, no new parse error) *plus* a shape rule: every
//! replacement is the old name becoming the new one, and every insertion
//! is one of four connection templates spelling only those two names.
//! 2. **Every implicit binding is printed, before and after.** For every
//! instance in a watched file, [`bindings`] lists what each connection's
//! port half and net half name — the net half of `.name` and of each port
//! `.*` reaches looked up exactly where the language looks it up. The two
//! lists must be equal, which is what refuses a dangling `.*`, a `.d` left
//! pointing at nothing, a `.*` that starts binding the new name, and a
//! connection added twice.
//!
//! Only bindings whose port or net spells the old or the new name are
//! printed: a rename adds and removes declarations of those two names alone,
//! so a lookup of any other name — and a port of any other name — cannot
//! move. That is the watched-file argument, applied one level down.
use std::path::{Path, PathBuf};
use vlog_parser::ast::{Connection, ExprKind, ListElem, SourceFile};
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
use vlog_parser::{parse_source_tolerant, tokenize};
use vlog_semantic::{
resolve_external, ExternalResolutions, Semantics, Surface, SymbolKind, WorkspaceIndex,
};
use super::ledger::{pieces_match, Split};
use super::{anchor_of, Anchor, Shifts};
use crate::rename::sites::{binds_implicitly, may_connect_implicitly, nearest, sites, Site};
use crate::rename::{display, Scope};
use crate::TextEdit;
/// The rename's lexical contract for a file whose edits insert connection
/// text: the old name replaced by the new one, the four connection templates
/// inserted — each **where a connection list takes it** — and nothing else
/// changed.
pub(super) fn insertions_match(
before: &str,
after: &str,
edits: &[TextEdit],
names: [&str; 2],
path: &Path,
) -> Result<(), String> {
let refusal =
|what: &str| format!("the rename would {what} in {}; no edits were made.", display(path));
let Ok(old_tokens) = tokenize(before) else {
return Err(refusal("edit a file lucisv cannot lex"));
};
let slots = Slots::of(before);
for edit in edits {
let honest = match edit.range.is_empty() {
true => template(&edit.new_text, names).is_some(),
false => replaces_one_name(&old_tokens, edit, names),
};
if !honest {
return Err(refusal(&format!("write `{}`, which is not a rename", edit.new_text)));
}
if edit.range.is_empty() && !slots.takes(before, edit, edits, names) {
let outside = format!("write `{}` outside a connection list", edit.new_text);
return Err(refusal(&outside));
}
}
let split = Split::read(before, after, edits, path, "the rename")?;
pieces_match(&split, edits, path, "the rename")?;
let grew = parse_source_tolerant(after).1.len() > parse_source_tolerant(before).1.len();
match grew {
true => Err(refusal("leave a connection list that does not parse")),
false => Ok(()),
}
}
/// A replacement is the one identifier token spelling the old name, replaced
/// by the new name.
fn replaces_one_name(
tokens: &[vlog_parser::token::Token],
edit: &TextEdit,
names: [&str; 2],
) -> bool {
let [old, new] = names;
let covered: Vec<_> =
tokens.iter().filter(|t| super::ledger::overlaps(t.span, edit.range)).collect();
matches!(covered.as_slice(), [only] if only.kind == TokenKind::Ident
&& only.span == edit.range
&& only.text == old
&& edit.new_text == new)
}
/// The four things a rename may insert.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Template {
/// `(X)`: a shorthand's net, written out.
Tail,
/// `,`: the comma before a `//` comment on a list's last element.
Comma,
/// `.X(Y)`: a connection after that comment, the comma already written.
Connection,
/// `, .X(Y)`: a connection appended to a list.
Appended,
}
/// Which template an insertion spells — `X` and `Y` the old or the new name,
/// no comment — or `None`.
fn template(text: &str, names: [&str; 2]) -> Option<Template> {
let tokens = tokenize(text).ok()?;
let mut code: Vec<&str> = Vec::new();
for token in &tokens {
if !token.leading.is_empty() || token.trailing.is_some() {
return None;
}
match token.kind {
TokenKind::Eof => {}
TokenKind::Ident if names.contains(&token.text.as_str()) => code.push("name"),
TokenKind::Symbol => code.push(token.text.as_str()),
_ => return None,
}
}
match code.as_slice() {
["(", "name", ")"] => Some(Template::Tail),
[","] => Some(Template::Comma),
[".", "name", "(", "name", ")"] => Some(Template::Connection),
[",", ".", "name", "(", "name", ")"] => Some(Template::Appended),
_ => None,
}
}
#[cfg(test)]
fn is_connection_text(text: &str, names: [&str; 2]) -> bool {
template(text, names).is_some()
}
/// Where a rename may insert into one file, read off the **before** tree with
/// the walk the engine plans with (`rename::sites`), so the plan and the
/// check cannot disagree about what a connection list is (QA M3.5 finding 1:
/// the template check alone admitted `,` into a positional list, `(d)` after
/// a call argument, `, .din(d)` into a `#(...)` override).
struct Slots {
/// The end of every shorthand connection's name (`.d` → after `d`).
tails: Vec<u32>,
/// Every named list holding `.*`: the end of its last element, and its
/// closing `)`.
lists: Vec<(u32, u32)>,
}
impl Slots {
fn of(before: &str) -> Slots {
let (tree, _) = parse_source_tolerant(before);
let mut out = Slots { tails: Vec::new(), lists: Vec::new() };
for site in sites(&tree.items) {
// A list holding text the parser could not read has no slot at
// all: an error element's span may stop short of its own `)`,
// so an append "after the last element" lands inside it, and the
// parse check cannot tell — one diagnostic before, one after
// (QA M3.5 finding 4). The engine already refuses such lists.
if site.unreadable().next().is_some() {
continue;
}
let shorthands = site.connections().filter(|c| c.expr.is_none() && c.name != "*");
out.tails.extend(shorthands.map(|c| c.name_span.end));
let last = site.conns.last().map(|e| match e {
ListElem::Ok(c) => c.span,
ListElem::Error(raw) => raw.span,
});
let close = site.instance.span.end.checked_sub(1);
let closed = close.filter(|&at| before.as_bytes().get(at as usize) == Some(&b')'));
if let (true, Some(last), Some(close)) = (site.has_wildcard(), last, closed) {
out.lists.push((last.end, close));
}
}
out
}
/// Whether `edit` — an insertion — lands where its template belongs: a
/// net right after a shorthand's name; a connection between a `.*` list's
/// last element (and the comments after it) and the list's `)`; and the
/// comma-before-`//` pair as a **pair** — a comma right after the last
/// element only with a bare connection written into the same list, and a
/// bare connection only behind such a comma. A lone `,` leaves `(.*,)`,
/// which the tolerant parser does not flag (QA M3.5 finding 3).
fn takes(&self, before: &str, edit: &TextEdit, edits: &[TextEdit], names: [&str; 2]) -> bool {
let at = edit.range.start;
let within = |at: u32, &(end, close): &(u32, u32)| {
let gap = before.get(end as usize..at as usize).unwrap_or(",");
end <= at && at <= close && tokenize(gap).is_ok_and(|tokens| tokens.len() == 1)
};
let comma_at =
|end: u32| edits.iter().any(|e| e.range == TextRange::empty(end) && e.new_text == ",");
let connection_in = |list: &(u32, u32)| {
edits.iter().any(|e| {
e.range.is_empty()
&& template(&e.new_text, names) == Some(Template::Connection)
&& within(e.range.start, list)
})
};
let lists = || self.lists.iter();
match template(&edit.new_text, names) {
Some(Template::Tail) => self.tails.contains(&at),
Some(Template::Comma) => lists().any(|list| list.0 == at && connection_in(list)),
Some(Template::Connection) => lists().any(|list| within(at, list) && comma_at(list.0)),
Some(Template::Appended) => lists().any(|list| within(at, list)),
None => false,
}
}
}
/// Where file `file`'s inserted connection text sits once the edits are
/// applied. The names it spells are the binding print's to account for, not
/// the resolution print's: before the edit they were not written.
pub(super) fn inserted_in(edits: &[(usize, Vec<TextEdit>)], file: usize) -> Vec<TextRange> {
let edits = edits.iter().find(|(f, _)| *f == file);
edits.map(|(_, edits)| inserted_after(edits)).unwrap_or_default()
}
/// Where each insertion's text sits once the edits are applied, so that the
/// resolution print does not compare the names inside it — the binding print
/// is what accounts for them.
fn inserted_after(edits: &[TextEdit]) -> Vec<TextRange> {
let mut out = Vec::new();
let mut delta: i64 = 0;
for edit in edits {
let start = (i64::from(edit.range.start) + delta).max(0) as u32;
if edit.range.is_empty() {
out.push(TextRange::new(start, start + edit.new_text.len() as u32));
}
delta += edit.new_text.len() as i64 - i64::from(edit.range.len());
}
out
}
/// What one half of a connection names.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum Bound {
/// These declarations, as (file, name span).
At(Vec<(PathBuf, u32, u32)>),
/// Nothing lucisv can see.
Nothing,
/// An expression other than a bare name: the resolution print compares
/// what is inside it.
Expression,
/// A name looked up in a scope lucisv cannot name — a hierarchical `bind`
/// target, or the `.*` of a module it cannot read (`probe 0`/`probe 1`).
Opaque(String),
}
/// One binding of one instance: where the instance is named, what the port
/// half names, and what the net half names.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Binding {
at: (u32, u32),
port: Bound,
net: Bound,
}
/// One side of the comparison: a file's tree, its analysis, the index it
/// resolves against, and the shift that maps a before-side span to after.
struct Side<'x> {
tree: &'x SourceFile,
semantics: &'x Semantics,
external: &'x ExternalResolutions,
index: &'x WorkspaceIndex,
path: &'x Path,
shifts: &'x Shifts,
}
/// The state after the edits, as [`super::verify`] already built it: each
/// edited file's new text and analysis, and the after-index.
pub(super) struct After<'x> {
pub(super) edited: &'x [(PathBuf, String)],
pub(super) analyses: &'x [(PathBuf, Semantics)],
pub(super) index: &'x WorkspaceIndex,
}
/// Every watched file's implicit bindings must be the same before and after.
/// A file that could write none of either name is skipped, unless the edits
/// insert into it.
pub(super) fn bindings_match(
scope: &Scope,
watched: &[usize],
edits: &[(usize, Vec<TextEdit>)],
shifts: &Shifts,
after: &After,
names: [&str; 2],
) -> Result<(), String> {
let abandoned = || "lucisv could not verify the rename, so it made no edits.".to_string();
for &i in watched {
let (Some(path), Some(text), Some(analysis)) =
(scope.path(i), scope.text(i), scope.cached(i))
else {
return Err(abandoned());
};
let slot = edits.iter().position(|(f, _)| *f == i);
let inserts = slot
.and_then(|k| edits.get(k))
.is_some_and(|(_, e)| e.iter().any(|e| e.range.is_empty()));
if !inserts && !may_connect_implicitly(text, &names) {
continue;
}
let (tree, _) = parse_source_tolerant(text);
let side = Side {
tree: &tree,
semantics: &analysis.semantics,
external: &analysis.external,
index: scope.index(),
path,
shifts,
};
let before = bindings(&side, names);
let after = match slot.and_then(|k| after.edited.get(k)) {
Some((_, text)) => edited_bindings(path, text, after, names),
None => scope.against(i, after.index).map(|(semantics, external)| {
let identity = Shifts::default();
bindings(
&Side {
tree: &tree,
semantics,
external: &external,
index: after.index,
path,
shifts: &identity,
},
names,
)
}),
};
let Some(after) = after else { return Err(abandoned()) };
if let Some(instance) = first_difference(&before, &after) {
let [old, new] = names;
return Err(format!(
"renaming `{old}` to `{new}` would change what an implicit connection of `{instance}` binds in {}; the rename was abandoned.",
display(path)
));
}
}
Ok(())
}
/// An edited file's bindings, read off its new text and the analysis the
/// after-index was built with.
fn edited_bindings(
path: &Path,
text: &str,
after: &After,
names: [&str; 2],
) -> Option<Vec<(Binding, String)>> {
let (tree, _) = parse_source_tolerant(text);
let (_, semantics) = after.analyses.iter().find(|(p, _)| p == path)?;
let external = resolve_external(semantics, after.index);
let identity = Shifts::default();
Some(bindings(
&Side {
tree: &tree,
semantics,
external: &external,
index: after.index,
path,
shifts: &identity,
},
names,
))
}
/// The instance whose bindings differ first, if any do.
fn first_difference(before: &[(Binding, String)], after: &[(Binding, String)]) -> Option<String> {
for n in 0..before.len().max(after.len()) {
match (before.get(n), after.get(n)) {
(Some((a, _)), Some((b, name))) if a != b => return Some(name.clone()),
(Some((_, name)), None) | (None, Some((_, name))) => return Some(name.clone()),
_ => {}
}
}
None
}
/// Every binding in one file whose port or net spells one of `names`, sorted,
/// each with the instance's name for the refusal.
fn bindings(side: &Side, names: [&str; 2]) -> Vec<(Binding, String)> {
let mut out: Vec<(Binding, String)> = Vec::new();
for site in sites(&side.tree.items) {
let at = side.shifts.map(side.path, site.instance.name_span);
let mut push = |port: Bound, net: Bound| {
out.push((Binding { at: (at.start, at.end), port, net }, site.instance.name.clone()))
};
for c in site.connections().filter(|c| c.name != "*") {
if let Some(net) = net_half(side, &site, c, names) {
push(port_half(side, c), net);
}
}
if site.has_wildcard() {
for (port, net) in wildcard(side, &site, names) {
push(port, net);
}
}
}
out.sort();
out
}
/// What a named connection's port half names: the reference the semantic
/// layer recorded for it.
fn port_half(side: &Side, c: &Connection) -> Bound {
reference_at(side, c.name_span)
}
/// What a named connection's net half names, when the connection is one the
/// print covers: `.name`'s implicit net, an explicit bare name, or (for a port
/// spelling one of the names) any other expression.
fn net_half(side: &Side, site: &Site, c: &Connection, names: [&str; 2]) -> Option<Bound> {
let port_named = names.contains(&c.name.as_str());
match c.expr.as_ref().map(|e| (&e.kind, e.span)) {
None => port_named.then(|| implicit(side, site, &c.name)),
Some((ExprKind::Ident(name), span)) if port_named || names.contains(&name.as_str()) => {
Some(reference_at(side, span))
}
Some(_) => port_named.then_some(Bound::Expression),
}
}
/// The bindings a `.*` makes for the ports spelling one of `names` that the
/// list does not connect explicitly — or, when the module cannot be read, a
/// probe of what each name would find there.
fn wildcard(side: &Side, site: &Site, names: [&str; 2]) -> Vec<(Bound, Bound)> {
let module = &site.instantiation.module;
if instantiable(side.index, module) != 1 {
let probe = |(slot, name): (usize, &&str)| {
(Bound::Opaque(format!("probe {slot}")), implicit(side, site, name))
};
return names.iter().enumerate().map(probe).collect();
}
let mut out = Vec::new();
for (port, defs) in side.index.members_of(module) {
let ports: Vec<_> = defs.iter().filter(|d| d.kind == SymbolKind::Port).collect();
if ports.is_empty() || !names.contains(&port) || site.named(port).is_some() {
continue;
}
let at = ports.iter().map(|d| located(side, d.file, d.name_span)).collect();
out.push((at_all(at), implicit(side, site, port)));
}
out
}
/// What `.name` or `.*` binds `name` to at `site`: the nearest declaration
/// where the instance is written, or — for a `bind` into one plain module —
/// that module's own declaration of it.
fn implicit(side: &Side, site: &Site, name: &str) -> Bound {
match site.bind_target() {
Ok(None) => {
// The nearest declaration shadows whatever its kind; one `.*`
// cannot bind (a parameter, a module) is a binding to nothing.
let found = nearest(side.semantics, site.instance.name_span.start, name)
.and_then(|s| side.semantics.symbol(s))
.filter(|s| binds_implicitly(s.kind));
match found {
Some(symbol) => at_all(vec![located_here(side, symbol.name_span)]),
None => Bound::Nothing,
}
}
Ok(Some(target)) if instantiable(side.index, target) == 1 => {
let defs = side.index.member_in(target, name, Surface::Hierarchical);
let defs = defs.iter().filter(|d| binds_implicitly(d.kind));
at_all(defs.map(|d| located(side, d.file, d.name_span)).collect())
}
_ => Bound::Opaque(name.to_string()),
}
}
/// What the reference written exactly at `span` resolves to.
fn reference_at(side: &Side, span: TextRange) -> Bound {
let Some(id) = side.semantics.reference_id_at(span.start) else { return Bound::Nothing };
let Some(reference) = side.semantics.reference(id).filter(|r| r.name_span == span) else {
return Bound::Nothing;
};
let anchor = anchor_of(
side.semantics,
side.external,
side.index,
side.path,
side.shifts,
id.0 as usize,
reference,
);
match anchor {
Anchor::Local(start, end) => at_all(vec![(side.path.to_path_buf(), start, end)]),
Anchor::External(defs) => at_all(defs),
Anchor::Unresolved => Bound::Nothing,
}
}
fn at_all(mut at: Vec<(PathBuf, u32, u32)>) -> Bound {
if at.is_empty() {
return Bound::Nothing;
}
at.sort();
Bound::At(at)
}
fn located_here(side: &Side, span: TextRange) -> (PathBuf, u32, u32) {
let span = side.shifts.map(side.path, span);
(side.path.to_path_buf(), span.start, span.end)
}
fn located(side: &Side, file: vlog_semantic::FileId, span: TextRange) -> (PathBuf, u32, u32) {
let path = side.index.path(file).unwrap_or(Path::new("?")).to_path_buf();
let span = side.shifts.map(&path, span);
(path, span.start, span.end)
}
fn instantiable(index: &WorkspaceIndex, name: &str) -> usize {
index.units(name).iter().filter(|d| d.kind.is_instantiable()).count()
}
/// Masked-corruption attacks (CLAUDE.md invariant 4): each is an edit the
/// rename engine could plausibly produce if it got implicit connections
/// wrong, handed straight to the verifier, and each must be refused. The
/// honest edit is the control.
#[cfg(test)]
mod tests {
use super::super::verify;
use super::*;
use crate::trace::VerifyTrace;
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 files(top: &str) -> Vec<(PathBuf, String)> {
vec![
(PathBuf::from("/rtl/leaf.sv"), LEAF.to_string()),
(PathBuf::from("/rtl/top.sv"), top.to_string()),
(PathBuf::from("/rtl/top2.sv"), TOP2.to_string()),
]
}
/// The edit replacing the whole word `name` found after `prefix`.
fn swap(text: &str, prefix: &str, name: &str, new: &str) -> TextEdit {
let from = text.find(prefix).expect("prefix") + prefix.len();
let start = (from + text[from..].find(name).expect("name")) as u32;
TextEdit { range: TextRange::new(start, start + name.len() as u32), new_text: new.into() }
}
/// The insertion of `new` right after the first `after`.
fn put(text: &str, after: &str, new: &str) -> TextEdit {
let at = (text.find(after).expect("anchor") + after.len()) as u32;
TextEdit { range: TextRange::empty(at), new_text: new.into() }
}
/// Verify a port rename `d` → `din` of `leaf` whose `top.sv` and
/// `top2.sv` edits are the ones given.
fn port_rename(
top: &str,
top_edits: Vec<TextEdit>,
top2_edits: Vec<TextEdit>,
) -> Result<(), String> {
let files = files(top);
let mut scope = Scope::build(&files);
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top_i, top2) =
(index("/rtl/leaf.sv"), index("/rtl/top.sv"), index("/rtl/top2.sv"));
let mut edits =
vec![(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")])];
for (file, list) in [(top_i, top_edits), (top2, top2_edits)] {
if !list.is_empty() {
edits.push((file, list));
}
}
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
}
fn shorthand_edits(tail: &str) -> Vec<TextEdit> {
vec![swap(TOP2, ".clk, .", "d", "din"), put(TOP2, ".clk, .d", tail)]
}
#[test]
fn the_honest_rewrite_verifies() {
let honest = port_rename(TOP, vec![put(TOP, "(.*", ", .din(d)")], shorthand_edits("(d)"));
assert_eq!(honest, Ok(()));
}
#[test]
fn the_rename_that_cut_both_bindings_is_refused() {
// QA finding 1, exactly: `.d` became `.din`, `.*` was left alone.
let cut = port_rename(TOP, Vec::new(), vec![swap(TOP2, ".clk, .", "d", "din")]);
assert!(cut.expect_err("refused").contains("implicit connection of `u_leaf`"));
let wildcard_only = port_rename(TOP, Vec::new(), shorthand_edits("(d)"));
assert!(wildcard_only.is_err(), "the `.*` in top.sv no longer binds `din`");
}
#[test]
fn a_shorthand_written_out_with_the_wrong_net_is_refused() {
// `(din)` spells only the two names, so only the binding print sees it.
let wrong = port_rename(TOP, vec![put(TOP, "(.*", ", .din(d)")], shorthand_edits("(din)"));
assert!(wrong.is_err(), "`.din(din)` binds nothing top2 declares");
}
#[test]
fn a_wildcard_connection_to_the_wrong_net_is_refused() {
let other = port_rename(TOP, vec![put(TOP, "(.*", ", .din(q)")], shorthand_edits("(d)"));
assert!(other.is_err(), "`q` is not one of the two names");
let swapped = port_rename(TOP, vec![put(TOP, "(.*", ", .d(din)")], shorthand_edits("(d)"));
assert!(swapped.is_err(), "`.d(din)` names a port `leaf` no longer has");
}
#[test]
fn an_insertion_that_is_not_connection_text_is_refused() {
for text in [", .din(d) /* c */", "; wire din;", ", .din(d), .din(d)", ", .din(d"] {
let bad = port_rename(TOP, vec![put(TOP, "(.*", text)], shorthand_edits("(d)"));
assert!(bad.is_err(), "{text:?} must be refused");
}
}
#[test]
fn a_connection_added_beside_an_explicit_one_of_the_same_port_is_refused() {
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 honest =
port_rename(top, vec![swap(top, "(.*, .", "d", "din")], shorthand_edits("(d)"));
assert_eq!(honest, Ok(()));
let doubled = port_rename(
top,
vec![swap(top, "(.*, .", "d", "din"), put(top, "(8'h0)", ", .din(d)")],
shorthand_edits("(d)"),
);
assert!(doubled.is_err(), "the port is connected twice");
}
#[test]
fn an_insertion_into_the_wrong_instance_is_refused() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\n leaf u_two (.clk, .d(d), .q());\nendmodule\n";
let wrong = port_rename(
top,
vec![swap(top, "u_two (.clk, .", "d", "din"), put(top, ".q(", ".din(d)")],
shorthand_edits("(d)"),
);
assert!(wrong.is_err());
}
/// Verify a rename `d` → `x` of top's own port, with the given edits.
fn net_rename(top: &str, extra: Vec<TextEdit>) -> Result<(), String> {
let files = files(top);
let mut scope = Scope::build(&files);
let top_i = scope.index_of(Path::new("/rtl/top.sv")).expect("top");
let mut list = vec![swap(top, "[7:0] ", "d", "x")];
list.extend(extra);
list.sort_by_key(|e| e.range.start);
verify(&mut scope, &[(top_i, list)], "d", "x", &mut VerifyTrace::default())
}
#[test]
fn a_net_rename_that_leaves_the_wildcard_alone_is_refused() {
assert_eq!(net_rename(TOP, vec![put(TOP, "(.*", ", .d(x)")]), Ok(()));
assert!(net_rename(TOP, Vec::new()).is_err(), "`.*` loses `d`");
assert!(net_rename(TOP, vec![put(TOP, "(.*", ", .x(d)")]).is_err(), "the halves swapped");
}
#[test]
fn a_wildcard_that_starts_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 files = vec![
(PathBuf::from("/rtl/child.sv"), child.to_string()),
(PathBuf::from("/rtl/top.sv"), top.to_string()),
];
let mut scope = Scope::build(&files);
let top_i = scope.index_of(Path::new("/rtl/top.sv")).expect("top");
let edits = vec![(top_i, vec![swap(top, "logic ", "a", "b"), put(top, "(.*", ", .a(b)")])];
let captured = verify(&mut scope, &edits, "a", "b", &mut VerifyTrace::default());
assert!(captured.is_err(), "`.*` now binds `b` to the renamed port");
}
#[test]
fn a_net_rename_behind_an_unreadable_wildcard_is_refused() {
let top = "module top (input logic [7:0] d);\n ghost u_g (.*);\nendmodule\n";
let files = vec![(PathBuf::from("/rtl/top.sv"), top.to_string())];
let mut scope = Scope::build(&files);
let edits = vec![(0usize, vec![swap(top, "[7:0] ", "d", "x")])];
let blind = verify(&mut scope, &edits, "d", "x", &mut VerifyTrace::default());
assert!(blind.is_err(), "the probe of `d` and `x` moved");
}
/// `top2` with every `.` of its shorthand list blanked out: the same
/// bytes at the same offsets, but a **positional** list — so its `d`
/// ends exactly where `top2`'s shorthand `.d` does.
const POSITIONAL: &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";
/// The position check keys on the file's own sites, not on a byte: `(d)`
/// at the offset that is a shorthand's end in `top2.sv` is still refused
/// in a file where that offset ends a positional element.
#[test]
fn a_shorthand_offset_is_no_licence_in_another_file() {
let end = TOP2.find(".clk, .d").expect("the shorthand") as u32 + 8;
assert_eq!(POSITIONAL.find(" clk, d").map(|at| at as u32 + 8), Some(end));
let files = vec![
(PathBuf::from("/rtl/leaf.sv"), LEAF.to_string()),
(PathBuf::from("/rtl/top.sv"), TOP.to_string()),
(PathBuf::from("/rtl/top2.sv"), TOP2.to_string()),
(PathBuf::from("/rtl/top3.sv"), POSITIONAL.to_string()),
];
let mut scope = Scope::build(&files);
let at = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top, top2, top3) =
(at("/rtl/leaf.sv"), at("/rtl/top.sv"), at("/rtl/top2.sv"), at("/rtl/top3.sv"));
let tail = |text: &str| TextEdit { range: TextRange::empty(end), new_text: text.into() };
let mut edits = vec![
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
(top, vec![put(TOP, "(.*", ", .din(d)")]),
(top2, shorthand_edits("(d)")),
(top3, vec![tail("(d)")]),
];
edits.sort_by_key(|(file, _)| *file);
let outcome = verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default());
let refusal = outcome.expect_err("a positional `d(d)` is not a shorthand");
assert!(refusal.contains("outside a connection list in top3.sv"), "{refusal}");
}
/// The same inside one file: `(d)` after the shorthand `.d` of one
/// instance is the rewrite, `(d)` after the positional `d` of the next is
/// not — and `,` after that positional element is not either.
#[test]
fn a_shorthand_licenses_only_its_own_position() {
let top = "module top2 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.clk, .d, .q);\n leaf u_two (clk, d, q);\nendmodule\n";
let files = vec![
(PathBuf::from("/rtl/leaf.sv"), LEAF.to_string()),
(PathBuf::from("/rtl/top2.sv"), top.to_string()),
];
for extra in ["(d)", ","] {
let mut scope = Scope::build(&files);
let at = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top2) = (at("/rtl/leaf.sv"), at("/rtl/top2.sv"));
let mut list = vec![
swap(top, ".clk, .", "d", "din"),
put(top, ".clk, .d", "(d)"),
put(top, "u_two (clk, d", extra),
];
list.sort_by_key(|e| e.range.start);
let mut edits = vec![
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
(top2, list),
];
edits.sort_by_key(|(file, _)| *file);
let outcome = verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default());
assert!(outcome.is_err(), "{extra:?} after a positional `d` must be refused");
}
}
/// The comma-before-`//` pair must be one pair: a comma closing one
/// `.*` list and a bare connection written into another are each half of
/// nothing, however well each half is placed.
#[test]
fn a_comma_and_its_connection_in_different_lists_are_refused() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_a (\n .* // one\n );\n leaf u_b (\n .* // two\n );\nendmodule\n";
let files = vec![
(PathBuf::from("/rtl/leaf.sv"), LEAF.to_string()),
(PathBuf::from("/rtl/top.sv"), top.to_string()),
];
let verified = |list: Vec<TextEdit>| {
let mut scope = Scope::build(&files);
let at = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top_i) = (at("/rtl/leaf.sv"), at("/rtl/top.sv"));
let mut list = list;
list.sort_by_key(|e| e.range.start);
let mut edits = vec![
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
(top_i, list),
];
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
};
let pair = |list: &str, comment: &str| {
vec![put(top, list, ","), put(top, comment, "\n .din(d)")]
};
let honest: Vec<TextEdit> =
[pair("u_a (\n .*", "// one"), pair("u_b (\n .*", "// two")].concat();
assert_eq!(verified(honest), Ok(()), "each list's own pair");
let crossed: Vec<TextEdit> = [
pair("u_a (\n .*", "// one"),
vec![put(top, "u_b (\n .*", ","), put(top, "// one", "\n .din(d)")],
]
.concat();
let refusal = verified(crossed).expect_err("u_b's comma has no connection of its own");
assert!(refusal.contains("outside a connection list"), "{refusal}");
}
#[test]
fn the_connection_templates_are_exactly_four() {
let names = ["d", "din"];
for ok in ["(d)", " (din )", ",", ".din(d)", ",\n .din(d)", ", .d(din)"] {
assert!(is_connection_text(ok, names), "{ok:?}");
}
for bad in ["(q)", ",,", ".din(d),", "(d)//c", ".din[0](d)", "(d + d)"] {
assert!(!is_connection_text(bad, names), "{bad:?}");
}
}
}
+33 -5
View File
@@ -18,7 +18,10 @@
//! contract, kept separately, so the formatter's safety net does not widen.
mod after;
mod implicit;
mod ledger;
#[cfg(test)]
mod qa_implicit;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -58,10 +61,7 @@ pub(crate) fn verify(
let shifts = Shifts::new(scope, edits, new_name);
// 1. The token stream of every touched file, before and after.
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
let Some(before) = scope.text(*i) else { return Err(ABANDONED.to_string()) };
trace.tokens.measure(|| tokens_match(before, text, &Shift::new(edits), new_name, path))?;
}
tokens_verified(scope, edits, &edited, [old_name, new_name], &mut trace.tokens)?;
// 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
@@ -98,9 +98,10 @@ pub(crate) fn verify(
let (after_index, edited_analyses) = trace.rebuild.measure(|| after_index(scope, &edited));
for (n, &i) in watched.iter().enumerate() {
let Some(path) = scope.path(i) else { return Err(ABANDONED.to_string()) };
let inserted = implicit::inserted_in(edits, i);
let after = trace
.after
.measure(|| after_print(scope, i, path, &after_index, &edited_analyses, &[]));
.measure(|| after_print(scope, i, path, &after_index, &edited_analyses, &inserted));
let (Some(after), Some(before)) = (after, before.get(n)) else {
return Err(ABANDONED.to_string());
};
@@ -111,6 +112,33 @@ pub(crate) fn verify(
));
}
}
// 3. What every implicit connection (`.name`, `.*`) binds, before and
// after — the bindings no reference records.
let after =
implicit::After { edited: &edited, analyses: &edited_analyses, index: &after_index };
let names = [old_name, new_name];
trace.after.measure(|| implicit::bindings_match(scope, &watched, edits, &shifts, &after, names))
}
/// Step 1 of [`verify`]: every touched file's token stream, before and after.
/// A file the rename also rewrites an implicit connection in may insert —
/// only connection text, where a connection list takes it, checked piece by
/// piece (`implicit`); every other file keeps the strict token identity.
fn tokens_verified(
scope: &Scope,
edits: &[(usize, Vec<TextEdit>)],
edited: &[(PathBuf, String)],
names: [&str; 2],
stage: &mut crate::trace::Stage,
) -> Result<(), String> {
for ((i, edits), (path, text)) in edits.iter().zip(edited) {
let Some(before) = scope.text(*i) else { return Err(ABANDONED.to_string()) };
stage.measure(|| match edits.iter().any(|e| e.range.is_empty()) {
true => implicit::insertions_match(before, text, edits, names, path),
false => tokens_match(before, text, &Shift::new(edits), names[1], path),
})?;
}
Ok(())
}
@@ -0,0 +1,498 @@
//! QA M3.5 (2026-09-23): masked-corruption attacks on the rename verifier's
//! implicit-connection widening (`check::implicit`), CLAUDE.md invariant 4.
//!
//! Each attack hands `verify` the honest edits of a port rename `d` → `din`
//! of `leaf` *plus* one corrupting insertion that spells one of the four
//! connection templates `insertions_match` admits, placed somewhere a rename
//! never writes. The template check looks at an insertion's text, not at
//! where it goes, and the resolution print skips inserted ranges — so an
//! insertion outside a named connection list is seen by nothing.
//!
//! Crate-internal because `verify` is: the dev exposed no public hook.
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use super::verify;
use crate::rename::Scope;
use crate::trace::VerifyTrace;
use crate::TextEdit;
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";
/// The attacked file: a positional instance with a parameter override, a
/// function call, a task call, a concatenation, a string and a comment.
const T3: &str = "module top3 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf #(.W(8)) u_p (clk, d, q);\n initial $display(\"see .d here\");\n // comment .d here\n function automatic logic [7:0] f(input logic [7:0] a, input logic [7:0] b = 0); return a; endfunction\n logic [7:0] r;\n logic [15:0] c;\n assign r = f(d, d);\n assign c = {d, d};\n (* keep *) wire [7:0] w;\n task automatic t(); endtask\n initial t;\n leaf u_n (.clk(clk), .q({q, q}), .*);\nendmodule\n";
/// The edit replacing the whole word `name` found after `prefix`.
fn swap(text: &str, prefix: &str, name: &str, new: &str) -> TextEdit {
let from = text.find(prefix).expect("prefix") + prefix.len();
let start = (from + text[from..].find(name).expect("name")) as u32;
TextEdit { range: TextRange::new(start, start + name.len() as u32), new_text: new.into() }
}
/// The insertion of `new` right after the first `after`.
fn put(text: &str, after: &str, new: &str) -> TextEdit {
let at = (text.find(after).expect("anchor") + after.len()) as u32;
TextEdit { range: TextRange::empty(at), new_text: new.into() }
}
/// Verify the honest port rename `d` → `din` over leaf/top/top2/top3, with
/// `extra` edits added to top3 beside its own honest one (`u_n`'s `.*`).
fn attack(extra: Vec<TextEdit>) -> Result<(), String> {
let files: Vec<(PathBuf, String)> = [
("/rtl/leaf.sv", LEAF),
("/rtl/top.sv", TOP),
("/rtl/top2.sv", TOP2),
("/rtl/top3.sv", T3),
]
.iter()
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
.collect();
let mut scope = Scope::build(&files);
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top, top2, top3) =
(index("/rtl/leaf.sv"), index("/rtl/top.sv"), index("/rtl/top2.sv"), index("/rtl/top3.sv"));
let mut t3 = vec![put(T3, "u_n (.clk(clk), .q({q, q}), .*", ", .din(d)")];
t3.extend(extra);
t3.sort_by_key(|e| (e.range.start, e.range.end));
let mut edits = vec![
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
(top, vec![put(TOP, "(.*", ", .din(d)")]),
(top2, vec![swap(TOP2, ".clk, .", "d", "din"), put(TOP2, ".clk, .d", "(d)")]),
(top3, t3),
];
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
}
#[test]
fn qa_the_honest_edits_verify() {
assert_eq!(attack(Vec::new()), Ok(()));
}
#[test]
fn qa_insertions_the_verifier_already_refuses() {
// Inside a string, a comment, an attribute; an empty named element;
// `(d)` after a `.*` or after an explicit connection; a connection
// before the first element with no comma; a second `.din(d)`.
for (anchor, text) in [
("see .d", "(d)"),
("comment .d", "(d)"),
("(* keep", "(d)"),
("u_n (.clk(clk),", ","),
("u_n (.clk(clk), .q({q, q}), .*", "(d)"),
("u_n (.clk(clk)", "(d)"),
("u_n (", ".din(d)"),
("u_n (.clk(clk), .q({q, q}), .*", ", .din(d)"),
] {
let outcome = attack(vec![put(T3, anchor, text)]);
assert!(outcome.is_err(), "{text:?} after {anchor:?} must be refused");
}
}
/// QA finding 1: an insertion is checked for its text, never for its place.
/// A lone `,` in a positional list shifts every later connection one port
/// down — `leaf u_p (clk,, d, q)` connects `d` to `q`'s port.
#[test]
fn qa_a_comma_inserted_into_a_positional_list_is_refused() {
let outcome = attack(vec![put(T3, "u_p (clk,", ",")]);
assert!(outcome.is_err(), "`u_p (clk,, d, q)` rewires the instance");
}
/// QA finding 1: a connection template inserted outside any connection list.
#[test]
fn qa_connection_text_outside_a_connection_list_is_refused() {
for (anchor, text) in [
("#(.W(8)", ", .din(d)"), // a parameter override
("assign r = f(d, d", "(d)"), // `d(d)`: a call on a net
("assign r = f(d,", ","), // an empty (defaulted) argument
("assign r = f(d, d", ", .din(d)"), // a named argument
("initial t", "(d)"), // a task call gains an argument
("assign c = {d,", ","), // an empty concatenation element
] {
let outcome = attack(vec![put(T3, anchor, text)]);
assert!(outcome.is_err(), "{text:?} after {anchor:?} must be refused: {outcome:?}");
}
}
/// QA finding 1, inside a named list: the template lands inside an explicit
/// connection's expression, which the binding print does not look into
/// (`Bound::Expression` is printed only for a port spelling one of the
/// names) and the resolution print skips.
#[test]
fn qa_connection_text_inside_an_explicit_connection_is_refused() {
for (anchor, text) in [
("u_n (.clk(clk", "(d)"), // `.clk(clk(d))`
("u_n (.clk(clk), .q({q", "(d)"), // `.q({q(d), q})`
("u_n (.clk(clk), .q({q,", ","), // `.q({q,, q})`
] {
let outcome = attack(vec![put(T3, anchor, text)]);
assert!(outcome.is_err(), "{text:?} after {anchor:?} must be refused: {outcome:?}");
}
}
// ----------------------------------------------------------------------
// M3.5 re-check (2026-09-23): attacks on the position rule (`Slots`)
// ----------------------------------------------------------------------
/// Verify a port rename `d` → `new` of `leaf` (whose two occurrences are
/// renamed honestly) with `top3`'s edits exactly as given — nothing honest
/// added there.
fn port_rename_with(new: &str, top3: &str, edits3: Vec<TextEdit>) -> Result<(), String> {
let files: Vec<(PathBuf, String)> = [("/rtl/leaf.sv", LEAF), ("/rtl/top3.sv", top3)]
.iter()
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
.collect();
let mut scope = Scope::build(&files);
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top) = (index("/rtl/leaf.sv"), index("/rtl/top3.sv"));
let mut edits3 = edits3;
edits3.sort_by_key(|e| (e.range.start, e.range.end));
let mut edits =
vec![(leaf, vec![swap(LEAF, "[7:0] ", "d", new), swap(LEAF, "q <= ", "d", new)])];
if !edits3.is_empty() {
edits.push((top, edits3));
}
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", new, &mut VerifyTrace::default())
}
fn outside(outcome: &Result<(), String>) -> bool {
outcome.as_ref().is_err_and(|refusal| refusal.contains("outside a connection list"))
}
const HEAD: &str = "module top3 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n";
#[test]
fn qa_r_an_append_to_a_named_list_without_a_wildcard_is_outside() {
let top = format!("{HEAD} leaf u_c (.clk(clk), .q(q));\nendmodule\n");
let appended = port_rename_with("din", &top, vec![put(&top, ".q(q)", ", .din(d)")]);
assert!(outside(&appended), "no `.*`, no append: {appended:?}");
}
#[test]
fn qa_r_a_tail_after_an_explicit_connections_name_is_outside() {
let top = format!("{HEAD} leaf u_c (.clk(clk), .d(d), .q(q));\nendmodule\n");
let honest = vec![swap(&top, "(clk), .", "d", "din")];
assert_eq!(port_rename_with("din", &top, honest.clone()), Ok(()));
for anchor in ["u_c (.clk", "(clk), .d"] {
let mut edits = honest.clone();
edits.push(put(&top, anchor, "(d)"));
let outcome = port_rename_with("din", &top, edits);
assert!(outside(&outcome), "`(d)` after {anchor:?}: {outcome:?}");
}
}
#[test]
fn qa_r_an_insertion_between_two_elements_of_a_wildcard_list_is_outside() {
let top = format!("{HEAD} leaf u_n (.*, .clk(clk));\nendmodule\n");
let honest = port_rename_with("din", &top, vec![put(&top, ".clk(clk)", ", .din(d)")]);
assert_eq!(honest, Ok(()), "the append after the last element is the rewrite");
let early = port_rename_with("din", &top, vec![put(&top, "u_n (.*", ", .din(d)")]);
assert!(outside(&early), "between `.*` and `.clk(clk)`: {early:?}");
}
#[test]
fn qa_r_an_insertion_after_the_closing_paren_is_outside() {
let top = format!("{HEAD} leaf u_n (.*);\nendmodule\n");
for text in [", .din(d)", "(d)", ","] {
let outcome = port_rename_with("din", &top, vec![put(&top, "u_n (.*)", text)]);
assert!(outside(&outcome), "{text:?} after `)`: {outcome:?}");
}
}
#[test]
fn qa_r_a_wildcard_list_inside_a_generate_block() {
let top = format!(
"{HEAD} for (genvar i = 0; i < 2; i++) begin : g\n leaf u_g (.*);\n end\nendmodule\n"
);
let honest = port_rename_with("din", &top, vec![put(&top, "u_g (.*", ", .din(d)")]);
assert_eq!(honest, Ok(()), "the generate-scoped `.*` is a slot like any other");
// A bare `.din(d)` needs the `,` written before it.
let bare = port_rename_with("din", &top, vec![put(&top, "u_g (.*", ".din(d)")]);
assert!(outside(&bare), "{bare:?}");
// The same `.*` with nothing added cuts the binding.
assert!(port_rename_with("din", &top, Vec::new()).is_err());
}
#[test]
fn qa_r_a_lone_trailing_comma_is_refused() {
// `,` at a `.*` list's end is a slot (the comma before a `//` comment),
// but written alone it leaves `(.*,)`, which is not a connection list.
let top = format!("{HEAD} leaf u_n (.*);\n leaf u_m (.clk, .d, .q);\nendmodule\n");
let edits = vec![
swap(&top, "u_m (.clk, .", "d", "din"),
put(&top, "u_m (.clk, .d", "(d)"),
put(&top, "u_n (.*", ", .din(d)"),
];
assert_eq!(port_rename_with("din", &top, edits.clone()), Ok(()));
let mut trailing = edits.clone();
trailing.push(put(&top, "u_n (.*", ","));
trailing.retain(|e| e.new_text != ", .din(d)");
let outcome = port_rename_with("din", &top, trailing);
assert!(outcome.is_err(), "`(.*,)`: {outcome:?}");
}
#[test]
fn qa_r_positions_are_before_coordinates_whatever_an_earlier_edit_shifts() {
// `d` → `dnw` grows the line by 2... and `dnew` by 3, which is exactly the
// distance from `.d`'s end to `.q`'s end in `.d,.q`. A tail computed in
// after-coordinates lands on `.q`'s shorthand slot in before-coordinates.
let top = format!("{HEAD} leaf u_s (.clk,.d,.q);\nendmodule\n");
let rename = swap(&top, "u_s (.clk,.", "d", "dnew");
let d_end = top.find("u_s (.clk,.d").expect("d") as u32 + 12;
let q_end = top.find("u_s (.clk,.d,.q").expect("q") as u32 + 15;
assert_eq!(q_end, d_end + 3, "premise: the shift equals the gap");
let tail = |at: u32| TextEdit { range: TextRange::empty(at), new_text: "(d)".into() };
assert_eq!(port_rename_with("dnew", &top, vec![rename.clone(), tail(d_end)]), Ok(()));
let shifted = port_rename_with("dnew", &top, vec![rename, tail(q_end)]);
assert!(shifted.is_err(), "`.dnew,.q(d)` must be refused: {shifted:?}");
}
#[test]
fn qa_r_an_append_inside_the_trailing_comment_is_refused() {
// The gap from `.*` to the insertion is only trivia, so the slot rule
// lets it through; the piece ledger must see the comment change.
let top = format!("{HEAD} leaf u_n (\n .* // the rest\n );\nendmodule\n");
for anchor in ["// the", "// the rest"] {
let outcome = port_rename_with("din", &top, vec![put(&top, anchor, ", .din(d)")]);
assert!(outcome.is_err(), "inside/at the end of the comment ({anchor:?}): {outcome:?}");
}
// The rewrite `layout.rs` writes: `,` before the comment, the connection
// on its own line after it.
let honest = vec![put(&top, " .*", ","), put(&top, "// the rest", "\n .din(d)")];
assert_eq!(port_rename_with("din", &top, honest), Ok(()));
// The bare connection without its comma, and the pair with the
// connection written inside the comment.
let bare = port_rename_with("din", &top, vec![put(&top, "// the rest", "\n .din(d)")]);
assert!(outside(&bare), "{bare:?}");
let inside = vec![put(&top, " .*", ","), put(&top, "// the", "\n .din(d)")];
assert!(port_rename_with("din", &top, inside).is_err(), "the comment is split");
}
/// Verify a net rename `d` → `x` of top's port, the bind file's edits given.
fn bind_net_rename(bind_edits: Vec<TextEdit>, bind: &str) -> Result<(), String> {
let top =
"module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\nendmodule\n";
let files: Vec<(PathBuf, String)> =
[("/rtl/leaf.sv", LEAF), ("/rtl/top.sv", top), ("/rtl/binds.sv", bind)]
.iter()
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
.collect();
let mut scope = Scope::build(&files);
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (top_i, binds) = (index("/rtl/top.sv"), index("/rtl/binds.sv"));
let mut edits = vec![(top_i, vec![swap(top, "[7:0] ", "d", "x")])];
let mut bind_edits = bind_edits;
bind_edits.sort_by_key(|e| e.range.start);
if !bind_edits.is_empty() {
edits.push((binds, bind_edits));
}
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", "x", &mut VerifyTrace::default())
}
#[test]
fn qa_r_a_shorthand_in_a_bind() {
let bind = "module binds;\n bind top leaf u_b (.clk, .d, .q);\nendmodule\n";
assert_eq!(bind_net_rename(vec![put(bind, ".clk, .d", "(x)")], bind), Ok(()));
assert!(bind_net_rename(Vec::new(), bind).is_err(), "`.d` left dangling");
// `.clk` is a shorthand slot too: the binding print is what refuses it.
let wrong = bind_net_rename(vec![put(bind, ".clk", "(x)")], bind);
assert!(wrong.is_err_and(|r| r.contains("implicit connection of `u_b`")));
let stale = bind_net_rename(vec![put(bind, ".clk, .d", "(d)")], bind);
assert!(stale.is_err(), "`.d(d)` names nothing in top any more");
}
/// QA finding 3 (re-check): `Slots::takes` admits a lone `,` at the end of
/// *any* `.*` list — the comma half of the comma-before-`//` pair — without
/// its `.X(Y)` half. Where the list binds one of the names the binding print
/// refuses it (`qa_r_a_lone_trailing_comma_is_refused`); here `other`
/// declares neither name, the binding print has nothing to compare, and the
/// tolerant parser reports no diagnostic for `(.*,)`, so it verifies.
#[test]
fn qa_r_a_lone_trailing_comma_on_a_wildcard_binding_neither_name() {
let other = "module other (input logic clk);\nendmodule\n";
let top = format!("{HEAD} other u_o (.*);\n leaf u_m (.clk, .d, .q);\nendmodule\n");
let files: Vec<(PathBuf, String)> =
[("/rtl/leaf.sv", LEAF), ("/rtl/other.sv", other), ("/rtl/top3.sv", top.as_str())]
.iter()
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
.collect();
let edits_with = |extra: Option<TextEdit>| {
let mut scope = Scope::build(&files);
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top3) = (index("/rtl/leaf.sv"), index("/rtl/top3.sv"));
let mut list =
vec![swap(&top, "u_m (.clk, .", "d", "din"), put(&top, "u_m (.clk, .d", "(d)")];
list.extend(extra);
list.sort_by_key(|e| e.range.start);
let mut edits = vec![
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
(top3, list),
];
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
};
assert_eq!(edits_with(None), Ok(()));
let trailing = edits_with(Some(put(&top, "u_o (.*", ",")));
assert!(trailing.is_err(), "`other u_o (.*,)` does not compile: {trailing:?}");
}
// ----------------------------------------------------------------------
// M3.5 final re-check (2026-09-23): attacks on the comma/connection pair
// ----------------------------------------------------------------------
/// A `.*` list one per line with a `//` comment on its last element.
fn commented(name: &str) -> String {
format!("{HEAD} leaf {name} (\n .* // the rest\n );\nendmodule\n")
}
/// Verify the port rename `d` → `din` with the two files' edits as given.
fn two_files(top3: &str, e3: Vec<TextEdit>, top4: &str, e4: Vec<TextEdit>) -> Result<(), String> {
let files: Vec<(PathBuf, String)> =
[("/rtl/leaf.sv", LEAF), ("/rtl/top3.sv", top3), ("/rtl/top4.sv", top4)]
.iter()
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
.collect();
let mut scope = Scope::build(&files);
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, t3, t4) = (index("/rtl/leaf.sv"), index("/rtl/top3.sv"), index("/rtl/top4.sv"));
let mut edits =
vec![(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")])];
for (file, list) in [(t3, e3), (t4, e4)] {
if !list.is_empty() {
edits.push((file, list));
}
}
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
}
#[test]
fn qa_p_a_comma_in_one_file_and_its_connection_in_another_are_refused() {
let (a, b) = (commented("u_a"), commented("u_b"));
let comma = |t: &str| put(t, " .*", ",");
let conn = |t: &str| put(t, "// the rest", "\n .din(d)");
let honest = two_files(&a, vec![comma(&a), conn(&a)], &b, vec![comma(&b), conn(&b)]);
assert_eq!(honest, Ok(()));
let split = two_files(&a, vec![comma(&a)], &b, vec![conn(&b)]);
assert!(outside(&split), "each file holds half a pair: {split:?}");
let split = two_files(&a, vec![conn(&a)], &b, vec![comma(&b)]);
assert!(outside(&split), "the other way round: {split:?}");
}
#[test]
fn qa_p_two_commas_and_one_connection_in_one_list_are_refused() {
let top = commented("u_n");
let comma = || put(&top, " .*", ",");
let conn = || put(&top, "// the rest", "\n .din(d)");
assert_eq!(port_rename_with("din", &top, vec![comma(), conn()]), Ok(()));
let doubled = port_rename_with("din", &top, vec![comma(), comma(), conn()]);
assert!(doubled.is_err(), "`.*,, // the rest` must be refused: {doubled:?}");
let twice = port_rename_with("din", &top, vec![comma(), conn(), conn()]);
assert!(twice.is_err(), "one comma, two connections: {twice:?}");
}
#[test]
fn qa_p_a_connection_before_its_comma_in_offset_order_is_refused() {
let top = commented("u_n");
let comma = || put(&top, " .*", ",");
// Both at the `.*`'s end, the connection first: `.*\n .din(d), //…`.
let early = put(&top, " .*", "\n .din(d)");
let reversed = port_rename_with("din", &top, vec![early.clone(), comma()]);
assert!(reversed.is_err(), "{reversed:?}");
let glued = port_rename_with("din", &top, vec![put(&top, " .*", ".din(d)"), comma()]);
assert!(glued.is_err(), "`.*.din(d),`: {glued:?}");
// In source order the same two pieces are a legal list whose comment
// now ends the new line: `.*,\n .din(d) // the rest` — accepted, and
// harmless (same bindings, the comment kept).
assert_eq!(port_rename_with("din", &top, vec![comma(), early]), Ok(()));
}
/// `.d(type(q)'(q))` is valid SV (a cast through the type operator) that the
/// tolerant parser reads as an error element `.d(type(q)'(q)` — one byte short
/// of the connection's `)`.
fn cast_list() -> String {
format!("{HEAD} leaf u_e (.*, .d(type(q)'(q)));\nendmodule\n")
}
#[test]
fn qa_p_a_pair_after_an_error_element() {
// After the connection's `)`: the gap to the error element's end is not
// trivia, so no slot.
let cast = cast_list();
let rename = swap(&cast, "u_e (.*, .", "d", "din");
let after_conn = put(&cast, "(q)'(q))", ", .din(d)");
let outcome = port_rename_with("din", &cast, vec![rename, after_conn]);
assert!(outside(&outcome), "{outcome:?}");
// Text that is not SV at all (`+.din(x)`): the verifier used to admit
// the pair after it (the error element is invisible to the binding
// print). Since finding 4 a list holding an error element has no slot at
// all, so the pair is refused — the engine refuses such a list too
// (`unreadable_elements`). Pinned so a change is noticed.
let junk = format!("{HEAD} leaf u_e (\n .*, +.din(x) // the rest\n );\nendmodule\n");
let pair = vec![put(&junk, "+.din(x)", ","), put(&junk, "// the rest", "\n .din(d)")];
let outcome = port_rename_with("din", &junk, pair);
assert!(outside(&outcome), "{outcome:?}");
assert!(port_rename_with("din", &junk, Vec::new()).is_err(), "the cut is still seen");
}
/// QA finding 4 (final re-check): a list holding an error element still
/// registers a slot at the element's end. For valid SV the parser misreads
/// (`.d(type(q)'(q))`, element ending before the connection's own `)`), an
/// append there lands *inside* that connection:
/// `.din(type(q)'(q), .din(d)))` — valid input, output that does not compile,
/// and it verifies: the diagnostic count is compared, not the diagnostics, and
/// the binding print cannot see into an error element. The engine never
/// writes it (`unreadable_elements` refuses a list whose error element spells
/// either name). Loud, not silent — but accepted.
#[test]
fn qa_p_an_append_at_an_error_elements_end_is_refused() {
let cast = cast_list();
let rename = swap(&cast, "u_e (.*, .", "d", "din");
let at_error = put(&cast, "(q)'(q)", ", .din(d)");
let outcome = port_rename_with("din", &cast, vec![rename, at_error]);
assert!(outcome.is_err(), "`.din(type(q)'(q), .din(d)))` must be refused: {outcome:?}");
}
#[test]
fn qa_p_a_clean_list_beside_an_error_element_list_still_verifies() {
// Finding 4's fix drops the slots of the list holding the error element
// only: an honest rewrite of a clean list in the same file still
// verifies, and the same append into the unreadable list is refused.
let other = "module other (input logic clk);\nendmodule\n";
let top = format!(
"{HEAD} other u_x (.*, .clk(type(clk)'(clk)));\n leaf u_n (.*);\n leaf u_m (.clk, .d, .q);\nendmodule\n"
);
let files: Vec<(PathBuf, String)> =
[("/rtl/leaf.sv", LEAF), ("/rtl/other.sv", other), ("/rtl/top3.sv", top.as_str())]
.iter()
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
.collect();
let run = |extra: Option<TextEdit>| {
let mut scope = Scope::build(&files);
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top3) = (index("/rtl/leaf.sv"), index("/rtl/top3.sv"));
let mut list = vec![
put(&top, "u_n (.*", ", .din(d)"),
swap(&top, "u_m (.clk, .", "d", "din"),
put(&top, "u_m (.clk, .d", "(d)"),
];
list.extend(extra);
list.sort_by_key(|e| e.range.start);
let mut edits = vec![
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
(top3, list),
];
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
};
assert_eq!(run(None), Ok(()), "the error element sits in another instance's list");
let into_error = run(Some(put(&top, "(clk)'(clk)", ", .din(d)")));
assert!(outside(&into_error), "{into_error:?}");
}
@@ -0,0 +1,609 @@
//! A rename versus the connections that name it **implicitly**: the `.name`
//! shorthand and the `.*` wildcard (IEEE 1800 §23.3.2.3–4).
//!
//! Both bind by *equal names*, so renaming either side cuts the binding
//! without a single reference moving — the semantic layer records the port
//! half of `.name` and nothing else of either. Two directions:
//!
//! * **A port `p` → `q` of module `M`.** In every instance of `M`, the
//! shorthand `.p` (whose port half the rename already edits to `.q`) gets
//! its net written out: `.q(p)`. A `.*` that bound `p` gets an explicit
//! `.q(p)` added beside it, which is legal and wins over the wildcard.
//! * **A net, variable or port `n` → `m` seen by an instance.** The shorthand
//! `.n` becomes `.n(m)`; a `.*` whose module declares a port `n` gets
//! `.n(m)` added. That covers the instances written where `n` is visible,
//! and the `bind` directives whose target is the module declaring it.
//!
//! Every rewrite is an **insertion** (the port half of `.p` is the rename's
//! own edit), every one is listed in the warnings, and anything lucisv cannot
//! read is refused rather than guessed: an unreadable `.*` module, a module
//! declared twice, a list split by compiler directives or holding text that
//! did not parse, a hierarchical `bind` target, and a `.*` that would start
//! binding the new name. `check::implicit` then re-derives every implicit
//! binding before and after, so an edit here that got it wrong is refused.
use std::collections::HashMap;
use vlog_parser::ast::PortList;
use vlog_parser::{parse_source_tolerant, LineIndex};
use vlog_semantic::{ScopeKind, Surface, SymbolId, SymbolKind};
use super::layout::{append, connection, shorthand_tail};
use super::sites::{binds_implicitly, may_connect_implicitly, nearest, sites, Site};
use super::{contains_word, display, Scope, Target};
use crate::TextEdit;
/// The insertions a rename's implicit connections need, and the sentences
/// that tell the user about each one.
#[derive(Default)]
pub(super) struct Implicit {
pub(super) edits: Vec<(usize, Vec<TextEdit>)>,
pub(super) warnings: Vec<String>,
}
/// Where the renamed declaration lives, as far as an implicit binding cares.
enum Home {
/// Inside module `name`; `top` when directly in the module's own scope,
/// which is the only scope a `bind` into that module reaches.
Module { name: String, top: bool },
/// Inside package `name`: visible wherever it is imported.
Package(String),
/// Anywhere else (a function, a class, the compilation unit).
Elsewhere,
}
/// The rename, as the walk needs it.
struct Renamed {
old: String,
new: String,
file: usize,
symbol: SymbolId,
kind: SymbolKind,
home: Home,
}
/// What a `bind` directive's connections can see of the renamed module.
enum Reach {
/// Its own top-level scope: the bind targets the module by name.
Module,
/// Possibly it: a target lucisv cannot tie to one module.
Maybe,
/// Not it: the target is another module, or instances of other modules.
Elsewhere,
}
/// A module's declared port names, or why lucisv cannot read them.
type Ports = Result<Vec<String>, &'static str>;
/// One pass over the in-scope files.
struct Walk<'r> {
renamed: &'r Renamed,
/// The rename's own edits: a shorthand is rewritten only where its port
/// half is one of them.
occurrences: &'r [(usize, Vec<TextEdit>)],
out: Implicit,
ports: HashMap<String, Ports>,
}
impl<'a> Scope<'a> {
/// The implicit connections renaming `target` to `new_name` must rewrite.
/// `occurrences` are the rename's own edits.
pub(super) fn implicit_connections(
&mut self,
target: &Target,
new_name: &str,
occurrences: &[(usize, Vec<TextEdit>)],
) -> Result<Implicit, String> {
let Some(renamed) = self.renamed(target, new_name) else { return Ok(Implicit::default()) };
let mut walk = Walk {
renamed: &renamed,
occurrences,
out: Implicit::default(),
ports: HashMap::new(),
};
if let (SymbolKind::Port, Home::Module { name, top: true }) = (renamed.kind, &renamed.home)
{
self.port_users(&mut walk, name)?;
}
self.signal_users(&mut walk)?;
let mut out = walk.out;
for (_, edits) in &mut out.edits {
edits.sort_by_key(|e| (e.range.start, e.range.end));
}
Ok(out)
}
/// What the target is and where it lives, read off its own analysis.
fn renamed(&mut self, target: &Target, new_name: &str) -> Option<Renamed> {
let semantics = &self.analysis(target.file)?.semantics;
let symbol = semantics.symbol(target.symbol)?;
let mut scope = semantics.scope(symbol.scope);
let mut top = true;
let home = loop {
let Some(here) = scope else { break Home::Elsewhere };
let owner = here.owner.and_then(|o| semantics.symbol(o)).map(|o| o.name.clone());
match (here.kind, owner) {
(ScopeKind::Module, Some(name)) => break Home::Module { name, top },
(ScopeKind::Package, Some(name)) => break Home::Package(name),
(ScopeKind::Generate | ScopeKind::Block, _) => {}
_ => break Home::Elsewhere,
}
top = false;
scope = here.parent.and_then(|p| semantics.scope(p));
};
Some(Renamed {
old: target.name.clone(),
new: new_name.to_string(),
file: target.file,
symbol: target.symbol,
kind: symbol.kind,
home,
})
}
/// Direction one: every instance of the module whose port is renamed.
fn port_users(&mut self, walk: &mut Walk, module: &str) -> Result<(), String> {
let ours = self.unique_module(module).is_some_and(|file| file == walk.renamed.file);
let old = [walk.renamed.old.as_str()];
for i in 0..self.len() {
let wanted =
|text: &&str| contains_word(text, module) && may_connect_implicitly(text, &old);
let Some(text) = self.text(i).filter(wanted) else { continue };
let (tree, _) = parse_source_tolerant(text);
for site in sites(&tree.items).iter().filter(|s| s.instantiation.module == module) {
self.port_site(walk, i, text, site, ours)?;
}
}
Ok(())
}
/// One instance of the module whose port `p` becomes `q`.
fn port_site(
&mut self,
walk: &mut Walk,
file: usize,
text: &str,
site: &Site,
ours: bool,
) -> Result<(), String> {
let (old, new) = (walk.renamed.old.as_str(), walk.renamed.new.as_str());
let here = self.describe(file, text, site);
unreadable_elements(site, old, new, &here)?;
if let Some(c) = site.named(old) {
let edited = walk
.occurrences
.iter()
.any(|(f, edits)| *f == file && edits.iter().any(|e| e.range == c.name_span));
if c.expr.is_some() || !edited {
return Ok(());
}
if site.bind_target().is_err() {
return Err(hierarchical_bind(&here, old));
}
let written = connection(new, old);
walk.push(file, vec![shorthand_tail(c.name_span.end, new, old)]);
walk.out.warnings.push(format!(
"{here} connected `{old}` by the shorthand `.{old}`; wrote `{written}` so it still binds the same net."
));
return Ok(());
}
if !site.has_wildcard() {
return Ok(());
}
directives(site, &here)?;
if !ours {
return Err(wildcard_unreadable(&here, &site.instantiation.module, old));
}
match self.wildcard_sees(file, site, old, new, &here)? {
(true, _) => walk.append(file, text, site, &connection(new, old), &here, old),
(false, true) => Err(captured(&here, new)),
(false, false) => Ok(()),
}
}
/// Whether a `.*` at `site` binds something named `old`, and whether it
/// would bind something named `new` — what decides between adding
/// `.new(old)`, refusing, and leaving the wildcard alone.
fn wildcard_sees(
&mut self,
file: usize,
site: &Site,
old: &str,
new: &str,
here: &str,
) -> Result<(bool, bool), String> {
match site.bind_target() {
Ok(None) => {
let Some(analysis) = self.analysis(file) else { return Ok((false, false)) };
let semantics = &analysis.semantics;
let offset = site.instance.name_span.start;
let binds = |name| {
let found = nearest(semantics, offset, name).and_then(|s| semantics.symbol(s));
found.is_some_and(|s| binds_implicitly(s.kind))
};
Ok((binds(old), binds(new)))
}
Ok(Some(target)) => {
if self.unique_module(target).is_none() {
return Err(bind_unreadable(here, target));
}
let binds = |name| {
let defs = self.index.member_in(target, name, Surface::Hierarchical);
defs.iter().any(|d| binds_implicitly(d.kind))
};
Ok((binds(old), binds(new)))
}
Err(()) => Err(hierarchical_bind(here, old)),
}
}
/// Direction two: every instance whose implicit connections can see the
/// renamed declaration under its old name.
fn signal_users(&mut self, walk: &mut Walk) -> Result<(), String> {
let renamed = walk.renamed;
if !binds_implicitly(renamed.kind) {
return Ok(());
}
let (file, symbol, old) = (renamed.file, renamed.symbol, renamed.old.as_str());
let rewrite = !matches!(renamed.home, Home::Package(_));
if let Some(text) = self.text(file).filter(|text| may_connect_implicitly(text, &[old])) {
let (tree, _) = parse_source_tolerant(text);
for site in sites(&tree.items).iter().filter(|s| s.bind.is_none()) {
if self.nearest_at(file, site, old) == Some(symbol) {
self.signal_site(walk, file, text, site, rewrite)?;
}
}
}
match &renamed.home {
Home::Module { name, top: true } => self.binds_into(walk, name, rewrite),
Home::Package(name) => self.importers(walk, name),
_ => Ok(()),
}
}
/// The nearest declaration of `name` where `site`'s implicit connections
/// bind, for an ordinary instantiation in `file`.
fn nearest_at(&mut self, file: usize, site: &Site, name: &str) -> Option<SymbolId> {
let analysis = self.analysis(file)?;
nearest(&analysis.semantics, site.instance.name_span.start, name)
}
/// The `bind` directives that bind into module `module`, whose connections
/// see its own top-level declarations — and the ones whose target lucisv
/// cannot name, which might.
fn binds_into(&mut self, walk: &mut Walk, module: &str, rewrite: bool) -> Result<(), String> {
let old = [walk.renamed.old.as_str()];
for i in 0..self.len() {
let wanted =
|text: &&str| contains_word(text, "bind") && may_connect_implicitly(text, &old);
let Some(text) = self.text(i).filter(wanted) else { continue };
let (tree, _) = parse_source_tolerant(text);
for site in sites(&tree.items).iter().filter(|s| s.bind.is_some()) {
match self.bind_reaches(i, site, module) {
Reach::Module => self.signal_site(walk, i, text, site, rewrite)?,
Reach::Maybe => self.signal_site(walk, i, text, site, false)?,
Reach::Elsewhere => {}
}
}
}
Ok(())
}
/// Whether a `bind`'s connections see `module`'s own scope.
///
/// A lone target is a module name or an **instance** name (IEEE 1800
/// §23.11). A module lucisv indexes is that module; otherwise the index's
/// instantiation edges say which modules own an instance of that name
/// (QA M3.5 finding 2: `bind i_nopass1 … (.clk_i, …)` into a
/// `prim_fifo_sync` refused `clk_i` renames of every other module). Owned
/// by other modules only — elsewhere; owned by nobody lucisv indexes, or by
/// `module` itself — maybe, which refuses what it would bind: the verifier
/// cannot name an instance's scope, so a rewrite there would be refused
/// anyway, and saying so up front is the clearer sentence.
fn bind_reaches(&self, file: usize, site: &Site, module: &str) -> Reach {
let target = match site.bind_target() {
Ok(Some(target)) => target,
Ok(None) => return Reach::Elsewhere,
Err(()) => return Reach::Maybe,
};
if target == module {
return Reach::Module;
}
if !self.index.units(target).is_empty() {
return Reach::Elsewhere;
}
let owners = self.instance_owners(file, site, target);
match owners.is_empty() || owners.contains(&module) {
true => Reach::Maybe,
false => Reach::Elsewhere,
}
}
/// The modules an instance named `target` instantiates, as a `bind`
/// written at `site` sees them. A bare instance name is found by upward
/// name resolution from the bind's own scope (§23.11), so the instances
/// the **enclosing module** declares answer first — `bind dut … (.*)` in
/// sram_ctrl's bench means that bench's `dut`, not entropy_src's — and
/// only when it declares none does every instance of that name count.
fn instance_owners(&self, file: usize, site: &Site, target: &str) -> Vec<&str> {
let here = self.file_id(file);
let at = site.instance.span.start;
let named = |edge: &vlog_semantic::InstantiationEdge| {
edge.instances.iter().any(|instance| instance.name == target)
};
let enclosing = |edge: &vlog_semantic::InstantiationEdge| {
Some(edge.file) == here && edge.owner.span.contains(at)
};
// Keyed by the module *instantiated*, which is what the bind reaches.
let mut local: Vec<&str> = Vec::new();
let mut anywhere: Vec<&str> = Vec::new();
for (instantiated, edges) in self.index.instantiations() {
if edges.iter().any(|edge| named(edge) && enclosing(edge)) {
local.push(instantiated);
}
if edges.iter().any(named) {
anywhere.push(instantiated);
}
}
if local.is_empty() {
anywhere
} else {
local
}
}
/// The instances that may see a package's declaration through an import:
/// any instance, in a file naming the package, that declares nothing of
/// that name itself. lucisv does not follow imports into `.*`, so these are
/// refused rather than rewritten.
fn importers(&mut self, walk: &mut Walk, package: &str) -> Result<(), String> {
let old = walk.renamed.old.as_str();
for i in 0..self.len() {
let wanted =
|text: &&str| contains_word(text, package) && may_connect_implicitly(text, &[old]);
let Some(text) = self.text(i).filter(wanted) else { continue };
let (tree, _) = parse_source_tolerant(text);
for site in sites(&tree.items).iter() {
if site.bind.is_some() || self.nearest_at(i, site, old).is_none() {
self.signal_site(walk, i, text, site, false)?;
}
}
}
Ok(())
}
/// One instance whose implicit connections see the renamed declaration.
/// `rewrite` is false where lucisv can only refuse what it finds.
fn signal_site(
&mut self,
walk: &mut Walk,
file: usize,
text: &str,
site: &Site,
rewrite: bool,
) -> Result<(), String> {
let renamed = walk.renamed;
let (old, new) = (renamed.old.as_str(), renamed.new.as_str());
let here = self.describe(file, text, site);
unreadable_elements(site, old, new, &here)?;
if let Some(c) = site.named(old).filter(|c| c.expr.is_none()) {
if !rewrite {
return Err(cannot_rewrite(&here, old, &format!(".{old}")));
}
let written = connection(old, new);
walk.push(file, vec![shorthand_tail(c.name_span.end, old, new)]);
walk.out.warnings.push(format!(
"{here} connected `{old}` by the shorthand `.{old}`; wrote `{written}`."
));
}
if !site.has_wildcard() {
return Ok(());
}
directives(site, &here)?;
let module = site.instantiation.module.clone();
let ports = match walk.ports_of(self, &module) {
Ok(ports) => ports,
Err(why) => return Err(wildcard_problem(&here, &module, old, why)),
};
let declares = |name: &str| ports.iter().any(|port| port == name);
if declares(new) && site.named(new).is_none() {
return Err(captured(&here, new));
}
if !declares(old) || site.named(old).is_some() {
return Ok(());
}
if !rewrite {
return Err(cannot_rewrite(&here, old, ".*"));
}
walk.append(file, text, site, &connection(old, new), &here, old)
}
/// The one in-scope file declaring module `name`, if exactly one does.
fn unique_module(&self, name: &str) -> Option<usize> {
let defs: Vec<_> =
self.index.units(name).iter().filter(|def| def.kind.is_instantiable()).collect();
let [def] = defs.as_slice() else { return None };
self.index.path(def.file).and_then(|path| self.index_of(path))
}
/// The declared ports of module `name`, read from its declaring file.
fn read_ports(&self, name: &str) -> Ports {
let count = self.index.units(name).iter().filter(|d| d.kind.is_instantiable()).count();
if count > 1 {
return Err(TWICE);
}
let file = self.unique_module(name).ok_or(UNREADABLE)?;
let text = self.text(file).ok_or(UNREADABLE)?;
let (tree, _) = parse_source_tolerant(text);
let (module, _) = crate::ports::find_module(&tree, name).ok_or(UNREADABLE)?;
if !module.port_directives.is_empty() {
return Err(DIRECTIVES);
}
let names = match &module.ports {
PortList::Ansi(ports) => ports.iter().map(|p| p.ok().map(|p| p.name.clone())).collect(),
PortList::NonAnsi(ports) => {
ports.iter().map(|p| p.ok().map(|p| p.name.clone())).collect()
}
PortList::Empty | PortList::None => Some(Vec::new()),
};
names.ok_or(UNREADABLE)
}
/// "`u_leaf` at top.sv:12", the way every sentence here names an instance.
fn describe(&self, file: usize, text: &str, site: &Site) -> String {
let path = self.path(file).map(display).unwrap_or_default();
let line = LineIndex::new(text).line_col(site.instance.name_span.start).0;
format!("`{}` at {path}:{line}", site.instance.name)
}
}
impl Walk<'_> {
/// Record insertions into one file.
fn push(&mut self, file: usize, edits: Vec<TextEdit>) {
match self.out.edits.iter_mut().find(|(f, _)| *f == file) {
Some((_, existing)) => existing.extend(edits),
None => self.out.edits.push((file, edits)),
}
}
/// Append `element` to `site`'s connection list, and say so.
fn append(
&mut self,
file: usize,
text: &str,
site: &Site,
element: &str,
here: &str,
old: &str,
) -> Result<(), String> {
let Some(edits) = append(text, site.conns, element) else {
return Err(format!(
"lucisv cannot find where {here}'s connection list ends; it made no edits."
));
};
self.push(file, edits);
self.out.warnings.push(format!("{here} bound `{old}` through `.*`; added `{element}`."));
Ok(())
}
/// A module's ports, read once per walk.
fn ports_of(&mut self, scope: &Scope, module: &str) -> Ports {
self.ports.entry(module.to_string()).or_insert_with(|| scope.read_ports(module)).clone()
}
}
/// The rename's own edits and the implicit-connection insertions, as one
/// sorted edit list per file. Two insertions at one offset would be two
/// rewrites of one place, which no correct plan makes, so that is a refusal.
pub(super) fn combine(
mut renamed: Vec<(usize, Vec<TextEdit>)>,
inserted: Vec<(usize, Vec<TextEdit>)>,
) -> Result<Vec<(usize, Vec<TextEdit>)>, String> {
for (file, edits) in inserted {
match renamed.iter_mut().find(|(f, _)| *f == file) {
Some((_, existing)) => existing.extend(edits),
None => renamed.push((file, edits)),
}
}
renamed.sort_by_key(|(file, _)| *file);
for (_, edits) in &mut renamed {
edits.sort_by_key(|e| (e.range.start, e.range.end));
let clash = edits.windows(2).any(|pair| match pair {
[a, b] => b.range.start < a.range.end || (a.range.is_empty() && a.range == b.range),
_ => false,
});
if clash {
return Err("two rewrites of one connection overlap; the rename was abandoned.".into());
}
}
Ok(renamed)
}
/// The verified edits as the caller receives them: an insertion written right
/// where a replacement ends becomes part of it, so `.p` → `.q` plus `(p)` is
/// the one edit `.q(p)`. The applied text is the same either way.
pub(super) fn fuse(edits: Vec<TextEdit>) -> Vec<TextEdit> {
let mut out: Vec<TextEdit> = Vec::with_capacity(edits.len());
for edit in edits {
match out.last_mut() {
Some(last)
if edit.range.is_empty()
&& !last.range.is_empty()
&& last.range.end == edit.range.start =>
{
last.new_text.push_str(&edit.new_text)
}
_ => out.push(edit),
}
}
out
}
/// Refuse a list holding text a tolerant parse could not read, when that text
/// could be an implicit connection of either name.
fn unreadable_elements(site: &Site, old: &str, new: &str, here: &str) -> Result<(), String> {
let hides = |raw: &str| contains_word(raw, old) || contains_word(raw, new) || raw.contains('*');
match site.unreadable().any(hides) {
true => Err(format!(
"{here}'s connection list holds text lucisv could not parse, so it cannot tell whether it binds `{old}` implicitly; the rename was abandoned."
)),
false => Ok(()),
}
}
/// Refuse a `.*` list split by compiler directives: which ports it binds
/// depends on the configuration.
fn directives(site: &Site, here: &str) -> Result<(), String> {
match site.instance.conn_directives.is_empty() {
true => Ok(()),
false => Err(format!(
"{here}'s connection list is split by compiler directives, so which ports its `.*` binds depends on the configuration; lucisv does not preprocess, so the rename was abandoned."
)),
}
}
const UNREADABLE: &str = "unreadable";
const TWICE: &str = "twice";
const DIRECTIVES: &str = "directives";
fn wildcard_problem(here: &str, module: &str, old: &str, why: &str) -> String {
match why {
TWICE => format!(
"{here} connects with `.*` to `{module}`, which is declared in more than one indexed file, so lucisv cannot tell whether `{old}` is bound implicitly; the rename was abandoned."
),
DIRECTIVES => format!(
"{here} connects with `.*` to `{module}`, whose port list carries compiler directives, so whether `{old}` is bound implicitly depends on the configuration; the rename was abandoned."
),
_ => wildcard_unreadable(here, module, old),
}
}
fn wildcard_unreadable(here: &str, module: &str, old: &str) -> String {
format!(
"{here} connects with `.*` to `{module}`, which lucisv cannot read, so it cannot tell whether `{old}` is bound implicitly; the rename was abandoned."
)
}
fn bind_unreadable(here: &str, target: &str) -> String {
format!(
"{here} is bound into `{target}`, which lucisv cannot read, so it cannot tell what its `.*` binds; the rename was abandoned."
)
}
fn hierarchical_bind(here: &str, old: &str) -> String {
format!(
"{here} is bound into a hierarchical `bind` target, whose scope lucisv cannot name, so it cannot tell what `{old}` binds there implicitly; the rename was abandoned."
)
}
fn captured(here: &str, new: &str) -> String {
format!(
"{here} connects with `.*`, which would start binding `{new}` to the renamed declaration; the rename was abandoned."
)
}
fn cannot_rewrite(here: &str, old: &str, how: &str) -> String {
format!(
"{here} may bind `{old}` implicitly through `{how}`, from a scope lucisv cannot tie to the renamed declaration (a package import, or a `bind` target it cannot name); the rename was abandoned."
)
}
+184
View File
@@ -0,0 +1,184 @@
//! The text a rewritten implicit connection is spelled with, and where it is
//! written: a `(net)` after a `.name` shorthand, or a whole `.port(net)`
//! appended to a connection list that uses `.*`.
//!
//! Text-level, and only ever an **insertion** — nothing the source wrote is
//! replaced, so no comment can be lost and the verifier's piece check sees
//! exactly the tokens written here and nothing else move.
//!
//! The appending rule is `ports::list::append_to_list`'s, restated here
//! because that one is private to the port refactorings (see the feature
//! README's Handshakes): the list's own layout is kept — one element per line
//! stays one per line at the last element's indentation, an inline list stays
//! inline — and when the last element carries a `//` comment the comma goes
//! before the comment and the new element on the next line, because a `,`
//! written after `//` is a `,` inside a comment. The newline is the list's
//! own, so a CRLF file stays CRLF.
use vlog_parser::ast::{Connection, ListElem};
use vlog_parser::span::TextRange;
use crate::TextEdit;
/// `name`, followed by the blank an escaped identifier needs to end: an
/// escaped identifier runs to the next whitespace, so `\a-b(x)` would be one
/// token swallowing the parenthesis (IEEE 1800 §5.6.1).
fn spelled(name: &str) -> String {
match name.starts_with('\\') {
true => format!("{name} "),
false => name.to_string(),
}
}
/// `.port(net)`, as a connection lucisv writes it.
pub(super) fn connection(port: &str, net: &str) -> String {
format!(".{}({})", spelled(port), spelled(net))
}
/// The insertion that turns the shorthand `.written` into `.written(net)`,
/// where `written` is what the port name will spell once the rename's own
/// edits are applied (it decides whether a blank must separate the two).
pub(super) fn shorthand_tail(name_end: u32, written: &str, net: &str) -> TextEdit {
let gap = if written.starts_with('\\') { " " } else { "" };
insert(name_end, format!("{gap}({})", spelled(net)))
}
/// The insertions that append `element` after the last element of a
/// connection list, or `None` when the list has no element to append after.
pub(super) fn append(
text: &str,
conns: &[ListElem<Connection>],
element: &str,
) -> Option<Vec<TextEdit>> {
let spans: Vec<TextRange> = conns
.iter()
.map(|e| match e {
ListElem::Ok(c) => c.span,
ListElem::Error(raw) => raw.span,
})
.collect();
let last = *spans.last()?;
let first = *spans.first()?;
let gap_from = match spans.len() {
1 => text.get(..first.start as usize)?.rfind('(')? as u32,
n => spans.get(n - 2)?.end,
};
let gap = text.get(gap_from as usize..last.start as usize)?;
let newline = if gap.contains("\r\n") { "\r\n" } else { "\n" };
let indent = line_indent(text, last.start);
let (at, line_comment) = after_same_line_comments(text, last.end);
Some(match (line_comment, gap.contains('\n')) {
(true, _) => vec![
insert(last.end, ",".to_string()),
insert(at, format!("{newline}{indent}{element}")),
],
(false, true) => vec![insert(at, format!(",{newline}{indent}{element}"))],
(false, false) => vec![insert(at, format!(", {element}"))],
})
}
fn insert(at: u32, text: String) -> TextEdit {
TextEdit { range: TextRange::empty(at), new_text: text }
}
/// Where an append writes once the comments written after the last element
/// on its own line are stepped over, and whether the last of them is a `//`
/// comment (whose end is the line break, before a CRLF's `\r`).
fn after_same_line_comments(text: &str, end: u32) -> (u32, bool) {
let mut at = end as usize;
loop {
let Some(rest) = text.get(at..) else { return (at as u32, false) };
let blanks = rest.len() - rest.trim_start_matches([' ', '\t']).len();
let rest = &rest[blanks..];
if rest.starts_with("//") {
let line = rest.find('\n').unwrap_or(rest.len());
let line = match rest[..line].ends_with('\r') {
true => line - 1,
false => line,
};
return ((at + blanks + line) as u32, true);
}
if !rest.starts_with("/*") {
return (at as u32, false);
}
match rest.find("*/") {
Some(close) if !rest[..close].contains('\n') => at += blanks + close + 2,
_ => return (at as u32, false),
}
}
}
/// The blanks the line holding `offset` starts with, or nothing when
/// `offset` is not the first thing written on its line.
fn line_indent(text: &str, offset: u32) -> String {
let offset = offset as usize;
let start = text.get(..offset).map_or(0, |before| before.rfind('\n').map_or(0, |n| n + 1));
let Some(head) = text.get(start..offset) else { return String::new() };
match head.chars().all(|c| c == ' ' || c == '\t') {
true => head.to_string(),
false => String::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::ast::{Connections, ItemKind};
use vlog_parser::parse_source_tolerant;
/// The one instance in `module m; … endmodule`, appended to.
fn appended(body: &str, element: &str) -> String {
let text = format!("module m;\n{body}\nendmodule\n");
let (tree, _) = parse_source_tolerant(&text);
let Some(ItemKind::Module(module)) = tree.items.first().map(|i| &i.kind) else {
panic!("a module")
};
let conns = module
.items
.iter()
.find_map(|item| match &item.kind {
ItemKind::Instantiation(inst) => match &inst.instances[0].conns {
Connections::Named(conns) => Some(conns),
Connections::Ordered(_) => None,
},
_ => None,
})
.expect("a named list");
let edits = append(&text, conns, element).expect("an append");
crate::apply(&text, &edits)
}
#[test]
fn an_inline_list_stays_inline() {
assert!(appended(" c u (.*);", ".d(x)").contains(" c u (.*, .d(x));"));
assert!(appended(" c u (.a(b), .* /* all */);", ".d(x)")
.contains("(.a(b), .* /* all */, .d(x));"));
}
#[test]
fn a_list_one_per_line_gets_its_own_line_at_the_same_indent() {
let out = appended(" c u (\n .a(b),\n .*\n );", ".d(x)");
assert!(out.contains(" .*,\n .d(x)\n );"), "{out}");
let lone = appended(" c u (\n .*\n );", ".d(x)");
assert!(lone.contains(" .*,\n .d(x)\n );"), "{lone}");
}
#[test]
fn a_line_comment_after_the_last_element_keeps_the_comma_out_of_it() {
let out = appended(" c u (\n .* // everything\n );", ".d(x)");
assert!(out.contains(" .*, // everything\n .d(x)\n );"), "{out}");
}
#[test]
fn a_crlf_list_stays_crlf() {
let out = appended(" c u (\r\n .* // all\r\n );", ".d(x)");
assert!(out.contains(" .*, // all\r\n .d(x)\r\n );"), "{out:?}");
}
#[test]
fn an_escaped_name_is_terminated() {
assert_eq!(connection("\\a-b", "c"), ".\\a-b (c)");
assert_eq!(shorthand_tail(5, "\\q", "\\p").new_text, " (\\p )");
assert_eq!(shorthand_tail(5, "q", "p").new_text, "(p)");
}
}
+17 -5
View File
@@ -9,10 +9,16 @@
//! This file is the rename itself: the entry points, the new-name check, the
//! walk from a cursor to the declaration it means, the occurrences of that
//! declaration, and the refusal sentences. `crate::scope` is the in-scope
//! workspace every refactoring in this crate reads through, and `warnings` is
//! what a finished rename says about the occurrences it could not edit.
//! workspace every refactoring in this crate reads through, `warnings` is
//! what a finished rename says about the occurrences it could not edit, and
//! `connections` (with `sites` and `layout`) rewrites the `.name` and `.*`
//! connections that bind the renamed name implicitly.
mod connections;
use connections::{combine, fuse};
mod layout;
mod preflight;
pub(crate) mod sites;
#[cfg(test)]
mod tests;
mod warnings;
@@ -245,7 +251,12 @@ fn renaming(
if target.name == new_name {
return Err(already_named(new_name));
}
let edits = trace.edits.measure(|| scope.collect_edits(&target, new_name))?;
let edits = trace.edits.measure(|| {
let renamed = scope.collect_edits(&target, new_name)?;
let implicit = scope.implicit_connections(&target, new_name, &renamed)?;
Ok::<_, String>((combine(renamed, implicit.edits)?, implicit.warnings))
});
let (edits, rewrites) = edits?;
trace.edited = edits.len();
// Two disjoint fields of one trace: `verify` times the whole pass while
// `checks` is filled by its stages, so they are borrowed apart.
@@ -253,10 +264,11 @@ fn renaming(
verify.measure(|| check::verify(&mut scope, &edits, &target.name, new_name, checks))?;
let RenameTrace { warnings: stage, warning_scans, .. } = &mut *trace;
let warnings = stage.measure(|| scope.warnings(&target, &edits, warning_scans));
let mut warnings = stage.measure(|| scope.warnings(&target, &edits, warning_scans));
warnings.extend(rewrites);
let mut out: Vec<(PathBuf, Vec<TextEdit>)> = edits
.into_iter()
.filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), edits)))
.filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), fuse(edits))))
.collect();
out.sort_by(|a, b| a.0.cmp(&b.0));
Ok(RefactorEdit { edits: out, warnings, created: Vec::new() })
+253
View File
@@ -0,0 +1,253 @@
//! Where an implicit connection is written, and where its name binds.
//!
//! `.name` and `.*` (IEEE 1800 §23.3.2.3–4) connect a port to the same-named
//! declaration visible where the instance is written — or, for a `bind`, in
//! the target's scope (§23.11). The semantic layer records a reference for
//! the `.port` half of `.name` and nothing at all for the net half or for
//! `.*`, so nothing a reference walk sees says that renaming the net (or the
//! port) cuts the binding. This file is the AST walk both halves of the rename
//! read that from: the engine (`connections.rs`) to decide the rewrite, the
//! verifier (`check::implicit`) to print what every implicit binding names
//! before and after it.
use vlog_parser::ast::{
BindDirective, Connection, Connections, GenBlock, GenElse, Instance, Instantiation, Item,
ItemKind, ListElem,
};
use vlog_semantic::{Semantics, SymbolId, SymbolKind};
/// One instance with a **named** connection list, and the `bind` directive
/// it is written in, if it is one. A positional list has no implicit
/// connection, so it is not visited.
pub(crate) struct Site<'t> {
pub(crate) instantiation: &'t Instantiation,
pub(crate) instance: &'t Instance,
pub(crate) conns: &'t [ListElem<Connection>],
pub(crate) bind: Option<&'t BindDirective>,
}
impl<'t> Site<'t> {
/// The well-formed connections.
pub(crate) fn connections(&self) -> impl Iterator<Item = &'t Connection> {
self.conns.iter().filter_map(ListElem::ok)
}
/// True when the list writes `.*`.
pub(crate) fn has_wildcard(&self) -> bool {
self.connections().any(|c| c.name == "*")
}
/// The connection naming port `name` explicitly (`.name` or `.name(…)`).
pub(crate) fn named(&self, name: &str) -> Option<&'t Connection> {
self.connections().find(|c| c.name == name)
}
/// The raw text of every element a tolerant parse could not read.
pub(crate) fn unreadable(&self) -> impl Iterator<Item = &'t str> {
self.conns.iter().filter_map(|e| match e {
ListElem::Error(raw) => Some(raw.text.as_str()),
ListElem::Ok(_) => None,
})
}
/// The module a `bind` binds into, when the target is one plain name —
/// the only target whose scope lucisv can name without elaborating.
/// `Err(())` for a hierarchical or indexed target; `Ok(None)` for an
/// ordinary instantiation.
pub(crate) fn bind_target(&self) -> Result<Option<&'t str>, ()> {
match self.bind.map(|b| b.target.as_slice()) {
None => Ok(None),
Some([only]) if only.index.is_none() => Ok(Some(only.name.as_str())),
Some(_) => Err(()),
}
}
}
/// Every instance with a named connection list in `items`: modules,
/// packages, generate regions and blocks, and `bind` directives.
pub(crate) fn sites(items: &[Item]) -> Vec<Site<'_>> {
let mut out = Vec::new();
walk(items, &mut out);
out
}
fn walk<'t>(items: &'t [Item], out: &mut Vec<Site<'t>>) {
for item in items {
match &item.kind {
ItemKind::Instantiation(inst) => push(inst, None, out),
ItemKind::Bind(bind) => push(&bind.inst, Some(bind), out),
ItemKind::Module(module) => walk(&module.items, out),
ItemKind::Package { items, .. } => walk(items, out),
ItemKind::GenerateRegion { items, .. } => walk(items, out),
ItemKind::GenBlock(block) => walk(&block.items, out),
ItemKind::GenIf(gen) => {
walk_block(&gen.then, out);
let mut els = gen.els.as_deref();
while let Some(next) = els {
match next {
GenElse::If(_, gen) => {
walk_block(&gen.then, out);
els = gen.els.as_deref();
}
GenElse::Block(block) => {
walk_block(block, out);
els = None;
}
}
}
}
ItemKind::GenFor(gen) => walk_block(&gen.body, out),
ItemKind::GenCase(gen) => gen.items.iter().for_each(|arm| walk_block(&arm.body, out)),
_ => {}
}
}
}
fn walk_block<'t>(block: &'t GenBlock, out: &mut Vec<Site<'t>>) {
walk(&block.items, out);
}
fn push<'t>(inst: &'t Instantiation, bind: Option<&'t BindDirective>, out: &mut Vec<Site<'t>>) {
for instance in &inst.instances {
if let Connections::Named(conns) = &instance.conns {
out.push(Site { instantiation: inst, instance, conns, bind });
}
}
}
/// Whether `.name` or `.*` can bind a declaration of this kind: a net, a
/// variable, a port of the enclosing module (the reading `ports/expand.rs`
/// uses), and an instance — an interface instance is what a `.*` binds an
/// interface port to, and writing a module instance's connection out
/// explicitly is exactly as wrong as the implicit one was. Anything else (a
/// parameter, a type, a module) is never bound, whatever its name.
pub(crate) fn binds_implicitly(kind: SymbolKind) -> bool {
matches!(kind, SymbolKind::Net | SymbolKind::Var | SymbolKind::Port | SymbolKind::Instance)
}
/// The declaration a lookup of `name` finds from the innermost scope covering
/// `offset`, walking outwards — what `.name` and `.*` bind to at an instance
/// written there. The nearest declaration wins whatever its kind; the caller
/// judges the kind.
///
/// Local scopes only: a name a `.*` could only reach through a package import
/// is not seen (the README's Assumptions say what that costs).
pub(crate) fn nearest(semantics: &Semantics, offset: u32, name: &str) -> Option<SymbolId> {
let scopes = semantics.scopes();
let mut best: Option<usize> = None;
for (i, scope) in scopes.iter().enumerate() {
if !scope.span.contains(offset) {
continue;
}
let better = best.is_none_or(|b| {
scopes.get(b).is_some_and(|current| scope.span.len() <= current.span.len())
});
if better {
best = Some(i);
}
}
let mut at = best;
while let Some(i) = at {
let current = scopes.get(i)?;
if let Some(symbol) = current.lookup_local(name) {
return Some(symbol);
}
at = current.parent.map(|p| p.0 as usize);
}
None
}
/// Whether `text` could write an implicit connection naming one of `names`:
/// a `.` that starts a list element (see [`opens_an_element`]) followed —
/// past blanks and comments — by `*` or by one of the names as a whole word.
/// A cheap superset of the parse that answers it exactly, so the engine and
/// the verifier parse only the files that pass; a hierarchical `u_x.d` is
/// not a connection and does not pass.
pub(crate) fn may_connect_implicitly(text: &str, names: &[&str]) -> bool {
let bytes = text.as_bytes();
let mut from = 0usize;
while let Some(hit) = text.get(from..).and_then(|rest| rest.find('.')) {
let dot = from + hit;
from = dot + 1;
if !opens_an_element(text, dot) {
continue;
}
let after = skip_trivia(text, dot + 1);
let rest = text.get(after..).unwrap_or("");
if rest.starts_with('*') {
return true;
}
let names_it = |name: &&str| {
let end = after + name.len();
let whole = !bytes.get(end).is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
!name.is_empty() && rest.starts_with(*name) && whole
};
if names.iter().any(names_it) {
return true;
}
}
false
}
/// Whether the `.` at `dot` may begin an element of a connection list: the
/// last thing before it, past blanks and block comments, is `(`, `,` or the
/// `*)` of an attribute — or a line lucisv does not read backwards (one
/// holding a `//` comment, or a compiler directive), which is let through,
/// because a superset is what the prefilter promises.
fn opens_an_element(text: &str, dot: usize) -> bool {
let mut end = dot;
loop {
let Some(before) = text.get(..end) else { return true };
let trimmed = before.trim_end();
if trimmed.ends_with("*/") {
match trimmed.rfind("/*") {
Some(open) => end = open,
None => return true,
}
continue;
}
let line_start = trimmed.rfind('\n').map_or(0, |n| n + 1);
let line = &trimmed[line_start..];
let crossed_a_line = before.get(trimmed.len()..).is_some_and(|gap| gap.contains('\n'));
if crossed_a_line && (line.contains("//") || line.trim_start().starts_with('`')) {
return true;
}
return trimmed.ends_with('(') || trimmed.ends_with(',') || trimmed.ends_with("*)");
}
}
/// The offset of the first byte at or after `at` that is neither blank nor
/// inside a comment.
fn skip_trivia(text: &str, mut at: usize) -> usize {
loop {
let Some(rest) = text.get(at..) else { return at };
let trimmed = rest.trim_start();
at += rest.len() - trimmed.len();
if trimmed.starts_with("//") {
at += trimmed.find('\n').unwrap_or(trimmed.len());
} else if trimmed.starts_with("/*") {
at += trimmed.find("*/").map_or(trimmed.len(), |end| end + 2);
} else {
return at;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_prefilter_sees_a_wildcard_and_a_shorthand_past_comments() {
assert!(may_connect_implicitly("u (. /* c */ *);", &["d"]));
assert!(may_connect_implicitly("u (.clk, .d);", &["d"]));
assert!(may_connect_implicitly("u (.\n // why\n d);", &["d"]));
assert!(may_connect_implicitly("u (.a(b), /* c */ .d);", &["d"]));
assert!(may_connect_implicitly("u (.a(b), // c\n .d);", &["d"]));
assert!(may_connect_implicitly("u (\n`ifdef A\n .*\n`endif\n);", &["d"]));
assert!(may_connect_implicitly("u ((* keep *) .d);", &["d"]));
assert!(!may_connect_implicitly("u (.dd(x), .e(d));", &["d"]));
assert!(!may_connect_implicitly("assign a = b.c;", &["d"]));
assert!(!may_connect_implicitly("assign w = u_sub.d;", &["d"]));
}
}
@@ -0,0 +1,469 @@
//! QA attacks on the rename's implicit-connection rewrite (TODO-MCP M3.5):
//! `.name` and `.*` written out explicitly when a rename would cut them.
//!
//! Every test drives the public `rename` over a little in-memory workspace
//! and asserts the whole text of each file afterwards, or the refusal's
//! sentence — the harness of `tests/rename_implicit.rs`. The verifier-direct
//! attacks (crafted corrupted edits handed to `check::verify`) need the
//! crate-internal entry point and live in `src/check/qa_implicit.rs`.
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'_' || *b == b'\\' || *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();
let before_ok = !is_word(start.checked_sub(1).and_then(|i| bytes.get(i)));
if before_ok && (name.ends_with(' ') || !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
}
type Outcome = Result<(Vec<String>, Vec<String>), String>;
/// 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: &str) -> Outcome {
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)?;
let texts = files.iter().map(|(n, t)| apply(t, &edit, &path(n))).collect();
Ok((texts, edit.warnings))
}
/// The same, over already-renamed texts (for the round trip).
fn renamed_owned(
files: &[(&str, String)],
file: &str,
prefix: &str,
name: &str,
new: &str,
) -> Outcome {
let borrowed: Vec<(&str, &str)> = files.iter().map(|(n, t)| (*n, t.as_str())).collect();
renamed(&borrowed, file, prefix, name, new)
}
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";
// ----------------------------------------------------------------------
// port rename: list shapes
// ----------------------------------------------------------------------
#[test]
fn qa_port_rename_over_shorthand_wildcard_explicit_and_mixed_lists() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_a (.clk, .d, .q);\n leaf u_b (.*);\n leaf u_c (.clk(clk), .d(d), .q(q));\n leaf u_d (.clk, .*);\n leaf u_e (.d, .*);\nendmodule\n";
let files = [("leaf.sv", LEAF), ("top.sv", top)];
let (texts, warnings) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
let want = top
.replace("u_a (.clk, .d, .q)", "u_a (.clk, .din(d), .q)")
.replace("u_b (.*)", "u_b (.*, .din(d))")
.replace("u_c (.clk(clk), .d(d)", "u_c (.clk(clk), .din(d)")
.replace("u_d (.clk, .*)", "u_d (.clk, .*, .din(d))")
.replace("u_e (.d, .*)", "u_e (.din(d), .*)");
assert_eq!(texts[1], want);
// One sentence per rewrite: u_a and u_e shorthands, u_b and u_d wildcards.
assert_eq!(warnings.len(), 4, "{warnings:?}");
for (inst, how) in
[("u_a", "shorthand"), ("u_b", "`.*`"), ("u_d", "`.*`"), ("u_e", "shorthand")]
{
assert!(
warnings
.iter()
.any(|w| w.starts_with(&format!("`{inst}` at top.sv:")) && w.contains(how)),
"{inst}: {warnings:?}"
);
}
}
#[test]
fn qa_two_instances_in_one_instantiation_each_get_their_connection() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_a (.*), u_b (.clk, .d, .q());\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("u_a (.*)", "u_a (.*, .din(d))")
.replace("u_b (.clk, .d,", "u_b (.clk, .din(d),")
);
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("u_a (.*)", "u_a (.*, .d(x))")
.replace("u_b (.clk, .d,", "u_b (.clk, .d(x),")
);
}
#[test]
fn qa_an_instance_array_with_a_wildcard_is_written_out() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q [3:0]);\n leaf u[3:0] (.*);\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))"));
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))"));
}
#[test]
fn qa_a_non_ansi_port_is_written_out() {
let leaf = "module leaf (clk, d, q);\n input logic clk;\n input logic [7:0] d;\n output logic [7:0] q;\n always_ff @(posedge clk) q <= d;\nendmodule\n";
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_a (.*);\n leaf u_b (.clk, .d, .q);\nendmodule\n";
let files = [("leaf.sv", leaf), ("top.sv", top)];
let (texts, _) = renamed(&files, "leaf.sv", "(clk, ", "d", "din").expect("renames");
assert_eq!(
texts[1],
top.replace("u_a (.*)", "u_a (.*, .din(d))")
.replace("u_b (.clk, .d,", "u_b (.clk, .din(d),")
);
}
// ----------------------------------------------------------------------
// layout
// ----------------------------------------------------------------------
#[test]
fn qa_one_per_line_with_a_line_comment_on_the_last_element() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (\n .clk (clk), // clock\n .* // the rest\n );\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(" .* // the rest\n", " .*, // the rest\n .din(d)\n")
);
}
#[test]
fn qa_an_inline_list_with_a_trailing_line_comment() {
// An inline list whose `)` is on the next line: the comma goes before the
// comment, the connection on its own line (at column 0 — the `.*` is not
// first on its line, so there is no indentation to copy).
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.* // all\n );\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("(.* // all\n", "(.*, // all\n.din(d)\n"));
}
#[test]
fn qa_an_attribute_and_a_block_comment_on_the_last_element_survive() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf ((* keep *) .clk, (* dont_touch *) .* /* rest */);\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(".* /* rest */)", ".* /* rest */, .din(d))"));
}
#[test]
fn qa_an_escaped_net_is_written_out_with_its_terminating_blank() {
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_a (.*);\n leaf u_b (.clk, .\\d$x );\nendmodule\n";
let files = [("leaf.sv", leaf), ("top.sv", top)];
// The parent's escaped net renamed to a plain name.
let (texts, _) = renamed(&files, "top.sv", "logic ", "\\d$x ", "dd").expect("renames");
assert_eq!(
texts[1],
// The blank that ended the escaped name stays where it was.
top.replacen("logic \\d$x )", "logic dd )", 1)
.replace("u_a (.*)", "u_a (.*, .\\d$x (dd))")
.replace("u_b (.clk, .\\d$x )", "u_b (.clk, .\\d$x (dd) )")
);
}
// ----------------------------------------------------------------------
// hierarchy: nested wildcards, bind, interfaces, generate
// ----------------------------------------------------------------------
#[test]
fn qa_a_leaf_port_under_nested_wildcards_touches_only_the_direct_parent() {
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, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
assert_eq!(texts[1], mid.replace("(.*)", "(.*, .din(d))"));
assert_eq!(texts[2], top, "top's `.*` binds mid's `d`, which did not move");
assert_eq!(warnings.len(), 1, "{warnings:?}");
}
#[test]
fn qa_a_net_rename_reaches_a_bind_in_a_file_spelling_neither_name() {
// The whole-set caller: binds.sv spells neither `d` nor `x`, so neither
// the watched-file rule nor a name search finds it — only the bind walk.
let bind = "module binds;\n bind top leaf u_b (.*);\nendmodule\n";
let top =
"module top (input logic clk, input logic [7:0] d, output logic [7:0] 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[1], top.replace("[7:0] d", "[7:0] x"));
assert_eq!(texts[2], bind.replace("(.*)", "(.*, .d(x))"));
assert_eq!(
warnings,
vec!["`u_b` at binds.sv:2 bound `d` through `.*`; added `.d(x)`.".to_string()]
);
}
#[test]
fn qa_a_net_rename_behind_a_hierarchical_bind_is_refused() {
let bind = "module binds;\n bind top.u_x leaf u_b (.*);\nendmodule\n";
let top =
"module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\nendmodule\n";
let files = [("leaf.sv", LEAF), ("top.sv", top), ("binds.sv", bind)];
let refusal = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect_err("refused");
assert!(
refusal.contains("`u_b` at binds.sv:2 may bind `d` implicitly through `.*`"),
"{refusal}"
);
}
#[test]
fn qa_a_bind_with_an_instance_list_target() {
// `bind top : u_t leaf ...` binds into top's instances named `u_t`; its
// scope is still `top`'s.
let bind = "module binds;\n bind top : u_t leaf u_b (.*);\nendmodule\n";
let top =
"module top (input logic clk, input logic [7:0] d, output logic [7:0] 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("(.*)", "(.*, .d(x))"));
assert_eq!(warnings.len(), 1, "{warnings:?}");
}
#[test]
fn qa_an_interface_port_bound_by_wildcard_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, warnings) = renamed(&files, "sub.sv", "bus_if ", "bus", "b").expect("renames");
assert_eq!(texts[1], sub.replace("bus_if bus,", "bus_if b,"));
assert_eq!(texts[2], top.replace("(.*)", "(.*, .b(bus))"));
assert_eq!(warnings.len(), 1, "{warnings:?}");
}
#[test]
fn qa_a_generate_shadow_is_left_to_its_own_net() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n if (1) begin : g\n logic [7:0] d;\n leaf u_g (.*);\n leaf u_h (.clk, .d, .q());\n end\n leaf u_leaf (.*);\nendmodule\n";
let files = [("leaf.sv", LEAF), ("top.sv", top)];
// The module-level port: only the instance outside the block sees it.
let (texts, _) = renamed(&files, "top.sv", "[7:0] ", "d", "x").expect("renames");
assert_eq!(
texts[1],
top.replacen("[7:0] d", "[7:0] x", 1).replace("u_leaf (.*)", "u_leaf (.*, .d(x))")
);
// The block's own net: only the instances inside it.
let (texts, _) = renamed(&files, "top.sv", " logic [7:0] ", "d", "y").expect("renames");
assert_eq!(
texts[1],
top.replace(" logic [7:0] d;", " logic [7:0] y;")
.replace("u_g (.*)", "u_g (.*, .d(y))")
.replace("u_h (.clk, .d,", "u_h (.clk, .d(y),")
);
}
// ----------------------------------------------------------------------
// refusals
// ----------------------------------------------------------------------
#[test]
fn qa_a_port_rename_into_a_module_declared_twice_is_refused() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
let files = [("leaf.sv", LEAF), ("leaf_copy.sv", LEAF), ("top.sv", top)];
let refusal = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect_err("refused");
assert!(refusal.contains("u_leaf"), "{refusal}");
}
#[test]
fn qa_a_port_rename_over_an_ifdef_split_wildcard_list_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)], "leaf.sv", "[7:0] ", "d", "din")
.expect_err("refused");
assert!(refusal.contains("split by compiler directives"), "{refusal}");
}
#[test]
fn qa_a_port_rename_a_parent_wildcard_would_capture_is_refused() {
// top declares `din` but no `d`: `.*` bound nothing to `d`, and would
// start binding top's `din` to the renamed port.
let top = "module top (input logic clk, 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 refusal = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect_err("refused");
assert!(refusal.contains("would start binding `din`"), "{refusal}");
}
#[test]
fn qa_a_parameter_named_like_the_port_is_no_binding() {
// A parameter `d` in top shadows nothing a `.*` can bind: leave it alone.
let top = "module top #(parameter int d = 1) (input logic clk, output logic [7:0] q);\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);
assert!(warnings.is_empty(), "{warnings:?}");
}
// ----------------------------------------------------------------------
// round trip
// ----------------------------------------------------------------------
#[test]
fn qa_renaming_back_restores_everything_but_the_written_out_connections() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_a (.*);\n leaf u_b (.clk, .d, .q);\nendmodule\n";
let files = [("leaf.sv", LEAF), ("top.sv", top)];
let (once, _) = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect("renames");
let back: Vec<(&str, String)> = vec![("leaf.sv", once[0].clone()), ("top.sv", once[1].clone())];
let (twice, warnings) =
renamed_owned(&back, "leaf.sv", "[7:0] ", "din", "d").expect("renames back");
assert_eq!(twice[0], LEAF, "the declaring file is byte-identical");
// The connections stay explicit: `.*` gains `.d(d)`, `.d` became `.d(d)`.
assert_eq!(
twice[1],
top.replace("u_a (.*)", "u_a (.*, .d(d))").replace("u_b (.clk, .d,", "u_b (.clk, .d(d),")
);
assert!(warnings.is_empty(), "the explicit connections are plain references now: {warnings:?}");
}
#[test]
fn qa_a_shorthand_into_an_unreadable_module_is_still_written_out() {
// The shorthand's port half does not move, so the module need not be read.
let top =
"module top (input logic clk, input logic [7:0] d);\n ghost u_g (.clk, .d);\nendmodule\n";
let (texts, warnings) =
renamed(&[("top.sv", top)], "top.sv", "[7:0] ", "d", "x").expect("renames");
assert_eq!(texts[0], top.replace("[7:0] d", "[7:0] x").replace(".clk, .d)", ".clk, .d(x))"));
assert_eq!(warnings.len(), 1, "{warnings:?}");
}
// ----------------------------------------------------------------------
// QA findings
// ----------------------------------------------------------------------
/// QA finding 2: a `bind` whose target is a lone *instance* name (opentitan's
/// `prim/fpv/tb/prim_fifo_sync_bind_fpv.sv`: `bind i_nopass1
/// prim_fifo_sync_assert_fpv … (.clk_i, .rst_ni, .clr_i, … .err_o)`) refuses
/// the rename of every module-level declaration spelled like one of its
/// shorthands, in *any* module — renaming `prim_count`'s `err_o` or
/// `aes_core`'s `clk_i` is refused over a bind into a `prim_fifo_sync`. The
/// index knows `i_f` is an instance of `fifo`, not of `cnt`.
#[test]
fn qa_a_bind_into_an_instance_of_another_module_does_not_refuse() {
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_f (.clk_i, .err_o);\nendmodule\n";
let bind = "module tb_bind;\n bind i_f fifo_assert u_a (.clk_i, .err_o);\nendmodule\n";
let files =
[("cnt.sv", cnt), ("fifo.sv", fifo), ("check.sv", check), ("tb.sv", tb), ("bind.sv", bind)];
let (texts, _) = renamed(&files, "cnt.sv", "output logic ", "err_o", "error_o")
.expect("the bind targets an instance of `fifo`, which the rename does not touch");
assert_eq!(texts[4], bind);
}
// ----------------------------------------------------------------------
// M3.5 re-check (2026-09-23): the enclosing-module rule for a bind onto a
// bare instance name
// ----------------------------------------------------------------------
const CNT: &str =
"module cnt (input logic clk_i, output logic err_o);\n assign err_o = 1'b0;\nendmodule\n";
const FIFO: &str =
"module fifo (input logic clk_i, output logic err_o);\n assign err_o = 1'b0;\nendmodule\n";
const CHECK: &str = "module chk (input logic clk_i, input logic err_o);\nendmodule\n";
/// Rename `cnt`'s `err_o` over the three modules plus `extra`.
fn rename_cnt_err(extra: &[(&'static str, &'static str)]) -> Outcome {
let mut files = vec![("cnt.sv", CNT), ("fifo.sv", FIFO), ("chk.sv", CHECK)];
files.extend_from_slice(extra);
renamed(&files, "cnt.sv", "output logic ", "err_o", "error_o")
}
#[test]
fn qa_b_the_enclosing_modules_own_instance_wins_and_is_another_module() {
// A binds onto its own `u` (a fifo); B also has a `u`, a cnt. A's wins.
let a = "module a;\n logic clk_i, err_o;\n fifo u (.clk_i, .err_o);\n bind u chk c_u (.clk_i, .err_o);\nendmodule\n";
let b = "module b;\n logic clk_i, err_o;\n cnt u (.clk_i, .err_o);\nendmodule\n";
let (texts, _) = rename_cnt_err(&[("a.sv", a), ("b.sv", b)])
.expect("A's `u` is a fifo: the bind never sees cnt's err_o");
assert_eq!(texts[3], a, "a.sv untouched");
assert_eq!(texts[4], b.replace(".err_o)", ".error_o(err_o))"), "b's shorthand written out");
}
#[test]
fn qa_b_the_enclosing_modules_own_instance_wins_and_is_ours() {
// Swapped: A's own `u` is the cnt, B's is a fifo — refused, not guessed.
let a = "module a;\n logic clk_i, err_o;\n cnt u (.clk_i, .err_o);\n bind u chk c_u (.clk_i, .err_o);\nendmodule\n";
let b = "module b;\n logic clk_i, err_o;\n fifo u (.clk_i, .err_o);\nendmodule\n";
let refusal = rename_cnt_err(&[("a.sv", a), ("b.sv", b)]).expect_err("refused");
assert!(refusal.contains("`c_u` at a.sv:4"), "{refusal}");
}
#[test]
fn qa_b_a_file_scope_bind_onto_another_modules_instance_is_skipped() {
let tb = "module tb;\n logic clk_i, err_o;\n fifo u (.clk_i, .err_o);\nendmodule\n";
let bind = "bind u chk c_u (.clk_i, .err_o);\n";
let (texts, warnings) =
rename_cnt_err(&[("tb.sv", tb), ("bind.sv", bind)]).expect("only a fifo is named `u`");
assert_eq!((texts[3].as_str(), texts[4].as_str()), (tb, bind));
assert!(warnings.is_empty(), "{warnings:?}");
}
#[test]
fn qa_b_a_file_scope_bind_onto_our_instance_is_refused() {
let tb = "module tb;\n logic clk_i, err_o;\n cnt u (.clk_i, .err_o);\nendmodule\n";
let bind = "bind u chk c_u (.clk_i, .err_o);\n";
let refusal = rename_cnt_err(&[("tb.sv", tb), ("bind.sv", bind)]).expect_err("refused");
assert!(refusal.contains("`c_u` at bind.sv:1"), "{refusal}");
}
#[test]
fn qa_b_a_bind_onto_a_name_no_indexed_instance_has_is_refused() {
let bind = "module tb_bind;\n bind u_ghost chk c_u (.clk_i, .err_o);\nendmodule\n";
let refusal = rename_cnt_err(&[("bind.sv", bind)]).expect_err("refused");
assert!(refusal.contains("`c_u` at bind.sv:2"), "{refusal}");
}
/// QA note 1 (non-blocking, lead-accepted gap): an instance inside a generate
/// block of the enclosing module is counted as the enclosing module's own.
/// Upward resolution from `a` does not see `a.g.u`, so `bind u` here reaches
/// the parent's `u` — a `cnt` — and its `.err_o` binds `cnt`'s renamed port.
/// The engine skips it; the verifier prints a bind onto an instance as
/// opaque on both sides, so nothing refuses and the shorthand is cut.
#[test]
#[ignore = "QA note 1: accepted generate-block gap"]
fn qa_b_a_generate_scoped_instance_is_not_the_enclosing_modules_own() {
let a = "module a;\n logic clk_i, err_o;\n if (1) begin : g\n fifo u (.clk_i, .err_o);\n end\n bind u chk c_u (.clk_i, .err_o);\nendmodule\n";
let p = "module p;\n logic clk_i, err_o;\n a u_a ();\n cnt u (.clk_i, .err_o);\nendmodule\n";
let outcome = rename_cnt_err(&[("a.sv", a), ("p.sv", p)]);
let refusal = outcome.expect_err("the bind may reach p.u, a cnt");
assert!(refusal.contains("`c_u`"), "{refusal}");
}
@@ -0,0 +1,376 @@
//! 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}");
}
+1 -1
View File
@@ -58,7 +58,7 @@ VS Code setting that restarts the server.
| `textDocument/foldingRange` | `pairs::analyze` + comment trivia | One `Region` per matched scope pair, folded through the line *before* the closer so `end`/`endmodule` stays visible, plus one `Comment` per multi-line block comment. An unmatched opener folds nothing. Same feature README |
| `textDocument/documentSymbol` | `Semantics::document_symbols` | Hierarchical |
| `textDocument/prepareRename` | `vlog_refactor::prepare_rename` | Declines with the engine's own sentence (`RequestFailed`), so the box never opens on a rename that would fail |
| `textDocument/rename` | `vlog_refactor::rename` | Cross-file `WorkspaceEdit` (`changes`); warnings go out on `window/logMessage`; refusals are `RequestFailed`. See `docs/features/refactor-rename/README.md` |
| `textDocument/rename` | `vlog_refactor::rename` | Cross-file `WorkspaceEdit` (`changes`); warnings go out on `window/logMessage`; refusals are `RequestFailed`. See `docs/features/refactor-rename/README.md`. Since 2026-09-23 the fan-out also hands over, one hop down, every module a handed-over file instantiates (`module_select::instantiated_by`), so a `.*` into a module declaring neither name is read rather than refused |
| `textDocument/completion` | `vlog_refactor::instantiation_plan` | Module hinting: one item per indexed module, inserting the whole instantiation skeleton as a snippet (plain text for a client that did not advertise `snippetSupport`). Capped at 64 items, `isIncomplete` when truncated; declines every position that is not module-item. See `docs/features/refactor-instantiate/README.md` |
| `textDocument/signatureHelp` | `vlog_refactor::instantiation_plan` | The instantiated module's ports (or, inside `#( ... )`, its parameters) with the active one highlighted — by name for a named list, by position for an ordered one. Triggers: `(` and `,`. Same feature README |
| `textDocument/inlayHint` | `vlog_refactor::instantiation_plan` | Ghost port names on an **ordered** connection list (`u1 (clk, rst_n)`) and parameter names on ordered `#( ... )` overrides, read from the instantiated module's declaration. Range-scoped; named lists, `.*`, omitted positions, connections past the last port, gate primitives and modules the index cannot resolve get nothing at all — a hint is decoration and never guesses. No `resolveProvider`. See `docs/features/inlay-hints/README.md` |
+740 -1
View File
@@ -138,7 +138,17 @@ sites, `.port(...)` connection names, and `#(.PARAM(...))` overrides.
identifier tokens spell the new name — same count, same kinds, same texts,
same attached comments, same spans after shifting.
Rules 12 and 13 are checked over the *whole* edit; either one fails the entire
14. **Implicit connections lucisv cannot read** (added 2026-09-23, see
"Implicit connections"): a `.*` or `.name` that binds — or could bind —
the renamed name through a module lucisv cannot read or finds declared
twice, a connection list split by compiler directives or holding text a
tolerant parse could not read, a hierarchical `bind` target, a `.*` that
would start binding the new name, and a package variable an import might
hand to a `.*`.
15. **Binding verification** (2026-09-23): what any `.name` or `.*` in a
watched file binds — port half and net half — differs before and after.
Rules 12, 13 and 15 are checked over the *whole* edit; any one fails the entire
rename, never part of it (`RefactorEdit` is all-or-nothing, hard invariant 1's
shape for refactorings).
@@ -543,6 +553,138 @@ implemented:
- `a label lucisv records no declaration for`, and
`an occurrence lucisv cannot attribute to any declaration` for the rest.
## Implicit connections (2026-09-23)
**The defect this closes** (TODO-MCP M3.5, M3 QA finding 1, reproduced with
`vlog_refactor::rename` directly). `.name` and `.*` (IEEE 1800 §23.3.2.3–4)
bind a port to the *same-named* declaration where the instance is written.
The semantic layer records a reference for the port half of `.name` and
nothing at all for its net half or for `.*` — so renaming a port `d` → `din`
of `leaf` left `leaf u_leaf (.*)` binding nothing and turned `.d` into `.din`
against a parent with no net `din`, and renaming the parent's net cut both
bindings. Every one verified clean: the token check saw one identifier change,
and the resolution print saw no reference move, because none was ever
recorded. A silent CLAUDE.md invariant-1 corruption in a shipped engine; the
LSP's rename shared it.
**What a rename does now** (`rename/connections.rs`):
| Renamed | Written at an instance | Becomes |
|---|---|---|
| port `p` → `q` of `M` | `M u (.p)` | `M u (.q(p))` — one edit, `p` → `q(p)` |
| port `p` → `q` of `M` | `M u (.*)` and a net, variable, port or instance named `p` visible | `M u (.*, .q(p))` |
| port `p` → `q` of `M` | `M u (.*)`, nothing named `p` or `q` visible | unchanged — the wildcard bound nothing and still binds nothing |
| net/var/port/instance `n` → `m` | `C u (.n)` where `n` is the renamed one | `C u (.n(m))` |
| net/var/port/instance `n` → `m` | `C u (.*)`, `C` declares port `n` | `C u (.*, .n(m))` |
| either | `.*` beside an explicit `.p(...)` / `.n(...)` | nothing added — the explicit one wins, and the rename's own edit handles it |
Every such rewrite is listed in `RefactorEdit.warnings` — "`u_leaf` at
top.sv:2 bound `d` through `.*`; added `.din(d)`." and "`u_leaf` at top2.sv:2
connected `d` by the shorthand `.d`; wrote `.din(d)` so it still binds the
same net." — so both the LSP and the MCP show it. A port of a module that is
itself instantiated gets both directions at once: renaming `mid`'s port `d`
adds `.din(d)` to `top`'s `mid u_mid (.*)` and `.d(din)` to `mid`'s own
`leaf u_leaf (.*)`.
**Where an implicit connection binds** (`rename/sites.rs`): an ordinary
instance, at the nearest declaration of the name walking outward from the
scope the instance is written in (generate blocks included); a `bind` whose
target is one plain module name, at that module's own top-level
declaration (`WorkspaceIndex::member_in(.., Surface::Hierarchical)`, the
table the semantic layer resolves a bind connection's bare name through).
Which instances are walked: for a port, every instance of its module in the
in-scope files that spell the module's name; for a net, every instance in its
own file from whose position the name resolves to it, plus every `bind` into
its module when it is declared at the module's top level; for a package
variable, every instance in a file that names the package — refused, not
rewritten (lucisv does not follow an import into a `.*`).
**Layout.** An insertion only — nothing the source wrote is replaced, so no
comment can move. A `.*` addition goes after the last connection element,
before the `)`, in the list's own style: `, .q(p)` on the same line for an
inline list; its own line at the last element's indentation for a list
written one per line; when the last element carries a `//` comment, the comma
goes before the comment and the connection on the next line (a `,` after `//`
is inside the comment). The newline is the list's own, so a CRLF file stays
CRLF. An escaped identifier gets the blank that terminates it. Nothing adds a
trailing comma.
**Refused, never guessed** — each sentence names the instance and its line:
- a `.*` whose module lucisv cannot read ("`u_x` at top.sv:4 connects with
`.*` to `ghost`, which lucisv cannot read, so it cannot tell whether `d` is
bound implicitly; the rename was abandoned."), or finds declared in more
than one indexed file, or whose port list carries compiler directives;
- a connection list split by compiler directives (when it holds `.*`), or
holding text a tolerant parse could not read that spells either name or a
`*`;
- a `bind` whose target is a hierarchical path, or a lone **instance** name
that may be an instance of the renamed module: resolved upward from the
bind's own scope first (the enclosing module's instances of that name),
else through every indexed instance of that name; refused when one of them
is the renamed module's or none is indexed, skipped when all are other
modules' (rework, QA finding 2);
- a `.*` whose module declares a port spelled like the **new** name, not
connected explicitly — the rename would make the wildcard start binding it;
- a package variable a `.*` or `.name` might reach through an import.
**How the verifier accounts for it** (`check/implicit.rs`; `check/` had to
learn the shape, because the whole point is that its reference print could
not see it). Two additions, both inside the existing `verify`:
1. **A file whose edits insert is held to the splice contract plus a shape
rule.** The token-identity check allows no insertion at all, so such a file
is checked by the port refactorings' piece comparison (`ledger::Split`,
`pieces_match`: every piece in place, no comment or attribute dropped or
duplicated) plus: every replacement is exactly one identifier token
spelling the old name, replaced by the new name; every insertion lexes to
`(X)`, `,`, `.X(Y)` or `, .X(Y)` with `X`, `Y` the old or the new name and
no comment, **at a place a connection list takes it** (rework, QA finding
1): `(X)` only right after a shorthand connection's name, `,` only right
after the last element of a named list holding `.*`, `, .X(Y)` between
that element — past blanks and comments — and the list's `)`, and a bare
`.X(Y)` only there behind such a `,`; the places are read off the
before-tree with the same `sites` walk the engine plans with. Anything
else: "the rename would write `…` outside a connection list in <file>; no
edits were made." And the file gains no parse diagnostic. The resolution print
excludes the inserted ranges (their names are the next check's to account
for).
2. **The binding print.** For every watched file that could write an
implicit connection of either name (a cheap text prefilter,
`sites::may_connect_implicitly`, which is a superset — a `.` that starts a
list element followed by `*` or one of the names — and every file the edits
insert into), every instance's bindings are printed before and after:
`(instance, what the port half names, what the net half names)`, for every
named connection whose port or bare-name net spells one of the two names,
and every port spelling one of them that a `.*` reaches. The net half of
`.name`/`.*` is looked up the way the language looks it up (above); a `.*`
into a module that cannot be read prints a *probe* of what each of the two
names finds there. Before-side spans are shifted through the edit map. The
two prints must be equal. Why only the two names: a rename adds and
removes declarations of those two names alone, so no other lookup and no
other port can move — the watched-file argument applied one level down.
The attack pairs (`check::implicit::tests`, CLAUDE.md invariant 4 — the
binding print is a new *strictness*, not a forgiveness, but the insertions it
admits are a widening of what a rename may write, so they ship with attacks):
the QA finding itself (`.d` → `.din`, `.*` untouched) and the wildcard alone;
a shorthand written out with the wrong net (`(din)` — spells only the two
names, so only the binding print sees it); a wildcard connection to a third
name and to the swapped halves (`.d(din)`); insertions that are not connection
text (a comment, `; wire din;`, a doubled connection, an unclosed one); a
connection added beside an explicit one of the same port; an insertion into
the wrong instance; a net rename that leaves `.*` alone, and one with swapped
halves; a `.*` that starts binding the new name; a net rename behind an
unreadable `.*`. Sabotage-checked: with the binding print disabled, seven of
the eleven fail (the rest are caught by the shape rule or the piece ledger
as well).
**What it costs.** A rename with no implicit connection of the name anywhere
parses nothing extra: the engine and the verifier both parse only files that
pass the prefilter (`the rename parses each input file once and each edited
file once more` still holds verbatim). A file that does pass costs the engine
one parse and the verifier one per side.
## Assumptions
- The caller hands over the same file set the workspace index was built from,
@@ -573,6 +715,23 @@ implemented:
- Refactored output is *edited source*, not reformatted source (umbrella
Handshakes): the edits are minimal, and the user runs the formatter
separately.
- **Implicit connections (2026-09-23).** `.*` and `.name` bind a port to a
net, a variable, a port or an instance of the same name
(`sites::binds_implicitly`: `ports/expand.rs`'s reading plus the instance,
because an interface port binds to an interface instance and writing a
module instance's connection out is exactly as wrong as the implicit one);
the nearest declaration of the name shadows, so a parameter or a type of
that name is a binding to nothing. The lookup is lexical and local — the nearest declaration
walking outward from the instance — so a name a `.*` could reach only
through a package import is not seen: a rename of a *package* variable is
refused wherever a file naming the package writes a candidate implicit
connection, and a rename that would make an import-reached name newly
visible to a `.*` is caught only when the local lookup moves. A `bind` into
a module the fan-out does not hold is outside the rename exactly as any
other use in such a file is (the staleness premise); a `bind` whose target
is a hierarchical path is refused whenever it writes a candidate implicit
connection of the name, since lucisv cannot name its scope. The
compilation unit (`$unit`) is treated as one file.
## Handshakes
@@ -678,6 +837,49 @@ the only alternative — matching the label textually — would have broken this
feature's one structural rule, that every edit comes from a resolved
reference.
**Requested 2026-09-23 (implicit connections), not blocking — each has a
workaround in this crate:**
- **`vlog_refactor::ports` (`ports/list.rs`, `ports/find.rs`).**
`append_to_list`, `after_same_line_comments`, `line_indent`,
`walk_instantiations` and `declared_ports` are `pub(super)` to the port
refactorings; the rename needed the same five, and M3.5 did not own the
files. Workaround: `rename/layout.rs` and `rename/sites.rs` restate them
(with two differences the rename needed: a CRLF-aware line break, and the
`bind` directive handed to the visitor rather than a bool). Request: lift
them to `pub(crate)` and let the rename call them, so there is one list
layout rule.
- **`vlog_semantic`.** Recording an implicit connection's net half as a
reference (`.name` → a use of the net; `.*` → one use per port the module
declares, when it can be read) would let `collect_occurrences`, find-all-
references and the resolution print see these bindings directly, and would
retire most of `rename/sites.rs`. Workaround: the AST walk here, which
both the engine and the verifier read.
- ~~**`lucisv_server` (`state/mod.rs::rename_sources_traced`) — the one that
matters for the LSP.**~~ **Delivered 2026-09-23 inside M3.5 (lead ruling):
see the work log's fan-out entry.** The original request, kept as filed: The rename's fan-out holds every file declaring
either name, so a module `C` a `.*` instantiates is in it exactly when `C`
declares a port spelled like one of them — which is the case that needs a
rewrite. When it does not, `C`'s file is not handed over, and the engine,
which cannot tell "not in this subset" from "not in the workspace", reports
`C` as a module it cannot read and **refuses**. Safe, and the whole-scope
callers (the MCP, the CLI, the tests) never see it; but an LSP rename of a
net in a module whose instances use `.*` into modules that do not declare
the name is refused where it could succeed. Request: a seventh rung — for
every file in the set that writes `.*`, add the declaring file of each
module instantiated there (`WorkspaceIndex::units` of the instantiation
edges the index already records). No engine change is needed for it.
- **`vlog_parser` (filed 2026-09-23, QA M3.5 finding 3 and round one's
`{d,, d}`).** The tolerant parser accepts a trailing `,` in a named
connection list (`other u_o (.*,)`) and an empty concatenation element
(`{d,, d}`) without a diagnostic, so the verifiers' "no new parse
diagnostic" rule cannot see either. The rename's position check refuses
both on its own (a lone comma is not a place a connection list takes);
the request is that the parser report them, so every refactoring's
splice contract gets the same net for free. Not this lane's to fix.
**Requested of nobody else.** Hierarchical tails and `defparam` paths remain
unresolved by design (`vlog_semantic` non-goal: "resolving a tail needs
instance elaboration"), so they stay warned-not-edited; making them edits is
@@ -718,6 +920,11 @@ a much larger change than an end label and is not part of M2.
the new name, which closes the one refusal the first draft lost. The
old name's exemption is argued under "The dangling-use case" and pinned
by its own test
- [x] Implicit connections (2026-09-23, TODO-MCP M3.5): `.name` and `.*`
rewritten explicitly in both directions (port and net), every rewrite
warned about, the unreadable cases refused, and the verifier taught the
shape (insertions under the splice contract + a shape rule; the binding
print) with eleven attack pairs
- [ ] Deferred: rename in comments and strings (rope's `docs=True`) — the
umbrella lists it as an option, off by default, "until asked for"
- [ ] Deferred: renaming a module together with its file
@@ -1031,6 +1238,137 @@ Gates after the rework: `cargo fmt --all -- --check` clean,
`cargo clippy --all-targets` clean workspace-wide, `cargo test --workspace`
green, `node editors/vscode/smoke.js` OK against the release binary.
**2026-09-23 — dev agent (M3.5, implicit connections).** The engine rewrote
nothing it could not see a reference for, and `.name`/`.*` bindings have no
reference — see "Implicit connections" for the contract, the refusals and the
verifier's new half. Key decisions:
- **AST walk, not semantic references.** The semantic layer records the port
half of `.name` (so a port rename already edited `.d` → `.din`) and nothing
of the net half or of `.*` (`bind/item.rs::bind_connection` skips `*` and
binds `expr: None` to nothing). `vlog_semantic` is not this lane's to
change, so the bindings are re-derived from the parse — one walk
(`rename/sites.rs`) that the engine and the verifier both read, so the two
cannot disagree about where an implicit connection is or where its name
binds. Filed as a Handshake request.
- **Insertions only.** The shorthand's port half is already the rename's
edit; the net half is an insertion right after it, fused into one
`TextEdit` (`p` → `q(p)`) only after verification, so the verifier sees a
pure rename edit plus a pure insertion. A `.*` gets an appended element, so
nothing the source wrote is replaced and no comment can move.
- **`check/` learned the shape rather than being bypassed.** A file with
insertions is checked by the splice contract the port refactorings already
use plus a four-template shape rule; the binding print is a new check, and
it is strictly *more* than the rename had (every file it prints was
already compared by the reference print). Sabotage-verified.
- **Prefilter.** `sites::may_connect_implicitly` keeps the engine and the
verifier from parsing files that cannot hold an implicit connection of
either name; the parse-budget tests (`K + E`) are unchanged and pass.
- **OpenTitan, read-only, on a scratch copy of `hw/ip/prim` + `hw/ip/aes`
(393 files, release, whole-scope).** `prim_fifo_sync`'s port `clr_i` →
`clr_q` is **refused**: `prim_fifo_sync_bind_fpv.sv` writes
`bind i_nopass1 prim_fifo_sync_assert_fpv … (.clk_i, .rst_ni, .clr_i, …)`,
a `bind` into an *instance* named `i_nopass1` — which is a
`prim_fifo_sync` in `prim_fifo_sync_tb`, so the old engine would have cut
those twelve bindings silently. With that one file left out of scope the
same rename succeeds (115 ms, 3 files, 16 edits): eleven `.clr_i` →
`.clr_q(clr_i)` in `prim_fifo_sync_tb.sv`, and `prim_fifo_sync`'s own
`u_fifo_cnt (.clr_i, …)` → `.clr_i(clr_q)` — both directions in one
rename. Renaming the testbench's own port `clr_i` → `clr_tb` writes
`(clr_tb)` after the eleven shorthands. A `.*` user: renaming
`fi_control_fsm_wrapper`'s port `aes_ctrl_cs` → `ctrl_cs` adds
`, .ctrl_cs(aes_ctrl_cs)` to `bind aes_control_fsm … u_fi_ctrl_fsm (.*)`
(the bind's target declares `aes_ctrl_cs`) and `, .aes_ctrl_cs(ctrl_cs)` to
the wrapper's own `fi_control_if fi_if (.*)`; renaming `aes_control_fsm`'s
variable `aes_ctrl_cs` → `ctrl_state_q` adds `.aes_ctrl_cs(ctrl_state_q)`
to the same bind. Each rename ~110 ms.
- **The server's fan-out step (2026-09-23, lead ruling on Handshake 1).**
`Workspace::rename_sources_traced` now adds, after the open buffers, the
declaring file of every module instantiated in a handed-over file — one hop
down the index's `instantiations()` edges, `bind` included
(`module_select::instantiated_by`, a walk over records; nothing is read).
So a `.*` into a module that declares neither name is handed over and read
as binding nothing, instead of refused as unreadable; a `.*` into a module
the workspace does not hold is still refused. The added files count in
`selected` and in the indirect census (as `instantiation`) but not in the
per-rung counts: `SelectionTrace`'s counter is private to `rename_trace.rs`,
which this lane does not own. Pinned by two wire tests
(`server/tests/rename_implicit.rs`: an open-buffer net rename beside
`quiet u_quiet (.*)` and `leaf u_leaf (.*)` succeeds with `, .d(x)` and no
edit to `u_quiet`; the same with `quiet` absent is refused naming `u_quiet`)
and one unit test of the helper. The engine is unchanged by it.
- **Deviation from the brief:** the MCP tool description's known-limit
sentence was replaced by one saying what happens now (the connection is
written out and listed in `warnings`), rather than only deleted.
**2026-09-23 — dev agent (M3.5 rework after QA's FAIL).**
- **Finding 1 — insertions checked for their text, never their place.**
`check/implicit.rs::insertions_match` now also asks `Slots::takes`: each
insertion's offset must be a place the before-tree's `sites` walk (the
engine's own) says a connection list takes that template — see "How the
verifier accounts for it", item 1. QA's three tests
(`check/qa_implicit.rs`, registration kept in `check/mod.rs`) are
un-ignored and pass unchanged; two attacks of my own pin that the check
keys on the file's sites, not on a byte: `(d)` at an offset that is a
shorthand's end in `top2.sv` is refused in a file where the same offset
ends a positional element, and in one file `(d)`/`,` after the positional
`d` of a second instance is refused beside the honest shorthand rewrite of
the first. Sabotage-checked: with the position check off, those two and
QA's three fail.
- **Finding 2 — a `bind` into a bare instance name refused unrelated
renames.** `connections.rs::bind_reaches` classifies each bind (module /
maybe / elsewhere); `instance_owners` resolves a lone instance name
through `WorkspaceIndex::instantiations()` — the enclosing module's own
instances of that name first (upward resolution, IEEE 1800 §23.11, which
is what opentitan's `bind dut … (.*)` in `sram_ctrl`'s and `entropy_src`'s
`tb.sv` means), every indexed instance of that name otherwise. All owned by
other modules → skipped; one is the renamed module's, or none is indexed →
refused as before. QA's test un-ignored and passing; two of mine: an
instance name owned by both `fifo` and `cnt` refuses a `cnt` rename (and
is skipped with `cnt`'s bench removed), and a bind written beside its own
`fifo dut` is `fifo`'s even though another bench has a `cnt dut`. **One
step past the ruling**, stated: the enclosing-module preference. Without
it `entropy_src`'s `clk_i` stays refused over `sram_ctrl`'s `bind dut`,
since opentitan has eight modules named `dut`; with it that rename
succeeds, and the refusal still fires wherever the bind's own module
declares an instance of the renamed module. **Known gap (QA note 1,
accepted):** a `bind` onto an instance that exists only inside a generate
block of the enclosing module is treated as that instance's module's and,
when that is another module, skipped silently — upward resolution would not
see into the generate block and would look further up.
- **Size.** `check::verify` 94 → 79 lines: step 1 (token check) is now
`tokens_verified`, the per-file inserted ranges `implicit::inserted_in`,
step 3's call a two-liner. Pure moves; no behaviour change, and the same
tests pass.
- **Rework 2 (QA re-check, finding 3).** `Slots::takes` admitted a lone
`,` at the end of any `.*` list; `other u_o (.*)` → `(.*,)` verified clean
where the list binds neither name, since the tolerant parser reports no
error. The comma is now accepted only when the same file's edits also
insert a bare `.X(Y)` into the same list — the comma-before-`//` pair as a
pair, mirroring the requirement the bare connection already had. QA's
`qa_r_a_lone_trailing_comma_on_a_wildcard_binding_neither_name` is
un-ignored; `a_comma_and_its_connection_in_different_lists_are_refused`
(mine) crosses two lists' halves and is refused. The parser gap is filed
in Handshakes.
- **OpenTitan re-run** (scratch copy grown to 489 files: `prim`, `aes`,
`entropy_src`, `sram_ctrl`; release, whole-set engine): `prim_count.err_o`
→ `error_o` OK (14 files, 17 edits; two shorthands written out);
`prim_count.clr_i` OK; `aes_core.clk_i` OK (3 files, 24 edits);
`entropy_src.clk_i` OK (5 files, 10 edits, among them the
`entropy_src_cov_bind.sv` `.*` gaining `.clk_i(clock_i)`);
`prim_packer_fifo.wready_o` OK; `prim_fifo_sync.clr_i` still **refused**
over `bind i_nopass1 …` (those instances are `prim_fifo_sync`s); the two
`aes_ctrl_cs` renames unchanged.
**2026-09-23 (lead, after the final re-check).** QA finding 4 fixed by the
lead: `check/implicit.rs::Slots::of` registers no slot for a list holding
an error element (the engine already refuses such lists); QA's test
un-ignored, and QA's own pin of the old behaviour in
`qa_p_a_pair_after_an_error_element` flipped to the stricter rule. Gates
through `tools/guard.sh`: fmt, clippy, vlog_refactor 616 passed, workspace
4 761 passed.
## QA log
**2026-08-24 — QA agent.**
@@ -1750,6 +2088,384 @@ OpenTitan with no measurable end-to-end regression. No new findings. The
macro-invocation warning residue is unchanged and remains the lead's
already-accepted, separately-tracked call.
**2026-09-23 — QA agent, M3.5 QA (implicit connections: `.name` / `.*`).**
Charter: TODO-MCP §M3.5 — attack the widened rename verifier first
(CLAUDE.md invariant 4), then the rewrite, LSP parity, opentitan copies,
sizes, gates. Worked on the uncommitted master checkout; every experiment in a
scratch copy of the repo and of opentitan `hw/ip/{prim,aes,entropy_src}`.
### Verdict: FAIL — one BLOCKING finding (verifier), one BLOCKING false refusal
### Finding 1 (BLOCKING) — an insertion is checked for its text, never its place
`check/implicit.rs::insertions_match` holds every inserted string to the four
templates (`(X)`, `,`, `.X(Y)`, `, .X(Y)`, X/Y the two names) but never asks
*where* it was inserted; the resolution print then skips every inserted range
(`inserted_after`) and the binding print only reads named connection lists'
connections. So a template placed anywhere else that still parses is seen by
nothing. Driven through the crate-internal `check::verify` (the dev exposed no
public hook) with the honest edits of a `d` → `din` port rename plus one extra
insertion — **each of these verifies `Ok(())`**:
- `,` into a positional list: `leaf u_p (clk,, d, q)` — every later port
shifts by one (silent rewiring);
- `, .din(d)` into a parameter override `#(.W(8), .din(d))`;
- `(d)` after a net in an expression `f(d, d(d))`; `(d)` after a task call
`initial t(d)`; `,` / `, .din(d)` into call arguments;
- `,` into a concatenation `{d,, d}` (the tolerant parser reports no
diagnostic for the empty element, so the "no new parse error" guard is
silent too);
- inside a named list, inside an explicit connection's expression:
`.clk(clk(d))`, `.q({q(d), q})`, `.q({q,, q})` (`net_half` prints nothing for
a non-name expression of a port spelling neither name).
The engine never writes these today, which is why nothing corrupted in the
engine-level tests — but the verifier is the safety net that is supposed to
refuse exactly this, and the history note in invariant 4 is this shape.
Tests: `crates/vlog_refactor/src/check/qa_implicit.rs` —
`qa_a_comma_inserted_into_a_positional_list_is_refused`,
`qa_connection_text_outside_a_connection_list_is_refused`,
`qa_connection_text_inside_an_explicit_connection_is_refused`, all
`#[ignore = "QA finding 1"]` (registered with one `#[cfg(test)] mod
qa_implicit;` line in `check/mod.rs`, outside my file list — needed because
`verify` is crate-internal; the lead may move it into `implicit.rs`'s tests).
**Fix:** tie each insertion to the place `layout.rs` writes it, read off the
*before* tree's `sites`: `(X)` only at `c.name_span.end` of a shorthand
connection (`c.expr.is_none()`); `,`, `.X(Y)` and `, .X(Y)` only at/after the
last element's end of a named list holding `.*`, before its `)` (with the
`,`-before-`//` pair as the one two-piece shape). Anything else refused.
### Finding 2 (BLOCKING — false refusal on a common opentitan shape)
`connections.rs::binds_into` treats a `bind` target that is a lone name no
indexed module answers to as "possibly an instance of the renamed module" and
refuses whenever its list writes `.old` or a `.*` reaching `old`. opentitan's
`hw/ip/prim/fpv/tb/prim_fifo_sync_bind_fpv.sv` has ten `bind i_nopass1
prim_fifo_sync_assert_fpv … (.clk_i, .rst_ni, .clr_i, .wvalid_i, .wready_o,
… .err_o)` — so on the scratch copy (449 files) renaming `prim_count`'s
`err_o` or `clr_i`, `aes_core`'s `clk_i`, `entropy_src`'s `clk_i` or
`prim_packer_fifo`'s `wready_o` is **refused**, over a bind into a
`prim_fifo_sync` instance none of them touches (whole-set engine and LSP
alike). The refusal is new in M3.5. Any module-level
declaration named `clk_i`/`rst_ni`/`err_o`/… in any module is affected while
that file is in the workspace; `hw/ip/sram_ctrl/dv/tb.sv`'s `bind dut … (.*)`
is the same shape. Test: `tests/qa_rename_implicit.rs::
qa_a_bind_into_an_instance_of_another_module_does_not_refuse`
(`#[ignore = "QA finding 2"]`). **Fix:** resolve the lone name as an instance
name through `WorkspaceIndex::instantiations()` (edges carry their instance
names): if every instance so named instantiates a module other than the
renamed declaration's, skip the site; refuse only when one is the renamed
module's or none is found.
### Attacks that held
Verifier (`check/qa_implicit.rs::qa_insertions_the_verifier_already_refuses`,
plus scratch experiments): an insertion inside a string, a comment, an
attribute; an empty named element `(.a(b),, …)`; `(d)` after `.*` or after an
explicit connection; `.din(d)` before the first element with no comma; a
second `, .din(d)` beside the honest one (two separate insertions); a
case-only different net `(D)` (refused by the template: `D` is neither name);
`.d(x)` added to an instance in a generate block whose own `d` shadows the
renamed one (binding print); `(d)` written after another module's `.d`
shorthand (harmless, `.d(d)`, accepted — same binding); `(din)` there (refused).
Rewrite (`tests/qa_rename_implicit.rs`, 20 passing, public `rename` only):
port rename over `.p` / `.*` / explicit / `.clk, .*` / `.d, .*` in one file;
two instances in one instantiation; an instance array `leaf u[3:0] (.*)`; a
non-ANSI port; one-per-line list with a `//` comment on the last element
(comma before the comment, element on its own line at the element's
indent); an inline list with a trailing `//` (element lands at column 0 — no
indent to copy; legal, cosmetic); an attribute on a connection and a block
comment after `.*`; an escaped net `\d$x ` renamed to a plain name (the
terminating blank stays where it was, `.\d$x (dd) )`); a leaf port under
nested `.*` (only the direct parent changes); a net rename reaching a `bind`
in a file spelling neither name (the whole-set caller); a hierarchical-bind
net rename refused; `bind top : u_t …` (instance-list form) rewritten; an
interface port bound to an interface instance by `.*`; a generate-scoped
shadow (module-level rename touches only the outer instance, the block's net
only the inner two); module declared twice, `ifdef`-split list, parent `.*`
capturing the new name — all refused with the instance named; a parameter
named like the port is no binding; a shorthand into an unreadable module is
still written out. **Round trip:** `d`→`din`→`d` leaves the declaring file
byte-identical; the parent differs only in the written-out connections —
`(.*)` becomes `(.*, .d(d))` and `.d` becomes `.d(d)`; no warnings on the way
back.
### LSP parity (`server/tests/qa_rename_implicit.rs`, 3 passing)
Port rename with the users on disk only — the same edits as the engine; an
unsaved open buffer using `.*` over an on-disk file connecting explicitly —
the buffer's text is the one rewritten; a net rename reaching a bind file that
spells neither name — handed over by `leaf`'s instantiation sites (the bound
module declares the port, so it is a container of the name). `instantiated_by`
reads only `self.index`, and `current_text` drops anything not held, so it
cannot hand over a file outside the workspace. **One-hop cost on opentitan**
(scratch copy, release, `QA_NO_HOP` toggle in a scratch build): `key_len_q` in
`aes_core.sv` selected 4 → 23 files, select 0.6 → 1.2 ms, request 4 → 22 ms —
and without the hop that rename is *refused* (`u_fi_ctrl_fsm … connects with
.* to fi_control_fsm_wrapper, which lucisv cannot read`), as are the three aes
fault-injection renames below; `prim_count.err_o` 121 → 181 files, 46 → 59 ms.
No explosion.
### Opentitan dry runs (scratch copy, whole-set engine and LSP agree)
- `fi_control_fsm_wrapper`'s port `aes_ctrl_cs` → `aes_ctrl_state`:
`bind aes_control_fsm … u_fi_ctrl_fsm (.*)` gains
`.aes_ctrl_state(aes_ctrl_cs)` (binds `aes_control_fsm`'s own state
variable — what `.*` bound) and the wrapper's `fi_if (.*)` gains
`.aes_ctrl_cs(aes_ctrl_state)`. Correct by hand.
- `aes_control_fsm`'s variable `aes_ctrl_cs` → `aes_ctrl_cs_q`: the bind gains
`.aes_ctrl_cs(aes_ctrl_cs_q)`. Correct; the `PRIM_FLOP_SPARSE_FSM`/`ASSERT`
invocations still spelling the old name are warned (existing macro policy).
- `fi_control_if`'s port `aes_ctrl_cs` → `ctrl_state`: the wrapper's `.*`
gains `.ctrl_state(aes_ctrl_cs)`. Correct.
- `entropy_src_fsm_cov_if`'s `state_i` → `st_i`: tb.sv's
`bind prim_sparse_fsm_flop : dut.… (.clk_i, .state_i, .state_o)` becomes
`.st_i(state_i)`. Correct.
- `prim_fifo_sync`'s `clr_i`: refused over `prim_fifo_sync_bind_fpv.sv`'s
`.clr_i` — a *correct* refusal (those binds target `prim_fifo_sync`
instances). `prim_count`/`aes_core`/`entropy_src`/`prim_packer_fifo`: the
false refusals of finding 2.
- Every rewrite was listed in `warnings`, one sentence each.
### Sizes / style
Production lines (non-blank, non-`//` lines before `#[cfg(test)] mod tests {`):
`rename/connections.rs` 434, `rename/sites.rs` 168, `rename/layout.rs` 82,
`rename/mod.rs` 433 (HEAD 423), `check/implicit.rs` 318, `check/mod.rs` 420
(HEAD 405), `module_select.rs` 36, `state/mod.rs` 985 (HEAD 981 — already over,
§55). Functions over 50 lines: `check::verify` 94 (HEAD 75 — now past the
"investigate at 80" mark), `check::implicit::bindings_match` 60,
`rename::renaming` 56 (HEAD 50); `verify_move` 101 is pre-existing. No
`unwrap`/`expect`/`panic!`/`#[allow]` in the new production code.
### Gates (all through `tools/guard.sh`, one at a time)
- `cargo fmt -p vlog_refactor -p lucisv_server -p lucisv_mcp -- --check` — clean
(after formatting my three files).
- `cargo clippy -p vlog_refactor -p lucisv_server -p lucisv_mcp --all-targets` —
`Finished`, no warnings.
- `cargo test -p vlog_refactor` — 587 passed, 0 failed, 6 ignored.
- `cargo test -p lucisv_server` — 1713 + 99 + 3 passed, 0 failed.
- `cargo test -p lucisv_mcp` — 0 failed; `qa_rename_never_breaks_an_implicit_port_connection`
(M3 finding 1, un-ignored) passes.
- `cargo test --workspace` — **4 732 passed, 0 failed, 52 ignored**
(4 707 + 25 QA tests; 4 new ignored findings tests).
**2026-09-23 — QA agent, M3.5 re-check (after the dev's rework).** Charter:
re-derive both blocking findings against the fix (`Slots` in
`check/implicit.rs`; `bind_reaches`/`instance_owners` in
`rename/connections.rs`), confirm the three moves out of `verify` are pure,
re-run the opentitan copy, gates.
### Verdict: FAIL — findings 1 and 2 closed; one new BLOCKING finding (3); one non-blocking note
### Finding 3 (BLOCKING, new) — a lone `,` at the end of any `.*` list verifies
`Slots::takes` admits `Template::Comma` at the end of every `.*` list, alone.
The engine only ever writes it as the first half of the comma-before-`//`
pair, whose second half (`.X(Y)`, `Template::Connection`) is already required
to have the comma (`comma_at`) — but not the other way round. Where the list
binds one of the two names the binding print refuses the cut; where it binds
neither (a `.*` into a module declaring neither name, in a file the rename
edits for another reason) nothing refuses: the tolerant parser reports no
diagnostic for `(.*,)` (the same leniency as `{d,, d}` in round one), the
pieces match, and the binding print has nothing to compare. Reproduction:
`check/qa_implicit.rs::qa_r_a_lone_trailing_comma_on_a_wildcard_binding_neither_name`
(`#[ignore = "QA finding 3"]`) — `other u_o (.*)` becomes `other u_o (.*,)`
beside an honest `.d` → `.din(d)` rewrite in the same file, and `verify`
returns `Ok(())`. Not a shape the engine writes today; a masked corruption the
safety net accepts, the class invariant 4 is about. **Fix** (a few lines in
`Slots::takes`): admit `Comma` at a list's end only when the same edit list
also inserts a `Connection` into that list (after trivia, before its `)`) —
the mirror of `comma_at`. Worth also filing against the tolerant parser: a
trailing `,` in a named connection list and an empty concatenation element
parse without a diagnostic.
### Finding 1 re-derived — the position rule (9 new tests + finding 3, `check/qa_implicit.rs::qa_r_*`)
All verifier-direct (`check::verify`, crate-internal), each a corrupt edit set
beside a control that verifies `Ok`:
- `, .din(d)` appended to a named list **without** `.*` — refused "outside a
connection list";
- `(d)` after an **explicit** connection's name (`.clk(d)(clk)`,
`.din(d)(d)`) — outside;
- `, .din(d)` **between** `.*` and a later `.clk(clk)` — outside (the same
text after the last element verifies);
- `, .din(d)`, `(d)`, `,` **after the `)`** — outside;
- a `.*` list **inside a generate-for**: the honest append verifies, a bare
`.din(d)` without its comma is outside, nothing added is a cut;
- a **lone trailing `,`** at a `.*` list's end (`(.*,)`, a legal *slot* for the
comma-before-`//` shape) where the list binds `d` — refused, but by the
binding print (`din` loses its binding), not by the position rule; where the
list binds neither name it verifies — finding 3;
- **shift accounting**: `d` → `dnew` in `(.clk,.d,.q)` grows the line by
exactly the distance from `.d`'s end to `.q`'s end, so a tail computed in
after-coordinates lands on `.q`'s shorthand slot in before-coordinates.
The before-coordinate tail verifies; the shifted one (`.dnew,.q(d)`) is
refused by the binding print. Slots and edits are both in before-coordinates
(`Slots::of(before)`, `edit.range.start`), so there is no mixed accounting;
- an append **inside the trailing `//` comment** (mid-comment and at its end):
`Slots::takes` admits it (the gap is trivia), the piece ledger refuses it; the
honest `,` + `\n .din(d)` pair verifies; the bare connection without the
comma is outside; the pair with the connection written mid-comment is
refused;
- a **shorthand in a `bind`** (net rename): `(x)` after `.d` verifies,
nothing is a cut, `(x)` after `.clk` (a legal slot) is refused by the binding
print, `(d)` after `.d` is refused.
My three round-one tests and the dev's two same-offset tests pass un-ignored.
### Finding 2 re-derived — the enclosing-module rule (5 new tests + 1 note, `tests/qa_rename_implicit.rs::qa_b_*`)
Renaming `cnt`'s `err_o`, with `chk` bound by `.clk_i, .err_o` shorthands:
- a bind in module `a` onto `u`, where `a`'s own `u` is a `fifo` and `b`'s `u`
is a `cnt` — **skipped**, `a.sv` untouched, `b`'s own `.err_o` written out;
- swapped (`a`'s `u` is the `cnt`) — **refused**, naming `c_u` at a.sv:4;
- a bind at **file scope** onto `u` where only `tb`'s `u` exists, a `fifo` —
skipped, no warning; the same where `tb`'s `u` is a `cnt` — refused;
- a bind onto a name no indexed instance has — refused.
### Note 1 (non-blocking, lead-accepted) — the generate-block gap, reproduced
`module a` with `fifo u` only inside `if (1) begin : g`, `bind u chk c_u
(.clk_i, .err_o)` in `a`, and a parent `p` holding `a u_a ()` and `cnt u`.
Upward resolution from `a` does not see `a.g.u`, so the bind reaches `p.u`, a
`cnt`. The engine counts `a.g.u` as `a`'s own, returns `Elsewhere`, and the
rename **succeeds** with `a.sv` untouched — the bind's `.err_o` is cut. Note the
direction: this is a silent skip, not a refusal, and the verifier cannot catch
it (a bind onto an instance prints `Opaque` on both sides). Exotic shape (a
same-named instance in a generate block of the binding module *and* in its
parent). Pinned as `qa_b_a_generate_scoped_instance_is_not_the_enclosing_modules_own`
`#[ignore = "QA note 1: accepted generate-block gap"]`, asserting the refusal.
Cheapest fix if the lead wants it: count an edge as local only when its
instance is declared in the module's own scope, or refuse whenever a local
same-named instance sits inside a generate block.
### `verify`'s three moves — pure
Compared the round-one body with the current one line by line: step 1's loop
moved verbatim into `tokens_verified` (same `measure` stage — `trace.tokens` —
per file, `names[1]` is `new_name`); the `inserted` lookup became
`implicit::inserted_in(edits, i)`, the same `find` + `inserted_after` +
`unwrap_or_default`; step 3 binds `names` to a local before the same call. No
behaviour change. `verify` is 79 lines.
### Opentitan copy, re-run (engine whole-set and LSP fan-out agree on every edit count)
| rename | result |
|---|---|
| `fi_control_fsm_wrapper.aes_ctrl_cs` → `aes_ctrl_state` | 2 files, 3 edits (bind `.*` + wrapper `.*`), as round one |
| `aes_control_fsm.aes_ctrl_cs` → `aes_ctrl_cs_q` | 2 files, 4 edits, as round one |
| `fi_control_if.aes_ctrl_cs` → `ctrl_state` | 2 files, 3 edits, as round one |
| `entropy_src_fsm_cov_if.state_i` → `st_i` | 2 files, 3 edits, as round one |
| `prim_fifo_sync.clr_i` → `clear_i` | refused over `prim_fifo_sync_bind_fpv.sv`'s `.clr_i` — correct, those binds target fifo instances |
| `prim_count.err_o` → `error_o` | **now succeeds**: 13 files, 16 edits; `.err_o` written out in `prim_count_tb.sv` and `prim_packer.sv` |
| `prim_count.clr_i` → `clear_i` | **now succeeds**: 13 files, 16 edits; three `.clr_i` shorthands written out (tb, `prim_fifo_sync_cnt` ×2) |
| `aes_core.clk_i` → `clock_i` | **now succeeds**: 3 files, 24 edits |
| `aes_core.key_len_q` → `key_len_qq` | 1 file, 3 edits |
| `entropy_src.clk_i` → `clock_i` | **now succeeds**: 5 files, 10 edits; `.clk_i(clock_i)` in three internal instances and two `bind entropy_src` asserts, `, .clk_i(clock_i)` on the cov bind's `.*` |
| `prim_packer_fifo.wready_o` → `wready_q` | **now succeeds**: 5 files, 13 edits; the two `bind prim_packer_fifo : dut.…` lists get `.wready_o(wready_q)` |
Each rewrite checked by hand against what the implicit connection bound; each
is listed in `warnings`. LSP fan-out sizes: 14–312 files, 9–213 ms per
request (`clk_i` of `aes_core`/`entropy_src` are the 312-file ones).
### Gates (each through `tools/guard.sh`, one at a time)
- `cargo fmt -p vlog_refactor -p lucisv_server -p lucisv_mcp -- --check` — clean.
- `cargo clippy -p vlog_refactor -p lucisv_server -p lucisv_mcp --all-targets` — `Finished`, no warnings.
- `cargo test -p vlog_refactor` — 609 passed, 0 failed, 4 ignored.
- `cargo test -p lucisv_server` — 1713 + 99 + 3 passed, 0 failed.
- `cargo test -p lucisv_mcp` — 206 passed, 0 failed, 2 ignored.
- `cargo test --workspace` — **4 754 passed, 0 failed, 50 ignored** (4 740 +
14 new QA tests; the two new ignored tests are note 1 and finding 3).
**2026-09-23 — QA agent, M3.5 final re-check (finding 3 fix: the comma/connection pair).**
Charter: re-derive finding 3, attack the pair rule in `Slots::takes`, confirm
my finding-3 test is unchanged, re-run the opentitan copy, gates.
### Verdict: FAIL — finding 3 closed; one new BLOCKING finding (4), same class
### Finding 3 — closed
`qa_r_a_lone_trailing_comma_on_a_wildcard_binding_neither_name` now passes
un-ignored. Diffed against the text I wrote (reconstructed from my own edit):
**byte-identical apart from the removed `#[ignore = "QA finding 3"]` line**.
The dev's cross-list test passes.
### Pair-rule attacks (`check/qa_implicit.rs::qa_p_*`, 4 new passing tests)
- `,` in one file's list and its `.din(d)` in another file's list, both ways —
refused "outside a connection list" (each file's edits are checked alone).
The honest pair in both files verifies.
- two `,` and one `.din(d)` in one list — refused (the tolerant parser does
flag `.*,,` followed by a connection); one `,` and two `.din(d)` — refused
(binding print).
- `.din(d)` before its `,` at the same offset (`.*\n .din(d), // …`) and
glued (`.*.din(d),`) — refused (parse). In source order at the same offset
(`.*,\n .din(d) // the rest`) it verifies: a legal list, the same
bindings, the comment kept (it now ends the new line) — accepted, harmless.
- a pair in a `.*` list whose last element is an error element: see finding 4.
Where the "error element" is not SV at all (`+.din(x)`) the before file
already does not compile; the verifier admits the pair after it (pinned).
### Finding 4 (BLOCKING by the rule; loud, not silent) — a slot at an error element's end
`Slots::of` registers a `.*` list whose last element is `ListElem::Error`,
with the element's end as the append point. `.d(type(q)'(q))` is valid SV (a
cast through a type reference — 1800-2017 A.8.4 `constant_primary ::=
type_reference`) that the tolerant parser reads as the error element
`.d(type(q)'(q)`, one byte short of the connection's own `)`. An append there
lands **inside** that connection: `leaf u_e (.*, .din(type(q)'(q), .din(d)));`
— valid input, output that does not compile — and `verify` returns `Ok(())`:
the parse check compares diagnostic *counts* (one before, one after), and the
binding print cannot see into an error element. The engine never writes it
(`unreadable_elements` refuses a list whose error element spells either
name), so nothing ships broken today; it is the verifier accepting what it
exists to refuse, the class of findings 1 and 3. Reproduction:
`check/qa_implicit.rs::qa_p_an_append_at_an_error_elements_end_is_refused`
(`#[ignore = "QA finding 4"]`); the same append after the connection's `)` is
refused (`qa_p_a_pair_after_an_error_element`). **Fix** (a few lines in
`Slots::of`): register no list slot — and no tail — for a site whose `conns`
hold an error element (or, mirroring the engine exactly, one whose error text
spells either name or `*`). Worth adding to the vlog_parser handshake: `type(x)'(y)`
in a port connection parses as an error element.
### Opentitan copy, re-run — identical
All 11 renames of the previous table, whole-set engine and LSP fan-out:
the per-edit and per-warning output is **identical** to the previous run
(diffed with timings stripped).
### Gates (each through `tools/guard.sh`, one at a time; no guard kill)
- `cargo fmt -p vlog_refactor -p lucisv_server -p lucisv_mcp -- --check` — clean.
- `cargo clippy -p vlog_refactor -p lucisv_server -p lucisv_mcp --all-targets` — `Finished`, no warnings.
- `cargo test -p vlog_refactor` — 615 passed, 0 failed, 4 ignored.
- `cargo test --workspace` — **4 760 passed, 0 failed, 50 ignored**, 135 s
(4 756 + 4 new QA tests; the new ignored test is finding 4).
**2026-09-23 — QA agent, M3.5 final confirmation (finding 4 fix, lead-applied).**
Read the change: `Slots::of` skips every site with `site.unreadable()` — no
shorthand tail, no append point — with the finding cited; the only change to
my file is the junk-list pin in `qa_p_a_pair_after_an_error_element` flipped to
`outside` (correct: that list has no slot now). Re-derived against the built
verifier: the cast-list append inside the connection (`.din(type(q)'(q),
.din(d)))`) is refused; the same append after the connection's `)` is
refused; new `qa_p_a_clean_list_beside_an_error_element_list_still_verifies`
— an honest `.*` append and `.d` → `.din(d)` in clean lists verify beside an
untouched `other u_x (.*, .clk(type(clk)'(clk)))` in the same file, and an
append into that list is refused "outside a connection list". Consequence
noted, non-blocking: a `.*` list holding an error element that genuinely needs
a rewrite is now refused by the verifier even where the engine would append
(error text spelling neither name) — a refusal, never a corruption, and only
for lists lucisv cannot parse. `tools/guard.sh -- cargo test -p vlog_refactor`:
617 passed, 0 failed, 3 ignored. **Verdict: PASS** — findings 1–4 closed; QA
note 1 (generate-block gap) stands as the lead's accepted known gap.
## Review
**2026-08-29 — lead, performance-wave Lane A.** Reviewed after QA's
@@ -1848,3 +2564,26 @@ engine's more precise words (pinned by the control test
costs under 0.2 ms over all 3 979 OpenTitan files and reads nothing, so the
`prepare_rename_here` cost stays gone. Details and measurements:
`docs/features/macro-word-census/README.md`.
**Lead, 2026-09-23 (M3.5).** The defect was a CLAUDE.md invariant-1
corruption in a shipped engine — a rename cut `.name`/`.*` bindings and
verified clean because nothing records what an implicit connection binds —
found only when the MCP block put `rename` in front of an adversarial QA.
The fix is the right shape: insertion-only rewrites through four spelled
templates, every rewrite in the warnings, every unreadable case refused by
name, and a verifier that prints every implicit binding before and after
(`check/implicit.rs`). That verifier is a widening of the rename's safety
contract, so invariant 4's discipline applied: three QA rounds attacked it
and found, in order, that it checked what an insertion spells but not where
it lands (fixed: slots keyed on the before-tree's sites), that a lone `,`
at the end of a `.*` list passed (fixed: the comma and its `.X(Y)` are
accepted only as a pair in one list), and that a list holding an error
element registered a slot at the element's end (fixed by the lead: such a
list has no slot; QA's pin flipped to the stricter rule). Rulings: the
enclosing module's own instances win a bare-name `bind` (§23.11); the
generate-scoped instance is an accepted, documented gap; the LSP hands the
engine one more hop of instantiated modules so a `.*` into a module
declaring neither name is read, not refused. Filed for the owner: the
tolerant parser's leniency on a trailing `,` and `{d,, d}`, and
`type(x)'(y)` in a connection parsing as an error element (vlog_parser).
Committed as M3.5; ships in 0.56.0.