From 4edada583fcade0d1054bfb4ff44c7522aa325e6 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 23 Sep 2026 11:41:46 -0700 Subject: [PATCH] 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 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- TODO-MCP.md | 6 +- TODO.md | 5 + crates/lucisv_mcp/src/tools/edit.rs | 2 +- crates/lucisv_mcp/tests/qa_m3.rs | 1 - crates/lucisv_server/src/module_select.rs | 35 +- crates/lucisv_server/src/rename.rs | 5 +- crates/lucisv_server/src/server/tests/mod.rs | 2 + .../src/server/tests/qa_rename_implicit.rs | 118 +++ .../src/server/tests/rename_implicit.rs | 67 ++ crates/lucisv_server/src/state/mod.rs | 8 +- crates/vlog_refactor/src/check/implicit.rs | 805 ++++++++++++++++++ crates/vlog_refactor/src/check/mod.rs | 38 +- crates/vlog_refactor/src/check/qa_implicit.rs | 498 +++++++++++ .../vlog_refactor/src/rename/connections.rs | 609 +++++++++++++ crates/vlog_refactor/src/rename/layout.rs | 184 ++++ crates/vlog_refactor/src/rename/mod.rs | 22 +- crates/vlog_refactor/src/rename/sites.rs | 253 ++++++ .../vlog_refactor/tests/qa_rename_implicit.rs | 469 ++++++++++ crates/vlog_refactor/tests/rename_implicit.rs | 376 ++++++++ docs/features/lucisv-server/README.md | 2 +- docs/features/refactor-rename/README.md | 741 +++++++++++++++- 21 files changed, 4226 insertions(+), 20 deletions(-) create mode 100644 crates/lucisv_server/src/server/tests/qa_rename_implicit.rs create mode 100644 crates/lucisv_server/src/server/tests/rename_implicit.rs create mode 100644 crates/vlog_refactor/src/check/implicit.rs create mode 100644 crates/vlog_refactor/src/check/qa_implicit.rs create mode 100644 crates/vlog_refactor/src/rename/connections.rs create mode 100644 crates/vlog_refactor/src/rename/layout.rs create mode 100644 crates/vlog_refactor/src/rename/sites.rs create mode 100644 crates/vlog_refactor/tests/qa_rename_implicit.rs create mode 100644 crates/vlog_refactor/tests/rename_implicit.rs diff --git a/TODO-MCP.md b/TODO-MCP.md index 42ae51f..3bc2678 100644 --- a/TODO-MCP.md +++ b/TODO-MCP.md @@ -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 diff --git a/TODO.md b/TODO.md index 2acd1e2..21eab69 100644 --- a/TODO.md +++ b/TODO.md @@ -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 diff --git a/crates/lucisv_mcp/src/tools/edit.rs b/crates/lucisv_mcp/src/tools/edit.rs index aab16d8..2c4d2b0 100644 --- a/crates/lucisv_mcp/src/tools/edit.rs +++ b/crates/lucisv_mcp/src/tools/edit.rs @@ -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 { diff --git a/crates/lucisv_mcp/tests/qa_m3.rs b/crates/lucisv_mcp/tests/qa_m3.rs index 50659d6..0278c35 100644 --- a/crates/lucisv_mcp/tests/qa_m3.rs +++ b/crates/lucisv_mcp/tests/qa_m3.rs @@ -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)] = &[ ( diff --git a/crates/lucisv_server/src/module_select.rs b/crates/lucisv_server/src/module_select.rs index 5786226..300ac1a 100644 --- a/crates/lucisv_server/src/module_select.rs +++ b/crates/lucisv_server/src/module_select.rs @@ -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 { + let ids: BTreeSet = 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(); diff --git a/crates/lucisv_server/src/rename.rs b/crates/lucisv_server/src/rename.rs index 127f92c..3fc2f22 100644 --- a/crates/lucisv_server/src/rename.rs +++ b/crates/lucisv_server/src/rename.rs @@ -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"); diff --git a/crates/lucisv_server/src/server/tests/mod.rs b/crates/lucisv_server/src/server/tests/mod.rs index df03ed1..213da19 100644 --- a/crates/lucisv_server/src/server/tests/mod.rs +++ b/crates/lucisv_server/src/server/tests/mod.rs @@ -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; diff --git a/crates/lucisv_server/src/server/tests/qa_rename_implicit.rs b/crates/lucisv_server/src/server/tests/qa_rename_implicit.rs new file mode 100644 index 0000000..f91c4fc --- /dev/null +++ b/crates/lucisv_server/src/server/tests/qa_rename_implicit.rs @@ -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 = + 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 { + 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:#}" + ); +} diff --git a/crates/lucisv_server/src/server/tests/rename_implicit.rs b/crates/lucisv_server/src/server/tests/rename_implicit.rs new file mode 100644 index 0000000..e8a5b85 --- /dev/null +++ b/crates/lucisv_server/src/server/tests/rename_implicit.rs @@ -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 + ); +} diff --git a/crates/lucisv_server/src/state/mod.rs b/crates/lucisv_server/src/state/mod.rs index 6e69a0d..aed7952 100644 --- a/crates/lucisv_server/src/state/mod.rs +++ b/crates/lucisv_server/src/state/mod.rs @@ -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. diff --git a/crates/vlog_refactor/src/check/implicit.rs b/crates/vlog_refactor/src/check/implicit.rs new file mode 100644 index 0000000..f51fff2 --- /dev/null +++ b/crates/vlog_refactor/src/check/implicit.rs @@ -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