# refactor-rename Milestone **M2** of `docs/features/refactor/README.md`. ## Goal Give vfmt the refactoring every Verilog user misses: rename a symbol and have *every* reference to it change, across files, or have the request refused with a sentence explaining why. The engine lives in a new crate, `crates/vlog_refactor`, so the CLI and every editor get identical behavior; `vfmt_server` only maps the protocol (`textDocument/prepareRename`, `textDocument/rename` → `WorkspaceEdit`). Every edit comes from a span the semantic layer resolved — there is no textual search-and-replace anywhere in this feature — and the whole edit is verified in memory before it is returned: re-tokenize every touched file and re-resolve it, and refuse the *entire* rename if anything but the renamed name moved. That is the formatter's never-corrupt contract, applied to refactoring, without touching `vlog_formatter` or `verify.rs`. ## API as built ```rust // crates/vlog_refactor/src/lib.rs pub struct TextEdit { pub range: TextRange, pub new_text: String } pub struct RefactorEdit { pub edits: Vec<(PathBuf, Vec)>, pub warnings: Vec } pub struct RenameTarget { pub range: TextRange, pub name: String } pub fn prepare_rename(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Result; pub fn rename(files: &[(PathBuf, String)], file: &Path, offset: u32, new_name: &str) -> Result; ``` `files` is **the boring option**: the in-scope files as `(path, text)` pairs — exactly what `WorkspaceIndex::build` already takes, and exactly what `vfmt_server`'s scope resolution (M1's filelist ⊃ walk ⊃ siblings ladder, open buffers overlaying disk) already produces. No trait, no borrow of server state, no I/O inside the crate. `Err(String)` is a **user-facing sentence**: the server returns it verbatim as the LSP request error, which is what VS Code puts in the rename box. Deviations from the milestone sketch, and why: - **`offset: u32`, not `usize`.** Everything below the protocol — `TextRange`, `Semantics::symbol_at`, `Def.name_span` — counts bytes in `u32`. A `usize` parameter would be cast at both ends of every call. - **`prepare_rename` returns a `RenameTarget`**, not a bare range: the editor wants the placeholder too, and it is the identifier's own text. ## What can be renamed Every kind `vlog_semantic` resolves, because the engine never looks at `SymbolKind` at all — it renames "the symbol the cursor resolves to", whatever that is: nets and variables (`wire`/`reg`/`logic`/`int`), module ports (ANSI and non-ANSI, where the redeclaration is a *reference* to the header port), parameters and localparams, genvars, typedefs, enum variants, struct members, functions, tasks, task/function arguments, block labels, module names, instance names, packages, classes and class members. Renaming **from a reference works exactly like renaming from the declaration**: the cursor is resolved to a declaration first (in this file, or through the workspace overlay into another file), and everything after that is the same code path. **End labels move with their declaration.** `endmodule : m`, `endinterface`/`endpackage`/`endfunction`/`endtask`/`endclass : name`, and `end : label` / `join : label` on a named block or generate block are all edited, because `vlog_semantic` records each of them as a *use* of the declaration it closes (round 2 of this milestone; see Handshakes). No text matching is involved: the label is bound to its own construct by the binder, so a label can never attach to a same-named declaration somewhere else. Two cases still record nothing and are warned about instead — a label that does not spell the declared name (already illegal SystemVerilog) and a label whose declaration was a redeclaration that bound no symbol of its own. Cross-file comes from the same overlay `textDocument/definition` uses: every in-scope file is analyzed, its external candidates are resolved against the `WorkspaceIndex`, and a reference whose answer is *this* declaration (same `FileId`, same `name_span`) is an edit. That covers module names in instantiations, package members at `import p::*` / `import p::x` / `p::x` sites, `.port(...)` connection names, and `#(.PARAM(...))` overrides. ## The refusal list — exact `rename` returns `Err` and produces **no edits at all** when: 1. `new_name` is empty, does not lex, lexes to more than one token, lexes to something that is not an identifier, or is a keyword. 2. `new_name` is the name it already has. 3. The file the request names is not one of the in-scope files. 4. The cursor is on no identifier the semantic layer recorded (whitespace, punctuation, a keyword, a `` `define`` directive, a system task). 5. The identifier is a reference the layer left `NotFound`. 6. The identifier is a reference the layer left `InheritedCandidate` — a name that could only come through a class's `extends`, which nothing resolves. 7. The identifier is an external candidate the workspace index cannot answer (`StillUnresolved`): the declaration is outside the indexed files, so the rename would be half a rename. 8. The identifier is an external candidate the index answers **ambiguously** (`ExternalTarget::Ambiguous`) — the name is declared in more than one file and picking one would be a coin flip. 9. The declaration is a file-scope unit (module, package, class, file-scope typedef) whose name the index holds more than once — the same ambiguity, caught when the rename starts *from the declaration* and so never reaches rule 8. 10. Some other in-scope reference to the name resolves ambiguously **onto this declaration** — a use vfmt would have to edit but cannot attribute. 11. The declaration's `name_span` is empty (the layer could not find the name literally in the source), or an edit span does not slice back to the name. 12. **Collision / capture.** After applying the edits in memory and re-analyzing every **watched** file — every file the edits touch, plus every file whose text spells the old or the new name — any reference or declaration resolves differently than it did before (modulo the rename itself), or the reference/declaration sets differ in size. This is the check that refuses `x` → `y` when a `y` already exists in a scope the rename reaches, in *both* directions: the renamed uses being captured by an existing `y`, and an existing use of `y` being captured by the renamed declaration — **including in a third file the rename never edits**, whose existing `y` reference the rename would make ambiguous. 13. **Token verification.** A touched file no longer lexes, or its token stream is not identical to the original's except that the edited 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 rename, never part of it (`RefactorEdit` is all-or-nothing, hard invariant 1's shape for refactorings). `prepare_rename` applies rules 3–7 (and 9), which is exactly what an editor needs to decide whether to open the rename box at all: everything else needs a new name to judge. ## The verification story Two independent checks, both run in memory on the edited text, before anything is returned. **1. Token-stream identity.** Every touched file is re-tokenized. The new stream must have the same length as the old one, and token *i* must have the same kind, the same attached comments (leading list and trailing, by text), the same `blank_before`, the span it gets by shifting the original's, and the same text — except for tokens whose span is exactly an edit, which must be `Ident` tokens spelling the new name. A rename that merged two tokens, split one, ate a comment, changed a number's spelling or wandered into a string or a directive cannot survive this. It is the analog of the formatter's verify pass, and it lives in this crate rather than borrowing `verify.rs` — hard invariant 4 says the formatter's safety net does not widen, and nothing here touches it. **2. Resolution identity.** For every **watched** file, before and after, the engine builds a print of *every* declaration `(name_span, name, kind)` and *every* reference `(name_span, name, what it resolves to)`, where "what it resolves to" is a workspace-wide anchor: `Local(span)` for an in-file resolution, `External(path, span)` for one the overlay answered, `None` for anything unresolved. The *before* print has its spans and anchors shifted through the edit map, and the names of the edited occurrences replaced with the new name. The two prints must be **equal**. So: every edited occurrence still resolves to the renamed declaration, the renamed declaration still has exactly the same reference set, and no other name in those files changed meaning. The post-edit side re-builds the workspace index over the edited texts, so a cross-file capture is caught the same way an in-file one is. **The watch list.** Watched = every file that receives an edit, plus every file whose text spells the old name or the new name as a whole word. That is sound: an edit only adds and removes declarations of those two names, and a lookup of any *other* name cannot see them, so a file mentioning neither cannot change meaning. The whole-word text search is a deliberate *superset* of "has a token spelling the name" — a token always spells its name literally — so it errs by watching a file whose only mention is in a comment, which costs one analysis and never causes a refusal (its print is identical either way; there is a test). This is what closes QA's third-file case: `top.sv` instantiating a pre-existing `child` never spells `sub`, receives no edit, and would previously have been accepted while its instantiation silently became ambiguous. Why the whole print and not just the names involved: only lookups of the old and the new name *can* change, so a narrower check would be sound — but it would need its own argument for why, and the wide one costs a few hundred microseconds on a Verilog file and needs no argument at all. Simplicity first. ## Preprocessor honesty vfmt does not preprocess (TODO.md §7). What that means here, exactly as implemented: - **`` `define`` bodies and macro names are never edited.** A `` `define`` is one `Directive` token, so the semantic layer records no reference inside it and no edit can be produced there in the first place. When the workspace's `DefineTable`s show the name as a macro name (`` `define a ``/`` `undef a ``) or inside a macro body, a **warning** names the file and line. - **Macro *invocations* are never edited, and their arguments are warned about.** `` `BUMP(a) `` lexes as a **single opaque `Ident` token**, name and argument list together, so `a` inside it is invisible to the semantic layer — there is nothing to resolve and nothing to edit. The engine scans every in-scope file's macro-invocation tokens for the name as a whole word and warns per occurrence: "`a` appears in the arguments of the macro invocation `` `BUMP `` at m.sv:4 …". This scan covers files the rename never edits, since a macro call in an untouched file still expands to the old name. - **`` `ifdef`` arms are ordinary tokens to vfmt**, so a resolved reference inside one **is** renamed — in every arm. That is the honest behavior: the tokens are there, they bound to the declaration, and editing only one arm would break the build for the other. No warning; there is nothing left unaccounted for. - **Occurrences the layer records nothing for are left alone and warned about, grouped by *why*** — the warning names the actual construct rather than guessing at a template: - `a hierarchical or member tail, which vfmt does not resolve` — `u_inst.sig`, `a.b.c`, and `defparam u1.P` paths. This is the honest limitation: resolving a tail needs instance elaboration, which is a non-goal of `vlog_semantic`. A `defparam` naming a renamed parameter is therefore left pointing at the old name, and said so. - `an end label vfmt could not attach to its declaration` — a mismatched label, or one whose declaration was a redeclaration. - `a label vfmt records no declaration for`, and `an occurrence vfmt cannot attribute to any declaration` for the rest. ## Assumptions - The caller hands over the same file set the workspace index was built from, with open buffers already overlaying disk. The crate does no I/O and does not walk anything. - A file whose text does not contain the old name as a substring cannot contain a reference to it, so it is never analyzed. Sound because the semantic layer promises `src[reference.name_span] == reference.name` — a reference always spells its name literally. This prefilter is what keeps a rename over an 860-file workspace to a handful of analyses. - Duplicate paths in `files` are deduplicated exactly as `WorkspaceIndex::build` does it (sort by path, first copy wins), so the engine's file indices and the index's `FileId`s describe the same texts. - A rename is a rare, user-initiated request, so re-analyzing candidate files twice (once before the edit, once after) is affordable. No caching, no incrementality. - Refactored output is *edited source*, not reformatted source (umbrella Handshakes): the edits are minimal, and the user runs the formatter separately. ## Handshakes **Consumed from `vlog_parser`** (no change required): - `tokenize`, `parse_source_tolerant`, `LineIndex`, `TextRange`. - `token::{Token, TokenKind, is_keyword}` — the new-name validity check and the token-stream verification. - `defines::{DefineTable, DefineKind}` via the index — the macro warnings. **Consumed from `vlog_semantic`** (no change required, nothing patched): - `analyze`, `Semantics::{symbol, symbol_at, reference_at, reference_id_at, references, references_of, file_scope, scope}`. - `Resolution::{Resolved, ExternalCandidate, InheritedCandidate, NotFound}` — the last three are three of the refusal rules. - `WorkspaceIndex::{build, files, path, units, defines}`, `resolve_external`, `ExternalTarget::{Resolved, Ambiguous, StillUnresolved}`, `Def`. - The promise that `Symbol.name_span`/`Reference.name_span` are exact byte ranges that slice back to the name — every edit span is one of these, and the engine re-checks the slice before emitting it. **Promised to `vfmt_server`** (and to any future CLI): - `rename` never panics and never returns a partial edit: `Ok` means every edit in it verified together, `Err` means nothing at all is to be applied. - `RefactorEdit.edits` is sorted by path; each file's edits are sorted by start offset, non-overlapping and non-empty. - `warnings` are informational only — an `Ok` result with warnings is still safe to apply. **Changed in `vlog_semantic`** (lead-authorized 2026-08-24 after QA round 1; strictly additive, and the only cross-module change this milestone makes): - `bind::Target` gains `Declaration(SymbolId)` — "this exact declaration, no lookup". `resolve.rs` answers it with `Resolution::Resolved(id)`. - `Binder::use_end_label` records an end label as a use of the declaration it closes, called from the module/interface, package, class, function, task, generate-block and statement-block/fork-join arms. - Nothing was renamed, removed or re-spanned; `vlog_parser` needed **no** change at all, because `end_label` / `end_label_span` were already on every one of those AST nodes. Logged in `docs/features/vlog-semantic/README.md`'s work log, and its "end labels record nothing" simplification is struck there. The reason this could not stay inside `vlog_refactor`: a rename that leaves `endmodule : old_name` behind produces **non-compiling SystemVerilog**, and 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 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 a much larger change than an end label and is not part of M2. ## Status / TODO - [x] New crate `crates/vlog_refactor` (workspace member; depends on `vlog_parser` + `vlog_semantic` only — no formatter, no LSP types) - [x] `TextEdit` / `RefactorEdit` / `RenameTarget` model - [x] Target location: from a declaration, from an in-file reference, from a cross-file reference through the overlay - [x] Cross-file edit collection through `resolve_external` - [x] New-name validity (single identifier token, not a keyword) - [x] Refusals: unresolved, inherited, still-unresolved, ambiguous (both directions), empty name span, same name, unknown file - [x] Collision safety by re-analysis (resolution print equality) over every **watched** file, edited or not (QA round 1, HIGH #1) - [x] Token-stream verification per touched file - [x] `` `define`` warnings, macro-invocation-argument warnings (QA round 1, HIGH #2), and unaccounted-occurrence warnings grouped by reason - [x] End labels renamed with their declaration, through a lead-authorized `vlog_semantic` change (QA round 1, priority finding) - [x] `vfmt_server`: `rename.rs`, `prepareRename` + `rename`, capabilities - [x] Tests: 64 in `vlog_refactor` (14 unit incl. 8 masked-corruption attacks, 48 behavior, 2 corpus), 3 new in `vlog_semantic`, 8 in `vfmt_server` (7 in `rename.rs`, 1 capability), 1 e2e session - [ ] 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 (`workspace/willRenameFiles`) — umbrella backlog - [ ] Deferred (honest limitation, documented in Preprocessor honesty): hierarchical tails (`u_inst.sig`) and `defparam` paths stay warned-not-edited; resolving them needs instance elaboration, a `vlog_semantic` non-goal ## Corpus acceptance `cargo test -p vlog_refactor --test corpus -- --nocapture`, over the 860 `.v`/`.sv`/`.svh` files in `corpus/` (Ibex, OpenTitan, PULP common_cells, picorv32), 2026-08-24: ``` corpus rename over 860 files: Ok((6, 18)) in 0.38s (release; 1.7s debug) ``` Renaming `prim_fifo_sync` — a module OpenTitan instantiates all over — edits **6 files, 18 occurrences**: the declaration, the instantiations, and the `.port`/`#(.PARAM)` names that reach into it. Every edit slices back to `prim_fifo_sync` in the file it names (asserted), and the whole thing takes 0.38 s in release over the full corpus, index rebuild and verification pass included. The substring prefilter is what buys that: 860 files are indexed twice, but only the handful that spell the name are analyzed. The second test asks `prepare_rename` at 300 offsets spread over a real file — whitespace, punctuation, mid-token, mid-comment, mid-directive — and requires an answer at every one and a panic at none. The tests assert the properties, not the numbers: no panic, every edit covers the name, more than one file touched, under 30 s, and a refusal (which is a correct answer — the corpus really does declare some names twice) reads as a sentence. ## Work log **2026-08-24 — dev agent.** Built the crate and the server wiring. Key decisions, all argued above: - **`(PathBuf, String)` slice as the file view**, not a trait. The server already materializes exactly this list for `WorkspaceIndex::build`; a trait would have one implementor and would have to answer "what is the file set?" as well as "what is this file's text?", which the caller knows better. - **Everything canonicalizes to a declaration** before any edit is computed. Renaming from a reference is not a second code path; it is one extra overlay lookup at the front. - **Verification is two checks, not one.** The token check catches lexical damage (an edit landing inside a string, a comment lost, two tokens merged); the resolution check catches semantic damage (capture, shadowing, a cross-file use silently rebinding). Neither implies the other: a capture leaves the token stream perfect, and a botched span leaves resolution plausible. - **The whole-file resolution print**, rather than only the references spelling the old or the new name. The narrow check is sound, but the wide one is obviously sound, and a Verilog file's reference list is a few thousand entries at most. - **The substring prefilter** is the one performance concession, and it rests on a promise the semantic layer's corpus test already asserts (every `name_span` slices back to its name). - **Unaccounted occurrences are warned about, not edited.** `endmodule : m` is the motivating case. Editing it would mean textual replacement, which this feature does not do anywhere; warning is the honest half-measure until the parser/semantic layer records the label. *(Superseded 2026-08-24 by the rework entry below: end labels are references now and are edited.)* - **Server errors use LSP's `RequestFailed` (-32803)**, which is what the protocol reserves for "the request was well-formed and the server declined"; VS Code shows the message in the rename box. `prepareRename` uses the same code, which is how the editor is stopped from offering a rename that would later fail. - **`Workspace::rebuild_index` and the new `Workspace::sources` share one helper** (`collect_sources`), so a rename sees byte-for-byte the file set the index was built from, including the open-buffer overlay, without keeping a second copy of the workspace in memory. Two things worth flagging for review: - **`endmodule : m` labels are warned about, not renamed.** This is the one place a user could be surprised. The alternative needs a reference from `vlog_semantic` for the end label ("`endmodule : m` and other end labels record nothing", `docs/features/vlog-semantic/README.md`), which is a handshake for a later round rather than a textual patch here. *(The lead authorized exactly that handshake; see the rework entry below.)* - **A `#[allow(clippy::mutable_key_type)]`** on `crates/vfmt_server/src/rename.rs`, with the reason in a comment: `WorkspaceEdit.changes` is keyed by `lsp_types::Uri`, whose interior mutability is its own parse cache and takes no part in `Hash`/`Eq`. The map's shape is the protocol's, not ours. Checks at the end: `cargo fmt --all -- --check` clean, `cargo clippy --all-targets` silent (zero warnings, workspace-wide), `cargo test --workspace` green — 55 in `vlog_refactor`, 212 in `vfmt_server`'s unit suite, 12 e2e sessions, nothing else moved. No `unwrap`/`expect`/`panic!` and no `unsafe` in any library path of either crate (test modules only). **2026-08-24 (later) — dev agent, rework after QA round 1 and the lead's three rulings.** All three items closed; nothing else in the design moved. **1. End labels are renamed, not warned (priority finding).** Taking the lead's authorization, the change went into `vlog_semantic` and *not* into `vlog_parser`: every node that can carry a label — `Module` (module and interface), `ItemKind::Package`, `ClassDecl`, `FunctionDecl`, `TaskDecl`, `GenBlock`, `StmtKind::Block`, `StmtKind::ForkJoin` — already carried `end_label` and `end_label_span`, so there was nothing to add to the AST and the spans suite never moved. `bind.rs` gains one target variant, `Target::Declaration(SymbolId)`, and one 20-line helper, `use_end_label`; `resolve.rs` answers the variant with `Resolution::Resolved(id)`. The decision that matters is **binding, not lookup**: the label is recorded as a use of the symbol the binder *just created for that construct*, so `end : inner` inside a module cannot attach to a different `inner` declared elsewhere, and no text matching is involved anywhere. Two cases deliberately record nothing rather than guess — a label that does not spell the declared name (`endmodule : wrong`, already illegal), and a label whose declaration was a redeclaration that bound no symbol of its own (`wire m;` then `begin : m`). Both then fall through to the warning path, which now names them precisely. `endclocking` is untouched: a clocking block is opaque to `vlog_semantic` and declares no symbol. Three tests added in `vlog_semantic`, five in `vlog_refactor` — including the two masked-corruption attacks the lead asked for: an end label belonging to a *different* construct of the same name must not be edited, and `// endmodule : m` / `"endmodule : m"` in a comment and a string must not be edited. **2. Third-file collision (HIGH #1).** `check::verify` no longer iterates the *edited* files; it iterates the **watched** files — `check.rs::watched_files` — which is the edited set plus every in-scope file whose text spells the old or the new name as a whole word. The soundness argument is one sentence and is now in the Verification story: an edit only adds and removes declarations of those two names, so a file mentioning neither cannot change meaning. Whole-word *text* search rather than a token scan, deliberately: it is a superset (a token always spells its name literally), it needs no parse to decide, and over-inclusion costs one analysis and never a refusal. QA's exact 3-file reproduction is now `a_collision_with_a_third_file_that_never_spells_the_old_name_is_refused`, and its mirror — `a_third_file_that_merely_mentions_the_new_name_in_a_comment_is_not_a_collision` — pins the no-false-refusal half. Corpus rename is unchanged at 0.35 s. **3. Macro-invocation arguments (HIGH #2).** The README's promise was true of `` `define`` bodies and false of macro *calls*, because a call is one opaque token and `unaccounted_warning` compared whole token texts. New `Scope::macro_use_warnings` scans macro-invocation tokens (`Token::is_macro`) for the name as a whole word *inside the argument list*, in every in-scope file that spells it — not only edited ones, since a call in an untouched file still expands to the old name. They are warnings, never edits: opaque is opaque. The Preprocessor honesty section was rewritten to describe exactly this, and to state the hierarchical-tail/`defparam` limitation as the limitation it is rather than burying it. **Bonus defect, fixed.** The fixed `` `endmodule : X` `` warning template is gone. `unaccounted_warnings` now groups strays by *reason*, read off the token stream's neighbours (`stray_reason`): a `.` before the name means a hierarchical or member tail; a `:` preceded by an `end*` keyword means an end label that could not be attached; the rest say so plainly. One warning per reason per file, naming the lines. Checks after the rework: `cargo fmt --all -- --check` clean, `cargo clippy --all-targets` zero warnings workspace-wide, `cargo test --workspace` green at 1085 tests (was 1072). ## QA log **2026-08-24 — QA agent.** ### Gates - `cargo fmt --all -- --check` — clean. - `cargo clippy --all-targets` — clean, zero warnings, workspace-wide (verified with a forced re-check after `touch`ing the new files, since the first run was a no-op cache hit). - `cargo test --workspace` — green, 0 failures across every crate. Counts match the Work log's claims: `vlog_refactor` 55 (14 unit incl. 8 masked-corruption attacks in `check.rs`, 39 behavior in `tests/rename.rs`, 2 corpus), `vfmt_server` unit suite 212, `vfmt_server` e2e 12 sessions (`the_binary_serves_a_whole_session_over_stdio` and friends). - Spot-checked the "no `unwrap`/`expect`/`panic!`/`unsafe` in library paths" claim: the only `expect()` calls in `crates/vlog_refactor/src/check.rs` are inside `#[cfg(test)] mod tests` (lines 302-303, 380). None in `crates/vfmt_server/src/rename.rs` outside its test module. The single `#![allow(clippy::mutable_key_type)]` in `vfmt_server/src/rename.rs:13` carries the required explanatory comment (lines 8-12). All confirmed. - All three gates: **pass, claims confirmed.** ### Priority finding — stale end labels (assessed, not fixed) Reproduced with the crate's public API for every construct that carries an end label. Given `module m; ... endmodule : m`, renaming `m` produces `module top; ... endmodule : m` — the label is untouched, and a warning is attached ("1 occurrence(s) of `m` ... are not resolved references ... and were left unchanged."). This is IEEE 1800 non-compiling output (the end label must match) but the dev's own test (`crates/vlog_refactor/tests/rename.rs:561` `an_end_label_is_left_alone_and_reported`) asserts exactly this as intended behavior, and the Work log already flags it for lead review. I reproduced the same pattern for every other end-labeled construct, which the milestone spec didn't enumerate individually — **all of them are affected, all of them only warned**: - `function ... endfunction : f` → label stays `f` after rename to `g`. - `task ... endtask : t` → label stays `t` after rename to `u`. - `class ... endclass : c` → label stays `c` after rename to `d`. - `package ... endpackage : p` → label stays `p` after rename to `q`. - `begin : blk ... end : blk` (named block) → label stays `blk` after rename to `newblk`. **Bonus defect while reproducing this**: the warning text is a fixed template that always says `` `endmodule : X` `` — literally, regardless of which construct produced the stray occurrence (`crates/vlog_refactor/src/rename.rs:497`). For the function/task/class/ package/block cases above, the warning shown to the user names the wrong keyword (e.g. renaming a task still says `` an `endmodule : t` label ``, never `` endtask ``). Small, but it actively misleads whoever reads the warning while trying to find and fix the stale label by hand. **Verdict on severity**: this is a real, reproducible non-compiling-output defect, but it is a *known, deliberate, tested, and disclosed* tradeoff — the dev flagged it explicitly for review and the Status/TODO says why (`vlog_semantic` records no reference for end labels yet). I'm not treating it as a blocking QA finding on its own; it needs the lead's call on whether M2 ships with this caveat or waits for the `vlog_semantic` handshake. I *am* flagging the warning-text bug above as new information the lead should have. ### New finding (HIGH) — a rename can be accepted while silently making an untouched third file's existing reference ambiguous The README's rule 12 / "verification story" claims collision safety is checked "in *both* directions ... an existing use of `y` being captured by the renamed declaration," over the whole workspace. In the implementation this is only true for files that themselves received an edit (`crates/vlog_refactor/src/check.rs:47-78` iterates `edits`/`edited`, which only contains files `collect_edits` touched — i.e. files that spell `old_name`). A file that spells only `new_name`, and never `old_name`, is outside the substring prefilter (`rename.rs:351`) and is never re-analyzed before/after, even though `rebuilt_index` (`check.rs:86-95`) *does* include its real, unedited text — so the ambiguity really exists in the rebuilt index, it's just never diffed against anything. Reproduction (workspace of 3 files, using the public API directly): ``` sub.sv: module sub;\nendmodule\n // rename target; nothing else in scope mentions "sub" child.sv: module child;\nendmodule\n // pre-existing, unrelated module named "child" top.sv: module top;\n child u1();\nendmodule\n // instantiates child.sv's child; never spells "sub" ``` `rename(&files, &path("sub.sv"), , "child")` returns **`Ok`** with one edit (`sub.sv` only) and **`warnings: []`**. After applying it, the workspace has two modules named `child` (the renamed one in `sub.sv`, and the pre-existing one in `child.sv`), and `top.sv`'s `child u1();` — which used to resolve unambiguously — is now ambiguous. `top.sv`'s bytes are untouched, so there's no textual corruption, but its *meaning* silently broke and nothing in the response says so. This is the same shape as the milestone's own `a_collision_in_another_file_is_refused_too` test (`crates/vlog_refactor/tests/rename.rs:474`) — except that test's `top.sv` already instantiates *both* `sub` and `child`, so `top.sv` is itself in the edited set and the existing check catches it. Drop the `sub` instantiation from `top.sv` (nothing else needs to reference the rename target for the collision to be real) and the refusal silently disappears. This is not the end-label case: there is no warning, no partial edit, no indication anything is wrong — `rename` reports full success. It directly contradicts the "both directions" claim in the Verification story section and, I'd argue, the umbrella's "refuses rather than guesses" principle. I did not fix it (would need `check.rs`'s resolution-identity pass to run over every in-scope file with a nonempty diff against `rebuilt_index`, not just `edited` — a real design change, not a small fix). Verified reproducible on a second run. The probe test itself was scratch (not committed); the repro above is exact enough to rebuild in under a minute. ### New finding (HIGH) — macro-invocation arguments are silently never renamed, with no warning, contradicting the "Preprocessor honesty" section The README states plainly: "text inside a macro invocation's arguments ... are left alone and **warned about**." Reproduced the opposite: given ```systemverilog `define BUMP(x) x = x + 1 module m; int a; initial `BUMP(a); endmodule ``` renaming `a` → `b` (from the `int a;` declaration) returns `Ok` with the declaration and no other edits, and **`warnings: []`** — the `a` inside `` `BUMP(a) `` is left as literal text `a`, and nothing tells the user. Root cause: `vlog_parser::tokenize` lexes an entire macro invocation (name *and* its parenthesized arguments) as **one opaque `Ident` token** (confirmed by direct tokenization: `` `BUMP(a) `` tokenizes to a single `Ident` token with text `` "`BUMP(a)" ``, span covering the whole thing — consistent with `vlog_semantic`'s own `scan::tests::a_macro_invocation_is_one_opaque_token`). `unaccounted_warning` (`crates/vlog_refactor/src/rename.rs:470-501`) looks for stray `Ident` tokens whose *text* equals the target name (`t.kind == TokenKind::Ident && t.text == name`, line 488). Since the argument's text is buried inside a bigger token (`` "`BUMP(a)" `` ≠ `"a"`), it can never match, so this class of occurrence can never produce the warning the README promises for it. This is different from the `endmodule : m` case: there, a warning *is* correctly produced (the label is its own plain `Ident` token). Here, the mechanism that would normally catch "text the layer records nothing for" structurally cannot see inside an opaque macro-invocation token, so the specific promise in the README is simply false as implemented. This one is worse than the end-label case for the same reason as the collision finding above: complete silence. A user renaming a variable that happens to be passed through a function-like macro gets an `Ok`, zero warnings, and a file that no longer behaves as documented (the macro expansion still uses the old name, the declaration doesn't exist under that name anymore). Whether the right fix is "warn, like macro bodies" or "refuse when a macro invocation argument spells the name" is a design call for the dev/lead — the README already committed to "warn," so at minimum the implementation doesn't match its own contract. ### Other attack attempts — passed, no corruption found - **Port name vs. connection signal name, `.p(p)`.** Renaming the *port* declaration only rewrites the connection-name side (`.p(...)` → `.port_new(...)`), leaving the connected signal alone. Renaming the *signal* only rewrites the expression side (`.p(sig_new)`), leaving the port name alone. Both directions correct. - **Genvar used inside a `generate`/`for` loop.** Declaration and every use inside the loop header and body renamed correctly. - **Two symbols with the same name in sibling scopes** (`begin : b1 int n; end` / `begin : b2 int n; end`). Renaming `b1`'s `n` leaves `b2`'s `n` untouched — matches the dev's own `a_name_that_only_shadows_somewhere_the_rename_never_reaches_is_allowed` test, reproduced independently with a different shape. - **Module instantiated via `bind`.** `bind top leaf b_leaf ();` — renaming `leaf` correctly updates the `bind` statement's target type along with the declaration. - **Hierarchical reference tail**, `u_inst.sig` and **`defparam u1.P`**. Both left unedited and both correctly warned about as "a hierarchical or member tail" — consistent with the README. (Note: like `endmodule : m`, this means a `defparam` targeting a renamed parameter is left referencing the *old* parameter name — also non-compiling output, also warned-not- fixed, same class of issue as the priority finding. Didn't reproduce every variant given the time budget; flagging so the lead's end-label decision covers `defparam` paths too, not just `endmodule`/`end` labels.) - **New name requiring escaping** (leading digit, e.g. `1bad`) — refused with "not a valid Verilog identifier," as expected. - **Rename inside a file with error nodes** (tolerant parse, garbage statement present) — renamed the valid declaration/use correctly, no panic, garbage left untouched. - **`new_name == old_name`**, comments/strings, ambiguous declarations, unresolved/inherited candidates — all covered by the existing suite; read and spot-re-ran, all still refuse/behave as documented. ### Real server binary over stdio Built `target/debug/vfmt-server` and drove it directly with a hand-rolled LSP/stdio client (`initialize` → `initialized` → `didOpen` → `textDocument/rename` → `shutdown` → `exit`), not just the crate's Rust tests: - **Multibyte-position case.** File with ` /* é 🎉 */ wire a;` as one line — "é" (1 UTF-16 unit, 2 UTF-8 bytes) and "🎉" (2 UTF-16 units/surrogate pair, 4 UTF-8 bytes) sit before the target identifier on the same line, so byte offset (21), UTF-16 offset (18), and char count (17) all disagree. Sent `textDocument/rename` at `{line: 1, character: 18}` (UTF-16, per the server's advertised `"positionEncoding": "utf-16"`). Got back a `WorkspaceEdit` with the edit range exactly `{18, 19}` on that line — the "a" and nothing else. Correct. - **Refusal case.** Same file, rename to `module` (a keyword). Got back a JSON-RPC error, `code: -32803` (`RequestFailed`), `message: "vfmt: \`module\` is a Verilog keyword."` — matches the documented `-32803` refusal convention exactly. No issues found in the LSP-layer UTF-16 handling or the refusal wiring. ### Summary | Claim | Verdict | |---|---| | `cargo fmt` / `cargo clippy` / `cargo test --workspace` clean | **Pass** | | Test counts (55 / 212 / 12) | **Pass, confirmed** | | No unwrap/expect/panic/unsafe in library paths | **Pass, confirmed** | | Stale end labels (`endmodule`/`endfunction`/`endtask`/`endclass`/`endpackage`/named `end`) | **Confirmed, all affected, all warned-not-fixed** — known/disclosed, lead's call | | Collision safety "both directions" over the whole workspace | **Fails** — silent, only checked for files that were themselves edited | | Macro-invocation-argument occurrences "warned about" | **Fails** — silently never renamed, never warned, contradicts README | | Everything else attempted (port/signal, genvar, sibling shadowing, `bind`, hierarchical tails, `defparam`, escaped names, tolerant parse, UTF-16 offsets, keyword refusal over real stdio) | **Pass** | No fixes applied — none of the findings were small/unambiguous; each needs a design decision (collision-check scope, macro-argument policy, or the `vlog_semantic` end-label handshake) that's the dev's/lead's call, not QA's. No temporary probe files were left in the tree (added, exercised, then removed). **2026-08-24 (round 2) — QA agent.** Re-verification after the dev's rework of all three round-1 findings, per the lead's rulings. ### Gates - `cargo fmt --all -- --check` — clean. - `cargo clippy --all-targets` — clean, zero warnings, workspace-wide (forced re-check after `touch`ing every changed file, not a cache hit). - `cargo test --workspace` — green, 1085 tests, 0 failures — matches the Work log's number exactly (was 1072 in round 1). `vlog_refactor` is now 64 (14 unit, 48 behavior in `tests/rename.rs`, 2 corpus); `vlog_semantic`'s `semantics.rs` gained new tests too (see the count note below). - Corpus rename re-timed in release: still **0.35 s** over the 860-file corpus, `Ok((6, 18))` — matches the dev's claim, confirming the `watched_files` whole-word scan added for the collision fix did not regress the thing round 1's corpus number was checking. - One small count discrepancy, not worth blocking on: the Work log/Handshakes say "3 new tests" in `vlog_semantic`; `git diff` shows **4** new `fn`s in `crates/vlog_semantic/tests/semantics.rs` (`an_end_label_is_a_use_of_the_declaration_it_closes`, `an_end_label_never_attaches_to_a_same_named_declaration_elsewhere`, `a_label_whose_name_is_already_bound_in_the_scope_records_nothing`, `a_mismatched_end_label_records_nothing_rather_than_guessing`), and the test-run total (23, was 19) agrees with 4, not 3. Cosmetic — the count in prose just undercounts what's actually there. - All three gates: **pass, claims confirmed** (with the harmless count note above). ### Round-1 finding #1 (priority) — end labels: verified fixed Re-ran the exact round-1 reproductions (module/function/task/class/package/ named-`begin`) plus fork/join and interface, which round 1 didn't try: - `module`, `function`, `task`, `class`, `package`, named `begin`/`end`, `fork : f`/`join : f`, and `interface`/`endinterface` all now rename their end label along with the declaration. Confirmed for every construct in the dev's list, not just the ones the milestone spec named. - The masked-corruption case (a *different* construct's end label happens to spell the renamed name): built independently of the dev's own test — `module m; endmodule module other; endmodule : m` (the `: m` on `other` is already-illegal SV, since it doesn't match `other`) — renaming `m` leaves `other`'s `endmodule : m` **untouched**, with a warning naming it as "an end label vfmt could not attach to its declaration." Correct: it must never attach by name. - The "redeclaration binds no symbol" case: `wire m; initial begin : m ... end : m` (a block label colliding with an existing net name — pre-existing `vlog_semantic` collision-handling, not part of this round's diff). Renaming the wire correctly leaves the block's *end* label unedited and warned; nothing panicked or silently misattached. (The block's own *begin* label did move with the wire, because the pre-existing, untouched `declare_with_scope` collision logic treats it as a reference to the wire rather than a fresh declaration — that's inherited behavior from before M2, not a round-2 regression, and it's not this milestone's to fix.) **One dead end worth recording so it isn't retried**: I initially wrote a "nested same-named begin blocks" attack (`begin : x` inside another `begin : x`) nested *inside two `initial` statements* — `initial begin : x initial begin : x ... end : x end : x`. That is not legal SystemVerilog (a bare statement list cannot contain a second `initial`), and under that malformed input the wrong end label moved. I re-ran it with the legal form (a bare `begin` nested directly inside the outer block's statement list, no second `initial`) and it was correct in **both** directions — renaming the outer `x` moves only the outer `begin`/`end`, renaming the inner `x` moves only the inner pair, confirmed with the AST (`vlog_parser::parse_source_tolerant`) and the `Semantics` reference table directly: the inner end label (`Reference[0]`, span 67..68) resolves to `SymbolId(2)` (inner), the outer end label (`Reference[1]`, span 77..78) resolves to `SymbolId(1)` (outer) — exactly the "binding not lookup" design working as claimed. So: **nested same-named begin blocks are fine**; the earlier scare was my own invalid test input, not a defect. Flagging it in case another QA pass reaches for the same attack shape and hits the same red herring. **Verdict: fixed.** Every construct renames its end label with the declaration; the two documented can't-attach cases (mismatched label, redeclaration) fall through cleanly to a warning with no corruption or misattachment in either. ### Round-1 finding #2 — third-file collision: verified fixed Re-ran the exact round-1 repro (`sub.sv`/`child.sv`/`top.sv`, renaming `sub` to the name of a module `top.sv` already instantiates, where `top.sv` itself never spells `sub`): now correctly **refused** — `renaming `sub` to `child` would change what `child` means in top.sv; the rename was abandoned.` Matches the dev's own new regression test (`a_collision_with_a_third_file_that_never_spells_the_old_name_is_refused`). New attack for round 2: the same 3-file shape, but `sub.sv`'s only mention in `top.sv` is inside an `` `ifdef NEVER_DEFINED``-guarded arm (so the "collision" instantiation of `sub` is never even active). Still refused, for the right structural reason: `watched_files` is a **whole-word text search**, which does not know or care about `` `ifdef``, so `top.sv` is watched regardless of whether the arm is compiled — the safe, over-inclusive direction the README argues for. This is consistent, not a new bug: refusing a rename that's arguably "fine" because the colliding text lives in a dead `` `ifdef`` arm is the conservative failure mode, not a corruption risk. Also checked the no-false-refusal mirror the dev added (`a_third_file_that_merely_mentions_the_new_name_in_a_comment_is_not_a_collision`) by reading it — it exercises exactly the "over-inclusion costs an analysis, never a refusal" argument from the Verification story section. **Verdict: fixed**, and the fix's stated soundness argument (whole-word superset of "has a token spelling the name") holds up under an `` `ifdef`` attack that specifically tries to exploit the gap between "spells the name" and "the code path is actually reachable." ### Round-1 finding #3 — macro-invocation arguments: verified fixed Re-ran the round-1 repro (`` `define BUMP(x) x = x + 1`` / `` `BUMP(a)``, renaming `a`): now warned — "`a` appears in the arguments of the macro invocation `BUMP` at m.sv:4 and was left unchanged; a macro invocation is one opaque token to vfmt, which does not expand macros." Matches the dev's new test (`the_name_inside_a_macro_invocations_arguments_is_warned_about`). New attack for round 2: split the invocation across lines — `` `BUMP(\n a\n );``. Still warned, correctly, at the invocation's own starting line (4). `macro_use_warnings` scans the *whole opaque token's* text for the name as a whole word, so line-splitting inside the argument list doesn't defeat it (the token itself spans all the lines; the warning names where the invocation starts, which is reasonable — it's the only stable anchor an opaque token has). Also spot-checked `a_macro_invocation_in_an_ untouched_file_is_warned_about_too` in the dev's own suite, which is exactly the "warn even where nothing gets edited" half of the original finding. **Verdict: fixed.** ### Additional round-2 attacks — passed, no corruption found - **End label inside a `generate`/`for` loop body** (`for (...) begin : g ... end : g`): both the loop-body label and its end label rename correctly. (Note: this is a single source-level declaration — `vlog_semantic` does no elaboration, so there is no "genblk array" to worry about at this layer; the concern from the attack list doesn't apply to a static analyzer that never unrolls loops.) - **Whole-word matching edge cases**: target name `a` next to `a_b` (no false match, `a_b` untouched); target name `a` inside a based literal `8'ha` (the literal's preceding byte `h` is alphanumeric, so `contains_word` correctly does not treat it as a whole-word occurrence — confirmed the literal is byte-for-byte unchanged in the output). - **Escaped identifier `\a` vs. plain `a`**: renaming bare `a` left `\a` completely untouched, no warning. Checked why: `vlog_parser`'s lexer keeps the backslash in the token's text (`lexer.rs:304-317`), so `vlog_semantic` treats `\a` and `a` as two unrelated identifier spellings rather than the same identifier IEEE 1800 §5.6.2 says they denote. That is a pre-existing `vlog_semantic`/`vlog_parser` simplification with no connection to this round's diff (nothing in `bind.rs`/`resolve.rs`'s changes touches escaped identifiers), so I'm not filing it against M2 — noting it only so it's on record if the lead wants it filed against `vlog_semantic` separately. It is not a corruption risk either way: since the two are already unrelated symbols in this codebase's model, leaving `\a` alone is consistent with that model, not a violation of it. - **`fork ... join : f`** and **`interface ... endinterface : ifc`**: both rename correctly with their declarations (constructs the round-1 report didn't individually try). ### Summary (round 2) | Round-1 finding | Round-2 verdict | |---|---| | Stale end labels (priority finding) | **Fixed** — verified across every construct including fork/join and interface; masked-corruption case and the redeclaration edge case both still refuse cleanly | | Third-file collision (silent) | **Fixed** — verified with the original repro and a new `` `ifdef``-arm variant | | Macro-invocation arguments (silent) | **Fixed** — verified with the original repro and a multi-line invocation variant | | Gates (fmt/clippy/test) | **Pass**, 1085 tests, 0 failures, corpus rename still 0.35 s | | New attacks this round (genblk-in-loop, nested same-name labels, whole-word edge cases, escaped identifiers, fork/join, interface) | **Pass** — no new corruption found; one pre-existing, out-of-scope `vlog_semantic` observation noted (escaped identifiers), one invalid-syntax red herring from my own probe recorded so it isn't retried | No fixes applied this round — nothing found needed one. No probe files left in the tree (`crates/vlog_refactor/tests/qa_probe2.rs` and the throwaway `/tmp` AST/semantics probes were added, exercised, and removed). **Overall verdict: ship.** All three round-1 findings are genuinely closed, not just papered over — I attacked each fix's actual mechanism (whole-word text search's blind spots, opaque-token scanning across line breaks, binding vs. lookup under nesting) rather than re-running the original repro unchanged, and the fixes held. The `vlog_semantic` change is scoped exactly as narrow as the Handshakes section says (additive, one target variant, one helper, no `vlog_parser` change), and the remaining warned-not-fixed surface (hierarchical tails, `defparam` paths, mismatched/redeclared end labels) is honestly disclosed and consistent with the "vfmt does not preprocess / does not elaborate" boundary the umbrella already draws. ## Review **2026-08-24 — lead.** Reviewed the full diff after QA round 2's ship verdict; ran the three gates independently (1085 tests, 0 failures, clippy silent). The two-layer verification in `check.rs` is the right safety story and the watched-files superset argument is sound as written. The authorized `vlog_semantic` end-label handshake came out smaller and better than expected — `Target::Declaration` is binding-not-lookup, so a label can never attach to the wrong construct, and the parser needed nothing. QA's round-1 HIGHs (third-file collision, macro-argument silence) are closed at the mechanism level with regression tests from QA's own reproductions. Honest limitations (hierarchical tails, defparam paths, mismatched end labels, escaped-identifier equivalence) are documented, warned, and consistent with the no-preprocessing boundary. Accepted; M2 checked off in the umbrella plan and TODO.md §8. QA's escaped-identifier note (`\a` vs `a`, IEEE 1800 §5.6.2) is recorded as a pre-existing `vlog_semantic` simplification, not an M2 defect.