Refactoring M2: vlog_refactor crate + LSP rename

New crate vlog_refactor: rename any symbol vlog_semantic resolves, in-file
and cross-file, with whole-edit-or-nothing verification (token identity +
before/after resolution print over every file spelling either name).
End labels rename too via a new vlog_semantic Target::Declaration bound at
declaration time. Server ships prepareRename/rename; refusals are LSP
request errors, define-body/macro-argument/hierarchical-tail occurrences
warn instead of guessing. QA round 1 found two silent HIGHs (third-file
collision, macro-argument silence) — both closed with regression tests.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-24 05:12:53 -07:00
1 parent 315bbf23ab
commit 33f58196e3
22 files changed
+3726 -26

No files matched your search

Generated
+9
View File
@@ -242,6 +242,7 @@ dependencies = [
"vlog_formatter",
"vlog_linter",
"vlog_parser",
"vlog_refactor",
"vlog_semantic",
]
@@ -264,6 +265,14 @@ dependencies = [
name = "vlog_parser"
version = "0.2.0"
[[package]]
name = "vlog_refactor"
version = "0.2.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
]
[[package]]
name = "vlog_semantic"
version = "0.2.0"
+1
View File
@@ -3,6 +3,7 @@ resolver = "2"
members = [
"crates/vlog_parser",
"crates/vlog_semantic",
"crates/vlog_refactor",
"crates/vlog_formatter",
"crates/vlog_linter",
"crates/vfmt_core",
+1 -1
View File
@@ -583,7 +583,7 @@ section only tracks the milestones.
- [x] **M1 `filelist`** — EDA `.f` filelist defines the index scope
(`-f` nesting, `+incdir+`/`+define+` recorded, env vars); fallback:
workspace walk, then current file's directory when rootless.
- [ ] **M2 `refactor-rename`** — new crate `vlog_refactor`; LSP
- [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.
- [ ] **M3 `refactor-ports`** — add/remove/propagate module ports across
+1
View File
@@ -12,6 +12,7 @@ path = "src/main.rs"
vfmt_core = { path = "../vfmt_core" }
vlog_parser = { path = "../vlog_parser" }
vlog_semantic = { path = "../vlog_semantic" }
vlog_refactor = { path = "../vlog_refactor" }
vlog_formatter = { path = "../vlog_formatter" }
vlog_linter = { path = "../vlog_linter" }
lsp-server = { workspace = true }
+21 -5
View File
@@ -15,6 +15,7 @@ mod lint;
mod locate;
mod nav;
mod pairs;
mod rename;
mod server;
mod settings;
mod state;
@@ -28,9 +29,9 @@ use std::path::PathBuf;
use lsp_server::Connection;
use lsp_types::{
CodeActionKind, CodeActionOptions, CodeActionProviderCapability, InitializeParams, OneOf,
PositionEncodingKind, SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions,
SemanticTokensServerCapabilities, ServerCapabilities, TextDocumentSyncCapability,
TextDocumentSyncKind, WorkDoneProgressOptions,
PositionEncodingKind, RenameOptions, SemanticTokensFullOptions, SemanticTokensLegend,
SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities,
TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions,
};
use crate::server::Server;
@@ -71,6 +72,13 @@ fn capabilities() -> ServerCapabilities {
hover_provider: Some(lsp_types::HoverProviderCapability::Simple(true)),
document_symbol_provider: Some(OneOf::Left(true)),
workspace_symbol_provider: Some(OneOf::Left(true)),
// `prepareProvider` is what stops an editor from offering a rename the
// engine would refuse: the client asks first, and a refusal there costs
// the user nothing.
rename_provider: Some(OneOf::Right(RenameOptions {
prepare_provider: Some(true),
work_done_progress_options: WorkDoneProgressOptions::default(),
})),
// The kinds are listed rather than `Simple(true)` so a client can ask
// for one of them alone — which is how fix-on-save is configured.
code_action_provider: Some(CodeActionProviderCapability::Options(CodeActionOptions {
@@ -137,9 +145,17 @@ mod tests {
assert!(caps.workspace_symbol_provider.is_some());
assert!(caps.semantic_tokens_provider.is_some());
assert!(caps.code_action_provider.is_some());
// Deliberately absent until the engines exist — see the README.
assert!(caps.rename_provider.is_some());
// Deliberately absent until the engine exists — see the README.
assert!(caps.completion_provider.is_none());
assert!(caps.rename_provider.is_none());
}
#[test]
fn rename_advertises_prepare_so_the_editor_asks_before_offering() {
let Some(OneOf::Right(options)) = capabilities().rename_provider else {
panic!("rename must carry options, not a bare `true`");
};
assert_eq!(options.prepare_provider, Some(true));
}
#[test]
+224
View File
@@ -0,0 +1,224 @@
//! `textDocument/prepareRename` and `textDocument/rename`.
//!
//! Protocol only: every edit is computed by `vlog_refactor` over the same file
//! set the workspace index was built from, and this module turns the result
//! into a `WorkspaceEdit` (or the refusal into a request error). Nothing here
//! decides what may be renamed — a second opinion would be a second engine.
// A `WorkspaceEdit`'s `changes` map is keyed by `lsp_types::Uri`, and that
// type carries a `Cell` for its own parse cache — interior mutability clippy
// cannot tell apart from a key that can change its hash. The cache does not
// participate in `Hash` or `Eq`, and the map's shape is the protocol's, not
// ours.
#![allow(clippy::mutable_key_type)]
use std::collections::HashMap;
use lsp_types::{PrepareRenameResponse, TextEdit, Uri, WorkspaceEdit};
use vlog_parser::LineIndex;
use crate::convert::Positions;
use crate::state::Workspace;
use crate::uri::path_to_uri;
/// The identifier at `offset` and its current name, or the reason it cannot
/// be renamed. Returning the reason — rather than `null` — is what puts the
/// engine's sentence in the editor's rename box instead of a shrug.
pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Result<PrepareRenameResponse, String> {
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
let target = vlog_refactor::prepare_rename(&ws.sources(), &path, offset)?;
Ok(PrepareRenameResponse::RangeWithPlaceholder {
range: doc.positions().range(target.range),
placeholder: target.name,
})
}
/// The whole rename as a `WorkspaceEdit`, plus whatever the engine wants the
/// user told. An `Err` is the engine's own sentence, returned verbatim.
pub fn rename(
ws: &Workspace,
uri: &Uri,
offset: u32,
new_name: &str,
) -> Result<(WorkspaceEdit, Vec<String>), String> {
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
let refactoring = vlog_refactor::rename(&ws.sources(), &path, offset, new_name)?;
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
for (path, edits) in &refactoring.edits {
// The engine edited the text `sources()` handed it, which is the open
// buffer's when there is one — the same precedence every other
// cross-file answer uses, so the ranges are never computed against
// text nobody has.
let (Some(target), Some(text)) = (path_to_uri(path), ws.text_of(path)) else {
return Err(format!(
"vfmt could not address {} as a document; no edits were made.",
path.display()
));
};
let index = LineIndex::new(&text);
let positions = Positions::new(&text, &index);
changes.insert(
target,
edits
.iter()
.map(|edit| TextEdit {
range: positions.range(edit.range),
new_text: edit.new_text.clone(),
})
.collect(),
);
}
Ok((WorkspaceEdit::new(changes), refactoring.warnings))
}
const UNSAVED: &str = "vfmt can only rename inside a saved file.";
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::path::PathBuf;
use std::str::FromStr;
/// A scratch workspace root. Removed on drop.
struct Tree {
path: PathBuf,
}
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("vfmt_server_rename_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
fn write(&self, rel: &str, text: &str) -> PathBuf {
let path = self.path.join(rel);
fs::write(&path, text).expect("write");
path
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
fn at(text: &str, needle: &str) -> u32 {
text.find(needle).expect("needle present") as u32
}
const SUB: &str = "module sub (input logic clk);\nendmodule\n";
const TOP: &str = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n";
/// A two-file workspace with `top.sv` open.
fn opened(tree: &Tree) -> (Workspace, Uri) {
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", TOP);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), TOP.to_string());
(ws, uri)
}
#[test]
fn prepare_offers_the_identifier_and_its_placeholder() {
let tree = Tree::new("prepare");
let (ws, uri) = opened(&tree);
let response = prepare(&ws, &uri, at(TOP, "u_sub")).expect("renameable");
let PrepareRenameResponse::RangeWithPlaceholder { range, placeholder } = response else {
panic!("a placeholder is what an editor wants");
};
assert_eq!(placeholder, "u_sub");
assert_eq!(range.start.line, 1);
assert_eq!(range.start.character, 6);
assert_eq!(range.end.character, 11);
}
#[test]
fn prepare_declines_where_there_is_nothing_to_rename() {
let tree = Tree::new("prepare_no");
let (ws, uri) = opened(&tree);
let message = prepare(&ws, &uri, at(TOP, "module")).expect_err("a keyword");
assert!(message.contains("no symbol to rename"), "{message}");
}
#[test]
fn prepare_declines_in_an_untitled_buffer() {
let mut ws = Workspace::default();
let uri = Uri::from_str("untitled:Untitled-1").expect("uri");
ws.set_document(uri.clone(), "module m;\n wire a;\nendmodule\n".to_string());
assert_eq!(prepare(&ws, &uri, 16).expect_err("no path"), UNSAVED);
}
#[test]
fn a_rename_edits_every_file_that_names_the_symbol() {
let tree = Tree::new("cross");
let (ws, uri) = opened(&tree);
let (edit, warnings) = rename(&ws, &uri, at(TOP, "sub u_sub"), "child").expect("renames");
assert!(warnings.is_empty(), "{warnings:?}");
let changes = edit.changes.expect("changes");
assert_eq!(changes.len(), 2, "the declaration's file and this one");
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
let sub_edits = changes.get(&sub_uri).expect("sub.sv is edited");
assert_eq!(sub_edits.len(), 1);
assert_eq!(sub_edits[0].new_text, "child");
assert_eq!(sub_edits[0].range.start.line, 0);
assert_eq!(sub_edits[0].range.start.character, 7, "the name `sub`");
let top_edits = changes.get(&uri).expect("top.sv is edited");
assert_eq!(top_edits.len(), 1);
assert_eq!(top_edits[0].range.start.line, 1);
assert_eq!(top_edits[0].range.start.character, 2);
}
#[test]
fn a_refused_rename_returns_the_engines_sentence() {
let tree = Tree::new("refused");
let (ws, uri) = opened(&tree);
let message = rename(&ws, &uri, at(TOP, "u_sub"), "module").expect_err("a keyword");
assert!(message.contains("keyword"), "{message}");
}
#[test]
fn ranges_are_utf16_in_a_file_with_multi_byte_text() {
let tree = Tree::new("utf16");
let text = "module m;\n // é 🎉\n wire a;\n assign a = 1;\nendmodule\n";
let file = tree.write("m.sv", text);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text.to_string());
let (edit, _) = rename(&ws, &uri, at(text, "wire a") + 5, "sig").expect("renames");
let mut changes = edit.changes.expect("changes");
let edits = changes.remove(&uri).expect("this file");
assert_eq!(edits.len(), 2);
assert_eq!(edits[0].range.start.line, 2);
assert_eq!(edits[0].range.start.character, 7);
}
#[test]
fn an_open_buffer_beats_disk_when_the_rename_is_computed() {
let tree = Tree::new("buffer");
tree.write("sub.sv", SUB);
let top_path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
// The buffer instantiates `sub`; the file on disk does not.
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), TOP.to_string());
let (edit, _) = rename(&ws, &uri, at(TOP, "sub u_sub"), "child").expect("renames");
let changes = edit.changes.expect("changes");
assert_eq!(changes.get(&uri).map(Vec::len), Some(1), "the buffer's instantiation");
}
}
+44 -5
View File
@@ -15,8 +15,8 @@ use lsp_types::notification::{
};
use lsp_types::request::{
CodeActionRequest, DocumentHighlightRequest, DocumentSymbolRequest, Formatting, GotoDefinition,
HoverRequest, RangeFormatting, References, Request as _, SemanticTokensFullRequest,
WorkspaceSymbolRequest,
HoverRequest, PrepareRenameRequest, RangeFormatting, References, Rename, Request as _,
SemanticTokensFullRequest, WorkspaceSymbolRequest,
};
use lsp_types::{
CodeActionParams, DidChangeConfigurationParams, DidChangeTextDocumentParams,
@@ -24,14 +24,16 @@ use lsp_types::{
DocumentFormattingParams, DocumentHighlightParams, DocumentRangeFormattingParams,
DocumentSymbolParams, DocumentSymbolResponse, GotoDefinitionParams, GotoDefinitionResponse,
HoverParams, LogMessageParams, MessageType, Position, PublishDiagnosticsParams,
ReferenceParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams, Uri,
WorkspaceSymbolParams, WorkspaceSymbolResponse,
ReferenceParams, RenameParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams,
TextDocumentPositionParams, Uri, WorkspaceSymbolParams, WorkspaceSymbolResponse,
};
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::state::Workspace;
use crate::{code_action, diagnostics, format, hover, nav, pairs, settings, symbols, tokens};
use crate::{
code_action, diagnostics, format, hover, nav, pairs, rename, settings, symbols, tokens,
};
/// Everything the server owns.
pub struct Server {
@@ -173,6 +175,37 @@ impl Server {
None => Ok(Value::Null),
}
}),
// A rename the engine declines comes back as a request error
// carrying its own sentence, which is what an editor shows in the
// rename box. `prepareRename` declines the same way, so the box
// never opens for a rename that would then fail.
PrepareRenameRequest::METHOD => {
decode(request).and_then(|at: TextDocumentPositionParams| {
let (uri, position) = (at.text_document.uri, at.position);
let Some(offset) = self.offset(&uri, position) else {
return Ok(Value::Null);
};
match rename::prepare(&self.workspace, &uri, offset) {
Ok(response) => to_value(response),
Err(message) => Err(Failure::Request(message)),
}
})
}
Rename::METHOD => decode(request).and_then(|p: RenameParams| {
let new_name = p.new_name;
let at = p.text_document_position;
let (uri, position) = (at.text_document.uri, at.position);
let Some(offset) = self.offset(&uri, position) else {
return Ok(Value::Null);
};
match rename::rename(&self.workspace, &uri, offset, &new_name) {
Ok((edit, warnings)) => {
self.report_scope(warnings);
to_value(edit)
}
Err(message) => Err(Failure::Request(message)),
}
}),
WorkspaceSymbolRequest::METHOD => {
decode(request).and_then(|p: WorkspaceSymbolParams| {
to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols(
@@ -405,6 +438,9 @@ enum Failure {
MethodNotFound(String),
InvalidParams(String),
Internal(String),
/// The request was well-formed and the server declined it, with a reason
/// meant for the user — LSP's `RequestFailed`.
Request(String),
}
impl Failure {
@@ -418,6 +454,9 @@ impl Failure {
(lsp_server::ErrorCode::InvalidParams as i32, message)
}
Failure::Internal(message) => (lsp_server::ErrorCode::InternalError as i32, message),
Failure::Request(message) => {
(lsp_server::ErrorCode::RequestFailed as i32, format!("vfmt: {message}"))
}
};
Response::new_err(id, code, message)
}
+20 -5
View File
@@ -157,6 +157,25 @@ impl Workspace {
/// file that is gone, say. Rendering them is `server.rs`'s job; this
/// module speaks no protocol.
pub fn rebuild_index(&mut self) -> Vec<String> {
let (sources, warnings) = self.collect_sources();
self.index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
warnings
}
/// The in-scope files and their current text — what a refactoring reads.
///
/// The same list `rebuild_index` feeds the index, recomputed rather than
/// kept: a refactoring is a rare, user-initiated request, and a second
/// copy of the workspace in memory is a high price for saving one walk.
pub fn sources(&self) -> Vec<(PathBuf, String)> {
self.collect_sources().0
}
/// Read every in-scope file, with open buffers overriding disk.
fn collect_sources(&self) -> (Vec<(PathBuf, String)>, Vec<String>) {
let (files, warnings) = self.source_files();
let mut sources: Vec<(PathBuf, String)> = Vec::new();
for path in files {
@@ -171,11 +190,7 @@ impl Workspace {
sources.retain(|(p, _)| p != &path);
sources.push((path, doc.text.clone()));
}
self.index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
warnings
(sources, warnings)
}
/// The text of a workspace file: the open buffer if there is one, else
+93
View File
@@ -898,3 +898,96 @@ fn with_no_workspace_folder_the_open_files_own_directory_is_indexed() {
let _ = std::fs::remove_dir_all(&dir);
}
/// The two files a cross-file rename needs: a module and something that
/// instantiates it, with a macro of the same name so the warning path runs too.
const RENAME_SUB: &str = "`define sub 1\nmodule sub (input logic clk);\nendmodule\n";
const RENAME_TOP: &str = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n";
#[test]
fn prepare_rename_and_rename_round_trip_over_the_wire() {
let dir = temp_dir("rename");
std::fs::write(dir.join("sub.sv"), RENAME_SUB).expect("write");
let top = dir.join("top.sv");
std::fs::write(&top, RENAME_TOP).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", top.display());
let sub_uri = format!("file://{}", dir.join("sub.sv").display());
// Line 1, character 2 is the `sub` of the instantiation.
let at = |id: u32, method: &str, extra: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/{method}","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":2}}{extra}}}}}"#
))
};
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(RENAME_TOP).expect("json")
)),
at(2, "prepareRename", ""),
at(3, "rename", r#","newName":"child""#),
// A keyword is refused, and the editor is told why.
at(4, "rename", r#","newName":"module""#),
// `module` on line 0 is not a symbol: prepareRename must decline so
// the editor never opens its box.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/prepareRename","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":0,"character":1}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
let rename_provider = &initialize["result"]["capabilities"]["renameProvider"];
assert_eq!(rename_provider["prepareProvider"], serde_json::json!(true), "{rename_provider:#?}");
let prepared = messages.iter().find(|m| m["id"] == 2).expect("prepareRename response");
assert_eq!(prepared["result"]["placeholder"], "sub");
assert_eq!(prepared["result"]["range"]["start"]["character"], 2);
assert_eq!(prepared["result"]["range"]["end"]["character"], 5);
let renamed = messages.iter().find(|m| m["id"] == 3).expect("rename response");
let changes = &renamed["result"]["changes"];
assert_eq!(changes.as_object().expect("a changes map").len(), 2, "{changes:#?}");
assert_eq!(changes[&uri][0]["newText"], "child");
assert_eq!(changes[&uri][0]["range"]["start"]["line"], 1);
assert_eq!(changes[&sub_uri][0]["newText"], "child");
assert_eq!(changes[&sub_uri][0]["range"]["start"]["line"], 1, "the module declaration");
assert_eq!(changes[&sub_uri][0]["range"]["start"]["character"], 7);
assert_eq!(
changes[&sub_uri].as_array().expect("one edit").len(),
1,
"the `define of the same name is never edited"
);
// And it is reported rather than passed over in silence.
assert!(
messages.iter().any(|m| m["method"] == "window/logMessage"
&& m["params"]["message"].as_str().is_some_and(|s| s.contains("macro"))),
"the macro warning must reach the client: {messages:#?}"
);
let refused = messages.iter().find(|m| m["id"] == 4).expect("refusal response");
assert_eq!(refused["error"]["code"], -32803, "LSP's RequestFailed");
assert!(
refused["error"]["message"].as_str().is_some_and(|m| m.contains("keyword")),
"{refused:#?}"
);
assert!(refused["result"].is_null(), "a refusal carries no edits: {refused:#?}");
let declined = messages.iter().find(|m| m["id"] == 5).expect("prepareRename response");
assert_eq!(declined["error"]["code"], -32803);
assert!(
declined["error"]["message"].as_str().is_some_and(|m| m.contains("no symbol to rename")),
"{declined:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "vlog_refactor"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "Refactorings for Verilog/SystemVerilog, computed from resolved references"
[dependencies]
vlog_parser = { path = "../vlog_parser" }
vlog_semantic = { path = "../vlog_semantic" }
+431
View File
@@ -0,0 +1,431 @@
//! Whole-edit-or-nothing verification.
//!
//! Two independent checks, both run on the edited text in memory before any
//! edit is returned. **Token identity** catches lexical damage — an edit that
//! landed in a string, ate a comment, merged two tokens. **Resolution
//! identity** catches semantic damage — a name captured by an existing
//! declaration, or a cross-file use that quietly rebound. Neither implies the
//! other, and either one failing fails the entire refactoring.
//!
//! Nothing here touches `vlog_formatter` or its `verify.rs`: this is the same
//! contract, kept separately, so the formatter's safety net does not widen.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
use vlog_parser::{parse_source_tolerant, tokenize};
use vlog_semantic::{
analyze, resolve_external, ExternalResolutions, ExternalTarget, ReferenceId, Semantics,
SymbolKind, WorkspaceIndex,
};
use crate::rename::{contains_word, display, Scope};
use crate::{apply, Shift, TextEdit};
/// Check the whole edit, or refuse it whole.
pub(crate) fn verify(
scope: &mut Scope,
edits: &[(usize, Vec<TextEdit>)],
old_name: &str,
new_name: &str,
) -> Result<(), String> {
let edited: Vec<(PathBuf, String)> = edits
.iter()
.filter_map(|(i, edits)| {
let path = scope.path(*i)?.to_path_buf();
Some((path, apply(scope.text(*i)?, edits)))
})
.collect();
if edited.len() != edits.len() {
return Err(ABANDONED.to_string());
}
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()) };
tokens_match(before, text, &Shift::new(edits), new_name, path)?;
}
// 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
// that spells neither name cannot change meaning: an edit only adds and
// removes declarations of those two names, and a lookup of any other name
// cannot see them. A file that spells *either* is watched, which is what
// catches a third file whose existing `new_name` reference the rename
// would make ambiguous without touching a byte of it.
let watched = watched_files(scope, edits, old_name, new_name);
for &i in &watched {
if scope.analysis(i).is_none() {
return Err(ABANDONED.to_string());
}
}
let mut before: Vec<Print> = Vec::new();
for &i in &watched {
let (Some(path), Some(analysis)) = (scope.path(i), scope.cached(i)) else {
return Err(ABANDONED.to_string());
};
before.push(print(&analysis.semantics, &analysis.external, scope.index(), path, &shifts));
}
let after_index = rebuilt_index(scope, &edited);
for (n, &i) in watched.iter().enumerate() {
let Some(path) = scope.path(i) else { return Err(ABANDONED.to_string()) };
let text = match edited.iter().find(|(edited_path, _)| edited_path == path) {
Some((_, edited_text)) => edited_text.as_str(),
None => match scope.text(i) {
Some(text) => text,
None => return Err(ABANDONED.to_string()),
},
};
let semantics = analyze(&parse_source_tolerant(text).0, text);
let external = resolve_external(&semantics, &after_index);
let after = print(&semantics, &external, &after_index, path, &Shifts::default());
let Some(before) = before.get(n) else { return Err(ABANDONED.to_string()) };
if let Some(what) = before.first_difference(&after) {
return Err(format!(
"renaming `{old_name}` to `{new_name}` would change what {what} means in {}; the rename was abandoned.",
display(path)
));
}
}
Ok(())
}
/// Every file whose resolution the rename could move: the ones it edits, plus
/// the ones that spell either name as a whole word. A whole-word text search
/// is a sound *superset* of "has a token spelling the name" — a token spells
/// its name literally, so it is always found — and it errs by watching a few
/// files whose only mention is in a comment.
fn watched_files(
scope: &Scope,
edits: &[(usize, Vec<TextEdit>)],
old_name: &str,
new_name: &str,
) -> Vec<usize> {
let mut watched: Vec<usize> = edits.iter().map(|(i, _)| *i).collect();
for i in 0..scope.len() {
let Some(text) = scope.text(i) else { continue };
if watched.contains(&i) {
continue;
}
if contains_word(text, old_name) || contains_word(text, new_name) {
watched.push(i);
}
}
watched.sort_unstable();
watched
}
const ABANDONED: &str = "vfmt could not verify the rename, so it made no edits.";
/// The workspace index as it would be after the edits, so that a cross-file
/// capture is caught exactly the way an in-file one is.
fn rebuilt_index(scope: &Scope, edited: &[(PathBuf, String)]) -> WorkspaceIndex {
let sources = scope.sources().iter().map(|(path, text)| {
let text = edited
.iter()
.find(|(edited_path, _)| edited_path == path)
.map_or(*text, |(_, edited_text)| edited_text.as_str());
(path.to_path_buf(), text)
});
WorkspaceIndex::build(sources.collect::<Vec<_>>())
}
// ----------------------------------------------------------------------
// token identity
// ----------------------------------------------------------------------
/// The edited file must lex to the same tokens as the original, except that
/// the tokens the edits replaced now spell the new name.
fn tokens_match(
before: &str,
after: &str,
shift: &Shift,
new_name: &str,
path: &Path,
) -> Result<(), String> {
let refusal = |what: &str| {
format!("the rename would change {what} in {}; no edits were made.", display(path))
};
let (Ok(old), Ok(new)) = (tokenize(before), tokenize(after)) else {
return Err(format!(
"{} would no longer lex after the rename; no edits were made.",
display(path)
));
};
if old.len() != new.len() {
return Err(refusal("the token stream's shape"));
}
for (old, new) in old.iter().zip(&new) {
let edited = shift.is_edited(old.span);
let expected_text = if edited { new_name } else { old.text.as_str() };
let expected_kind = if edited { TokenKind::Ident } else { old.kind };
if new.kind != expected_kind || new.text != expected_text {
return Err(refusal(&format!("the token `{}`", old.text)));
}
if new.span != shift.map(old.span) {
return Err(refusal(&format!("where `{}` sits", old.text)));
}
if new.blank_before != old.blank_before {
return Err(refusal("the blank lines"));
}
let comments_kept = old.leading.len() == new.leading.len()
&& old.leading.iter().zip(&new.leading).all(|(a, b)| a.text == b.text)
&& old.trailing.as_ref().map(|c| &c.text) == new.trailing.as_ref().map(|c| &c.text);
if !comments_kept {
return Err(refusal("a comment"));
}
}
Ok(())
}
// ----------------------------------------------------------------------
// resolution identity
// ----------------------------------------------------------------------
/// Where the edits moved each touched file's bytes, keyed by path, plus the
/// name the edited occurrences now spell. The default value maps nothing,
/// which is what the post-edit side wants.
#[derive(Default)]
struct Shifts {
by_path: HashMap<PathBuf, Shift>,
new_name: String,
}
impl Shifts {
fn new(scope: &Scope, edits: &[(usize, Vec<TextEdit>)], new_name: &str) -> Shifts {
let mut by_path = HashMap::new();
for (i, edits) in edits {
if let Some(path) = scope.path(*i) {
by_path.insert(path.to_path_buf(), Shift::new(edits));
}
}
Shifts { by_path, new_name: new_name.to_string() }
}
fn map(&self, path: &Path, span: TextRange) -> TextRange {
self.by_path.get(path).map_or(span, |shift| shift.map(span))
}
/// The name an occurrence spells after the edits.
fn name(&self, path: &Path, span: TextRange, name: &str) -> String {
match self.by_path.get(path) {
Some(shift) if shift.is_edited(span) => self.new_name.clone(),
_ => name.to_string(),
}
}
}
/// What one name resolves to, said in terms that survive an edit: a file path
/// and a byte span, never a `SymbolId` or a `FileId` (both are positions in
/// tables that a re-analysis rebuilds).
#[derive(Debug, PartialEq, Eq)]
enum Anchor {
/// A declaration in the same file.
Local(u32, u32),
/// Declarations the workspace overlay answered with, in its own order.
External(Vec<(PathBuf, u32, u32)>),
/// Nothing resolves it — `NotFound`, an inherited candidate, or an
/// external candidate the workspace cannot answer.
Unresolved,
}
/// Everything one file declares and everything it names, with the spans and
/// anchors of the *edited* text. Built for the pre-edit analysis (shifted
/// forward) and for the post-edit one (as it is); the two must be equal.
#[derive(Debug, PartialEq, Eq, Default)]
struct Print {
declarations: Vec<(u32, u32, String, SymbolKind)>,
references: Vec<(u32, u32, String, Anchor)>,
}
impl Print {
/// The first entry the two prints disagree on, named for the user.
fn first_difference(&self, other: &Print) -> Option<String> {
if self.declarations.len() != other.declarations.len() {
return Some("the set of declarations".to_string());
}
for (a, b) in self.declarations.iter().zip(&other.declarations) {
if a != b {
return Some(format!("the declaration of `{}`", b.2));
}
}
if self.references.len() != other.references.len() {
return Some("the set of names".to_string());
}
for (a, b) in self.references.iter().zip(&other.references) {
if a != b {
return Some(format!("`{}`", b.2));
}
}
None
}
}
fn print(
semantics: &Semantics,
external: &ExternalResolutions,
index: &WorkspaceIndex,
path: &Path,
shifts: &Shifts,
) -> Print {
let mut declarations: Vec<(u32, u32, String, SymbolKind)> = semantics
.symbols()
.iter()
.map(|symbol| {
let span = shifts.map(path, symbol.name_span);
(span.start, span.end, shifts.name(path, symbol.name_span, &symbol.name), symbol.kind)
})
.collect();
declarations.sort_by_key(|d| (d.0, d.1));
let mut references: Vec<(u32, u32, String, Anchor)> = semantics
.references()
.iter()
.enumerate()
.map(|(id, reference)| {
let span = shifts.map(path, reference.name_span);
let anchor = anchor_of(semantics, external, index, path, shifts, id, reference);
(span.start, span.end, shifts.name(path, reference.name_span, &reference.name), anchor)
})
.collect();
references.sort_by_key(|r| (r.0, r.1));
Print { declarations, references }
}
fn anchor_of(
semantics: &Semantics,
external: &ExternalResolutions,
index: &WorkspaceIndex,
path: &Path,
shifts: &Shifts,
id: usize,
reference: &vlog_semantic::Reference,
) -> Anchor {
if let Some(symbol) = reference.resolved().and_then(|s| semantics.symbol(s)) {
let span = shifts.map(path, symbol.name_span);
return Anchor::Local(span.start, span.end);
}
let defs = match external.get(ReferenceId(id as u32)) {
Some(ExternalTarget::Resolved(def)) => std::slice::from_ref(def),
Some(ExternalTarget::Ambiguous(defs)) => defs.as_slice(),
_ => &[],
};
if defs.is_empty() {
return Anchor::Unresolved;
}
Anchor::External(
defs.iter()
.map(|def| {
let file = index.path(def.file).unwrap_or(Path::new("?")).to_path_buf();
let span = shifts.map(&file, def.name_span);
(file, span.start, span.end)
})
.collect(),
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rename::Scope;
const SOURCE: &str =
"module m;\n wire a;\n assign a = 1; // a stays\n initial $display(\"a\");\nendmodule\n";
/// The two edits a `a` → `sig` rename of `SOURCE` would produce.
fn rename_edits() -> Vec<TextEdit> {
let declaration = SOURCE.find("wire a").expect("decl") as u32 + 5;
let use_ = SOURCE.find("assign a").expect("use") as u32 + 7;
vec![
TextEdit {
range: TextRange::new(declaration, declaration + 1),
new_text: "sig".into(),
},
TextEdit { range: TextRange::new(use_, use_ + 1), new_text: "sig".into() },
]
}
fn attack(corrupted: &str) -> Result<(), String> {
let edits = rename_edits();
tokens_match(SOURCE, corrupted, &Shift::new(&edits), "sig", Path::new("/rtl/m.sv"))
}
#[test]
fn the_edit_the_engine_actually_produces_verifies() {
let honest = apply(SOURCE, &rename_edits());
assert_eq!(attack(&honest), Ok(()), "the real output must pass");
assert!(honest.contains("wire sig;") && honest.contains("// a stays"));
}
// The masked-corruption attacks: crafted (input, corrupted output) pairs
// that a sloppier check would forgive.
#[test]
fn an_edit_that_also_rewrote_a_comment_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replace("// a stays", "// sig stays");
assert!(attack(&corrupted).is_err(), "a comment must not change");
}
#[test]
fn an_edit_that_also_rewrote_a_string_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replace("\"a\"", "\"sig\"");
assert!(attack(&corrupted).is_err(), "a string literal must not change");
}
#[test]
fn an_edit_that_dropped_a_comment_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replace(" // a stays", "");
assert!(attack(&corrupted).is_err(), "comments are never dropped");
}
#[test]
fn an_edit_that_lost_or_gained_a_token_is_rejected() {
let dropped = apply(SOURCE, &rename_edits()).replace("assign sig = 1;", "assign sig = 1");
assert!(attack(&dropped).is_err(), "a lost `;`");
let gained = apply(SOURCE, &rename_edits()).replace("wire sig;", "wire sig, extra;");
assert!(attack(&gained).is_err(), "an invented declaration");
}
#[test]
fn an_edit_that_wrote_a_different_name_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replacen("wire sig", "wire other", 1);
assert!(attack(&corrupted).is_err(), "the edited token must spell the new name");
}
#[test]
fn an_edit_that_moved_an_untouched_token_is_rejected() {
// Whitespace only — the token stream is otherwise identical, which is
// exactly what a check comparing texts alone would wave through.
let corrupted = apply(SOURCE, &rename_edits()).replace("assign sig", "assign sig");
assert!(attack(&corrupted).is_err(), "a shifted span must be caught");
}
#[test]
fn an_edit_whose_result_does_not_lex_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replace("endmodule", "/* oops");
assert!(attack(&corrupted).is_err(), "an unlexable result is a failure, not output");
}
#[test]
fn a_rename_that_edited_the_declaration_but_not_its_uses_is_rejected() {
// The whole point of the resolution check: the tokens are perfect, the
// file still parses, and `a` now names nothing.
let files = vec![(PathBuf::from("/rtl/m.sv"), SOURCE.to_string())];
let mut scope = Scope::build(&files);
let declaration = SOURCE.find("wire a").expect("decl") as u32 + 5;
let partial = vec![(
0usize,
vec![TextEdit {
range: TextRange::new(declaration, declaration + 1),
new_text: "sig".into(),
}],
)];
let outcome = verify(&mut scope, &partial, "a", "sig");
assert!(outcome.is_err(), "a half-done rename must not verify: {outcome:?}");
}
}
+160
View File
@@ -0,0 +1,160 @@
//! Refactorings for Verilog/SystemVerilog.
//!
//! This crate plays the role of [rope](https://github.com/python-rope/rope) in
//! ruff's world: it turns "rename this" into a set of byte edits over the
//! files a workspace is made of. Every edit comes from a span
//! `vlog_semantic` resolved — there is no textual search-and-replace here —
//! and the whole edit is verified in memory before it is handed back: each
//! touched file is re-tokenized and re-analyzed, and the *entire* refactoring
//! is refused if anything but the renamed name moved.
//!
//! The crate does no I/O and speaks no protocol. The caller hands over the
//! in-scope files as `(path, text)` pairs — the same shape
//! `vlog_semantic::WorkspaceIndex::build` takes — and gets back a
//! [`RefactorEdit`] or a sentence explaining the refusal.
//!
//! See `docs/features/refactor-rename/README.md` for the refusal list and the
//! verification story.
mod check;
mod rename;
pub use rename::{prepare_rename, rename, RenameTarget};
use std::path::PathBuf;
use vlog_parser::span::TextRange;
/// One replacement inside one file: the bytes to replace, and what to write.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextEdit {
/// Byte range in the file's current text.
pub range: TextRange,
/// The text that replaces it.
pub new_text: String,
}
/// Everything a refactoring wants applied, plus what the user must be told
/// about what it deliberately left alone.
///
/// All-or-nothing: a `RefactorEdit` only ever exists after every one of its
/// edits verified *together*, so a caller applies all of them or none.
#[derive(Debug, Clone, Default)]
pub struct RefactorEdit {
/// Per file, sorted by path. Each file's edits are sorted by start
/// offset, non-overlapping, and none of them is empty.
pub edits: Vec<(PathBuf, Vec<TextEdit>)>,
/// Sentences for the user: occurrences the refactoring could not account
/// for (macro bodies, `endmodule :` labels). Informational only — a
/// result with warnings is still safe to apply.
pub warnings: Vec<String>,
}
impl RefactorEdit {
/// How many files the refactoring touches.
pub fn file_count(&self) -> usize {
self.edits.len()
}
/// How many replacements it makes in total.
pub fn edit_count(&self) -> usize {
self.edits.iter().map(|(_, edits)| edits.len()).sum()
}
/// The edits for one file, or nothing when it is untouched.
pub fn edits_for(&self, path: &std::path::Path) -> &[TextEdit] {
self.edits.iter().find(|(p, _)| p == path).map_or(&[], |(_, edits)| edits.as_slice())
}
}
/// Apply a file's edits to its text. The edits must be sorted and
/// non-overlapping, which is what [`RefactorEdit`] promises.
pub(crate) fn apply(text: &str, edits: &[TextEdit]) -> String {
let mut out = String::with_capacity(text.len());
let mut cursor = 0usize;
for edit in edits {
let start = edit.range.start as usize;
let end = edit.range.end as usize;
if start < cursor || end > text.len() {
continue;
}
out.push_str(text.get(cursor..start).unwrap_or(""));
out.push_str(&edit.new_text);
cursor = end;
}
out.push_str(text.get(cursor..).unwrap_or(""));
out
}
/// How an edited file's byte offsets moved. Every edit replaces one
/// identifier, so a name span either *is* an edit or is disjoint from all of
/// them — which is what makes the mapping exact rather than approximate.
#[derive(Debug, Clone, Default)]
pub(crate) struct Shift {
/// `(original span, replacement length)`, sorted by start.
edits: Vec<(TextRange, u32)>,
}
impl Shift {
pub(crate) fn new(edits: &[TextEdit]) -> Shift {
Shift { edits: edits.iter().map(|e| (e.range, e.new_text.len() as u32)).collect() }
}
/// Where a span of the original text lands in the edited text.
pub(crate) fn map(&self, span: TextRange) -> TextRange {
let mut start = span.start;
for (range, new_len) in &self.edits {
if range.start < span.start {
// Add before subtracting: the edits are disjoint and all sit
// before `span.start`, so this cannot go negative anyway, but
// an unsigned subtraction is not a place to rely on that.
start = start.saturating_add(*new_len).saturating_sub(range.len());
}
}
let len = match self.edits.iter().find(|(range, _)| *range == span) {
Some((_, new_len)) => *new_len,
None => span.len(),
};
TextRange::new(start, start + len)
}
/// True when this exact span is one of the replacements.
pub(crate) fn is_edited(&self, span: TextRange) -> bool {
self.edits.iter().any(|(range, _)| *range == span)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn edit(start: u32, end: u32, text: &str) -> TextEdit {
TextEdit { range: TextRange::new(start, end), new_text: text.to_string() }
}
#[test]
fn applying_edits_replaces_exactly_the_named_bytes() {
assert_eq!(apply("abc def abc", &[edit(0, 3, "xy"), edit(8, 11, "xy")]), "xy def xy");
}
#[test]
fn a_shift_maps_spans_around_and_onto_the_edits() {
let edits = vec![edit(0, 3, "xy"), edit(8, 11, "xy")];
let shift = Shift::new(&edits);
// The edited spans themselves take the replacement's length.
assert_eq!(shift.map(TextRange::new(0, 3)), TextRange::new(0, 2));
assert_eq!(shift.map(TextRange::new(8, 11)), TextRange::new(7, 9));
// A span between them slides by the first edit's delta only.
assert_eq!(shift.map(TextRange::new(4, 7)), TextRange::new(3, 6));
assert!(shift.is_edited(TextRange::new(0, 3)));
assert!(!shift.is_edited(TextRange::new(4, 7)));
}
#[test]
fn a_longer_replacement_shifts_forward() {
let edits = vec![edit(0, 1, "long")];
let shift = Shift::new(&edits);
assert_eq!(shift.map(TextRange::new(0, 1)), TextRange::new(0, 4));
assert_eq!(shift.map(TextRange::new(2, 3)), TextRange::new(5, 6));
}
}
+654
View File
@@ -0,0 +1,654 @@
//! Rename: the first refactoring, and the shape every later one follows.
//!
//! Read top-to-bottom, a rename is five steps: check the new name, resolve the
//! cursor to a *declaration*, collect every reference to that declaration in
//! the in-scope files, verify the whole edit in memory, and describe what was
//! deliberately left alone. Any step may refuse, and a refusal is a sentence
//! for the user, never a partial edit.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use vlog_parser::defines::DefineKind;
use vlog_parser::span::TextRange;
use vlog_parser::token::{is_keyword, TokenKind};
use vlog_parser::{parse_source_tolerant, tokenize, LineIndex};
use vlog_semantic::{
analyze, resolve_external, Def, ExternalResolutions, ExternalTarget, FileId, ReferenceId,
Resolution, Semantics, SymbolId, WorkspaceIndex,
};
use crate::{check, RefactorEdit, TextEdit};
/// The identifier a rename would act on: where it is, and what it spells.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenameTarget {
/// The identifier under the cursor, in the file the request named.
pub range: TextRange,
/// Its current name — the editor's rename-box placeholder.
pub name: String,
}
/// Whether the symbol at `offset` can be renamed, and where its identifier is.
///
/// This is LSP's `textDocument/prepareRename`: it applies every refusal that
/// does not need to know the new name, so an editor never opens a rename box
/// for a rename [`rename`] would then decline.
pub fn prepare_rename(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
) -> Result<RenameTarget, String> {
let mut scope = Scope::build(files);
let target = scope.locate(file, offset)?;
Ok(RenameTarget { range: target.cursor, name: target.name })
}
/// Rename the symbol at `offset` in `file` to `new_name`, across every file in
/// `files`.
///
/// `files` is the in-scope set — path and current text, open buffers already
/// overlaying disk — exactly what the workspace index was built from. Errors
/// are sentences meant for the user; an `Ok` result is verified and complete.
pub fn rename(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
new_name: &str,
) -> Result<RefactorEdit, String> {
check_new_name(new_name)?;
let mut scope = Scope::build(files);
let target = scope.locate(file, offset)?;
if target.name == new_name {
return Err(format!("`{new_name}` is the name it already has."));
}
let edits = scope.collect_edits(&target, new_name)?;
check::verify(&mut scope, &edits, &target.name, new_name)?;
let warnings = scope.warnings(&target, &edits);
let mut out: Vec<(PathBuf, Vec<TextEdit>)> = edits
.into_iter()
.filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), edits)))
.collect();
out.sort_by(|a, b| a.0.cmp(&b.0));
Ok(RefactorEdit { edits: out, warnings })
}
/// A new name must lex as exactly one identifier and must not be a keyword.
/// Anything else would be a textual edit that happens to look like a rename.
fn check_new_name(new_name: &str) -> Result<(), String> {
if new_name.is_empty() {
return Err("a new name cannot be empty.".to_string());
}
// Keywords first: they lex fine, just not as identifiers, and "`module`
// is a Verilog keyword" is a better sentence than "not an identifier".
if is_keyword(new_name) {
return Err(format!("`{new_name}` is a Verilog keyword."));
}
let refusal = format!("`{new_name}` is not a valid Verilog identifier.");
let Ok(tokens) = tokenize(new_name) else {
return Err(refusal);
};
// `tokenize` always ends the stream with an `Eof` token.
let [name, end] = tokens.as_slice() else {
return Err(refusal);
};
if end.kind != TokenKind::Eof || name.kind != TokenKind::Ident || name.text != new_name {
return Err(refusal);
}
// A macro usage lexes as an identifier that starts with a backtick.
if new_name.starts_with('`') {
return Err(refusal);
}
Ok(())
}
/// One file's two analysis layers, as `textDocument/definition` uses them.
pub(crate) struct Analysis {
pub(crate) semantics: Semantics,
pub(crate) external: ExternalResolutions,
}
/// What the cursor turned out to sit on, before the scope is borrowed again.
enum Found {
/// A declaration in the file the request named.
Here(SymbolId, TextRange),
/// A use whose declaration the workspace overlay must supply.
Elsewhere(String, TextRange, Option<ExternalTarget>),
}
/// The declaration a rename acts on, and where the cursor sat.
pub(crate) struct Target {
/// Index into [`Scope::sources`] of the file holding the declaration.
pub(crate) file: usize,
pub(crate) symbol: SymbolId,
pub(crate) name: String,
/// The identifier under the cursor, in the file the request named.
pub(crate) cursor: TextRange,
}
/// The in-scope files, the index built from them, and the analyses computed so
/// far. Analyses are built on demand: a rename usually needs a handful of the
/// workspace's files, and analyzing the rest would be pure cost.
pub(crate) struct Scope<'a> {
/// Path and text, sorted by path and deduplicated the way
/// `WorkspaceIndex::build` does it, so index `i` and `FileId(i)`'s texts
/// agree.
sources: Vec<(&'a Path, &'a str)>,
index: WorkspaceIndex,
/// Source index → the index's own file id.
file_ids: Vec<Option<FileId>>,
cache: HashMap<usize, Analysis>,
}
impl<'a> Scope<'a> {
pub(crate) fn build(files: &'a [(PathBuf, String)]) -> Scope<'a> {
let mut sources: Vec<(&Path, &str)> =
files.iter().map(|(p, t)| (p.as_path(), t.as_str())).collect();
// The same normalization `WorkspaceIndex::build` applies: a stable
// sort by path, then the first copy of a repeated path wins.
sources.sort_by(|a, b| a.0.cmp(b.0));
sources.dedup_by(|a, b| a.0 == b.0);
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.to_path_buf(), *t)));
let ids: HashMap<&Path, FileId> = index
.files()
.iter()
.enumerate()
.map(|(i, path)| (path.as_path(), FileId(i as u32)))
.collect();
let file_ids = sources.iter().map(|(path, _)| ids.get(path).copied()).collect();
Scope { sources, index, file_ids, cache: HashMap::new() }
}
pub(crate) fn len(&self) -> usize {
self.sources.len()
}
pub(crate) fn path(&self, i: usize) -> Option<&'a Path> {
self.sources.get(i).map(|(path, _)| *path)
}
pub(crate) fn text(&self, i: usize) -> Option<&'a str> {
self.sources.get(i).map(|(_, text)| *text)
}
pub(crate) fn sources(&self) -> &[(&'a Path, &'a str)] {
&self.sources
}
fn file_id(&self, i: usize) -> Option<FileId> {
self.file_ids.get(i).copied().flatten()
}
fn index_of(&self, path: &Path) -> Option<usize> {
self.sources.iter().position(|(p, _)| *p == path)
}
/// The two analysis layers for one file, computed on first use.
pub(crate) fn analysis(&mut self, i: usize) -> Option<&Analysis> {
let Scope { sources, index, cache, .. } = self;
let text = sources.get(i).map(|(_, text)| *text)?;
Some(cache.entry(i).or_insert_with(|| {
let semantics = analyze(&parse_source_tolerant(text).0, text);
let external = resolve_external(&semantics, index);
Analysis { semantics, external }
}))
}
/// One file's analysis, but only if it has already been computed — what
/// the verification pass reads while it also holds the index.
pub(crate) fn cached(&self, i: usize) -> Option<&Analysis> {
self.cache.get(&i)
}
/// Resolve a cursor position to the declaration a rename must act on.
///
/// The cursor may sit on the declaration itself, on a use in the same
/// file, or on a use whose declaration lives in another file — all three
/// end here, which is what makes renaming from a reference identical to
/// renaming from the declaration.
fn locate(&mut self, file: &Path, offset: u32) -> Result<Target, String> {
let Some(here) = self.index_of(file) else {
return Err(format!(
"{} is not one of the files vfmt indexes; nothing outside the project scope can be renamed.",
display(file)
));
};
// The analysis borrow is confined to this block so the two
// `declaration*` calls below can take the scope mutably again.
let found = {
let Some(analysis) = self.analysis(here) else {
return Err("the file could not be analyzed.".to_string());
};
let semantics = &analysis.semantics;
match semantics
.reference_id_at(offset)
.and_then(|id| Some((id, semantics.reference(id)?)))
{
Some((id, reference)) => {
let (name, cursor) = (reference.name.clone(), reference.name_span);
match &reference.resolution {
Resolution::Resolved(symbol) => Found::Here(*symbol, cursor),
Resolution::NotFound => return Err(format!(
"`{name}` is not resolved to any declaration, so vfmt cannot tell what renaming it would mean."
)),
Resolution::InheritedCandidate { base, .. } => return Err(format!(
"`{name}` could only come from the base class `{base}`, which vfmt does not resolve; renaming it would be a guess."
)),
Resolution::ExternalCandidate { .. } => {
Found::Elsewhere(name, cursor, analysis.external.get(id).cloned())
}
}
}
None => match semantics.symbol_at(offset) {
Some(symbol) => {
let cursor = semantics
.symbol(symbol)
.map_or_else(|| TextRange::empty(offset), |s| s.name_span);
Found::Here(symbol, cursor)
}
None => return Err(NOTHING_HERE.to_string()),
},
}
};
match found {
Found::Here(symbol, cursor) => self.declaration(here, symbol, cursor),
Found::Elsewhere(name, cursor, target) => {
self.declaration_across_files(&name, cursor, target)
}
}
}
/// A declaration in a known file, once the uniqueness rules have been
/// applied to it.
fn declaration(
&mut self,
file: usize,
symbol: SymbolId,
cursor: TextRange,
) -> Result<Target, String> {
let (name, name_span, at_file_scope) = {
let Some(analysis) = self.analysis(file) else {
return Err("the declaring file could not be analyzed.".to_string());
};
let Some(declaration) = analysis.semantics.symbol(symbol) else {
return Err(NOTHING_HERE.to_string());
};
(
declaration.name.clone(),
declaration.name_span,
declaration.scope == analysis.semantics.file_scope(),
)
};
if name_span.is_empty() {
return Err(format!(
"vfmt cannot find where `{name}` is spelled in its declaration, so it will not edit it."
));
}
if at_file_scope && self.index.units(&name).len() > 1 {
return Err(ambiguous(&name));
}
Ok(Target { file, symbol, name, cursor })
}
/// The declaration a cross-file use names, through the workspace overlay.
fn declaration_across_files(
&mut self,
name: &str,
cursor: TextRange,
target: Option<ExternalTarget>,
) -> Result<Target, String> {
let def = match target {
Some(ExternalTarget::Resolved(def)) => def,
Some(ExternalTarget::Ambiguous(_)) => return Err(ambiguous(name)),
_ => {
return Err(format!(
"`{name}` is declared outside the files vfmt indexes, so a rename here would only be half a rename."
))
}
};
let Some(file) = self.index.path(def.file).and_then(|p| self.index_of(p)) else {
return Err(format!("`{name}`'s declaring file is not in scope."));
};
let found = {
let Some(analysis) = self.analysis(file) else {
return Err("the declaring file could not be analyzed.".to_string());
};
analysis.semantics.symbol_at(def.name_span.start)
};
let Some(symbol) = found else {
return Err(format!("vfmt cannot locate the declaration of `{name}`."));
};
self.declaration(file, symbol, cursor)
}
/// Every occurrence of the declaration in every in-scope file: its own
/// name, its in-file uses, and the cross-file uses the overlay attributes
/// to it.
fn collect_edits(
&mut self,
target: &Target,
new_name: &str,
) -> Result<Vec<(usize, Vec<TextEdit>)>, String> {
let Some(def_file) = self.file_id(target.file) else {
return Err("the declaring file is not indexed.".to_string());
};
let Some(def_span) = self
.analysis(target.file)
.and_then(|a| a.semantics.symbol(target.symbol).map(|s| s.name_span))
else {
return Err(NOTHING_HERE.to_string());
};
let is_ours = |def: &Def| def.file == def_file && def.name_span == def_span;
let mut out: Vec<(usize, Vec<TextEdit>)> = Vec::new();
for i in 0..self.len() {
let Some(text) = self.text(i) else { continue };
// A file that does not spell the name cannot reference it: the
// semantic layer promises every `name_span` slices back to its
// own name. This is the prefilter that keeps a rename cheap.
if !text.contains(&target.name) {
continue;
}
let Some(analysis) = self.analysis(i) else { continue };
let mut spans: Vec<TextRange> = Vec::new();
if i == target.file {
spans.push(def_span);
spans.extend(
analysis.semantics.references_of(target.symbol).iter().map(|r| r.name_span),
);
}
for (id, reference) in analysis.semantics.references().iter().enumerate() {
if reference.name != target.name {
continue;
}
match analysis.external.get(ReferenceId(id as u32)) {
Some(ExternalTarget::Resolved(def)) if is_ours(def) => {
spans.push(reference.name_span)
}
Some(ExternalTarget::Ambiguous(defs)) if defs.iter().any(is_ours) => {
return Err(ambiguous(&target.name))
}
_ => {}
}
}
let edits = self.edits_from_spans(i, spans, &target.name, new_name)?;
if !edits.is_empty() {
out.push((i, edits));
}
}
if out.is_empty() {
return Err(format!("vfmt found nothing to rename for `{}`.", target.name));
}
Ok(out)
}
/// Turn occurrence spans into sorted, non-overlapping edits, refusing any
/// span that does not slice back to the name it claims.
fn edits_from_spans(
&self,
file: usize,
mut spans: Vec<TextRange>,
name: &str,
new_name: &str,
) -> Result<Vec<TextEdit>, String> {
let Some(text) = self.text(file) else { return Ok(Vec::new()) };
spans.retain(|s| !s.is_empty());
spans.sort_by_key(|s| (s.start, s.end));
spans.dedup();
let mut last_end = 0u32;
for (n, span) in spans.iter().enumerate() {
if text.get(span.as_range()) != Some(name) {
return Err(format!(
"vfmt found `{name}` recorded at bytes {}..{} of {}, which does not spell it; the rename was abandoned.",
span.start,
span.end,
display(self.path(file).unwrap_or(Path::new("?")))
));
}
if n > 0 && span.start < last_end {
return Err(
"two occurrences of the name overlap; the rename was abandoned.".to_string()
);
}
last_end = span.end;
}
Ok(spans
.into_iter()
.map(|range| TextEdit { range, new_text: new_name.to_string() })
.collect())
}
/// What the rename could not account for: the name inside `` `define``
/// text, inside a macro invocation's opaque token, and identifier
/// occurrences no reference was recorded for.
fn warnings(&mut self, target: &Target, edits: &[(usize, Vec<TextEdit>)]) -> Vec<String> {
let mut warnings = self.macro_warnings(&target.name);
// Macro *invocations* are scanned in every file that spells the name,
// not only the edited ones: `` `BUMP(a) `` in a file the rename never
// touches still expands to the old name.
for i in 0..self.len() {
warnings.extend(self.macro_use_warnings(i, &target.name));
}
for (i, edits) in edits {
warnings.extend(self.unaccounted_warnings(*i, &target.name, edits));
}
warnings.dedup();
warnings
}
/// vfmt does not preprocess, so a name that is also a macro name, or that
/// appears in a macro body, is left exactly as written — and said so.
fn macro_warnings(&self, name: &str) -> Vec<String> {
let mut out = Vec::new();
for i in 0..self.len() {
let (Some(text), Some(file)) = (self.text(i), self.file_id(i)) else { continue };
if !text.contains(name) {
continue;
}
let Some(defines) = self.index.defines(file) else { continue };
let lines = LineIndex::new(text);
let where_ = display(self.path(i).unwrap_or(Path::new("?")));
for define in defines.entries() {
let line = lines.line_col(define.span.start).0;
if define.name == name {
let what = match define.kind {
DefineKind::Define => "defined",
DefineKind::Undef => "undefined",
};
out.push(format!(
"`{name}` is also a macro {what} at {where_}:{line}; macro names and macro uses are never renamed."
));
} else if contains_word(&define.body, name) {
out.push(format!(
"`{name}` appears in the body of macro `{}` at {where_}:{line} and was left unchanged; vfmt does not preprocess.",
define.name
));
}
}
}
out
}
/// A macro invocation lexes as **one opaque token**, arguments included,
/// so the name inside `` `BUMP(a) `` is invisible to the semantic layer and
/// cannot be edited. It can be seen, though — and silence would be worse
/// than a warning, because the expansion still spells the old name.
fn macro_use_warnings(&self, file: usize, name: &str) -> Vec<String> {
let (Some(text), Some(path)) = (self.text(file), self.path(file)) else {
return Vec::new();
};
if !text.contains(name) {
return Vec::new();
}
let Ok(tokens) = tokenize(text) else { return Vec::new() };
let lines = LineIndex::new(text);
let mut out = Vec::new();
for token in tokens.iter().filter(|t| t.is_macro()) {
// The macro's own name is reported by `macro_warnings` when the
// workspace defines it; what is new here is the argument text.
let Some(arguments) = token.text.split_once('(').map(|(_, rest)| rest) else {
continue;
};
if !contains_word(arguments, name) {
continue;
}
let macro_name = macro_name_of(&token.text);
out.push(format!(
"`{name}` appears in the arguments of the macro invocation `{macro_name}` at {}:{} and was left unchanged; a macro invocation is one opaque token to vfmt, which does not expand macros.",
display(path),
lines.line_col(token.span.start).0
));
}
out
}
/// Identifier tokens spelling the name that no declaration and no
/// reference covers — grouped by *why* vfmt could not attribute them, so
/// the user is told where to look rather than guessing.
fn unaccounted_warnings(&mut self, file: usize, name: &str, edits: &[TextEdit]) -> Vec<String> {
let (Some(text), Some(path)) = (self.text(file), self.path(file)) else {
return Vec::new();
};
let Some(analysis) = self.analysis(file) else { return Vec::new() };
let mut covered: Vec<TextRange> =
analysis.semantics.symbols().iter().map(|s| s.name_span).collect();
covered.extend(analysis.semantics.references().iter().map(|r| r.name_span));
covered.extend(edits.iter().map(|e| e.range));
let Ok(tokens) = tokenize(text) else { return Vec::new() };
let lines = LineIndex::new(text);
// Reason → the lines it happened on, in source order.
let mut groups: Vec<(&'static str, Vec<u32>)> = Vec::new();
for (i, token) in tokens.iter().enumerate() {
if token.kind != TokenKind::Ident || token.text != name {
continue;
}
if covered.contains(&token.span) {
continue;
}
let reason = stray_reason(&tokens, i);
let line = lines.line_col(token.span.start).0;
match groups.iter_mut().find(|(r, _)| *r == reason) {
Some((_, at)) => at.push(line),
None => groups.push((reason, vec![line])),
}
}
groups
.into_iter()
.map(|(reason, at)| {
let at = at.iter().map(u32::to_string).collect::<Vec<_>>().join(", ");
format!(
"`{name}` also occurs in {} at line(s) {at} as {reason}; vfmt records no reference there, so it was left unchanged.",
display(path)
)
})
.collect()
}
/// The workspace index the edits were computed against.
pub(crate) fn index(&self) -> &WorkspaceIndex {
&self.index
}
}
const NOTHING_HERE: &str = "there is no symbol to rename at this position.";
fn ambiguous(name: &str) -> String {
format!(
"`{name}` is declared in more than one indexed file; vfmt will not guess which declaration this rename means."
)
}
/// Why an identifier spelling the name is not a reference vfmt can edit,
/// read off its neighbours in the token stream. Naming the actual construct
/// is the difference between a warning the user can act on and one they have
/// to decode.
fn stray_reason(tokens: &[vlog_parser::token::Token], i: usize) -> &'static str {
let before = i.checked_sub(1).and_then(|n| tokens.get(n));
if before.is_some_and(|t| t.is_sym(".")) {
return "a hierarchical or member tail, which vfmt does not resolve";
}
if before.is_some_and(|t| t.is_sym(":")) {
let keyword = i.checked_sub(2).and_then(|n| tokens.get(n));
// `endmodule : m` / `end : blk` where the label could not be attached
// to its declaration — a name already bound in the enclosing scope,
// or a label that does not spell the declared name.
if keyword.is_some_and(|t| t.kind == TokenKind::Keyword && t.text.starts_with("end")) {
return "an end label vfmt could not attach to its declaration";
}
return "a label vfmt records no declaration for";
}
"an occurrence vfmt cannot attribute to any declaration"
}
/// The macro name of an invocation token, as a message spells it:
/// `` `BUMP(a) `` → `BUMP`. The leading backtick is dropped so the name reads
/// the same way the `` `define`` warnings spell it.
fn macro_name_of(invocation: &str) -> &str {
let name = match invocation.split_once('(') {
Some((name, _)) => name.trim_end(),
None => invocation,
};
name.strip_prefix('`').unwrap_or(name)
}
/// How a file is named in a message: its file name, because an absolute path
/// in a rename box is unreadable.
pub(crate) fn display(path: &Path) -> String {
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()
}
/// True when `needle` occurs in `haystack` as a whole identifier — the test
/// macro text and the verification pass's file filter get, where there is no
/// token stream to consult (or where the token is opaque).
pub(crate) fn contains_word(haystack: &str, needle: &str) -> bool {
if needle.is_empty() {
return false;
}
let bytes = haystack.as_bytes();
let mut from = 0;
while let Some(hit) = haystack.get(from..).and_then(|s| s.find(needle)) {
let start = from + hit;
let end = start + needle.len();
let before = start.checked_sub(1).and_then(|i| bytes.get(i)).copied();
let after = bytes.get(end).copied();
if !before.is_some_and(is_name_byte) && !after.is_some_and(is_name_byte) {
return true;
}
from = start + 1;
}
false
}
fn is_name_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_new_name_must_be_one_plain_identifier() {
assert!(check_new_name("ok_name").is_ok());
assert!(check_new_name("_x1$").is_ok());
assert!(check_new_name("").is_err(), "empty");
assert!(check_new_name("two names").is_err(), "two tokens");
assert!(check_new_name("a+b").is_err(), "an expression");
assert!(check_new_name("module").is_err(), "a keyword");
assert!(check_new_name("1234").is_err(), "a number");
assert!(check_new_name("`MACRO").is_err(), "a macro use");
assert!(check_new_name("a ").is_err(), "trailing space");
}
#[test]
fn whole_word_search_ignores_substrings() {
assert!(contains_word("a + WIDTH - 1", "WIDTH"));
assert!(!contains_word("a + MY_WIDTH - 1", "WIDTH"));
assert!(!contains_word("WIDTHS", "WIDTH"));
assert!(contains_word("`WIDTH", "WIDTH"), "a macro use of the name still counts");
assert!(!contains_word("x", ""));
}
}
+129
View File
@@ -0,0 +1,129 @@
//! Real-RTL acceptance (`corpus/`, fetched by `tools/corpus_fetch.sh`).
//!
//! Two properties, neither of them a percentage: a rename over a real
//! workspace either edits every occurrence or refuses with a sentence — it
//! never panics and never produces an edit that does not slice back to the
//! name — and asking at offsets all over a real file answers without panicking.
//! Skipped when the corpus is not checked out.
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Instant;
use vlog_refactor::{prepare_rename, rename};
fn corpus() -> Option<Vec<PathBuf>> {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !root.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return None;
}
let mut files = Vec::new();
collect(&root, &mut files);
files.sort();
Some(files)
}
fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect(&path, out);
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) {
out.push(path);
}
}
}
fn read(files: &[PathBuf]) -> Vec<(PathBuf, String)> {
files.iter().filter_map(|p| Some((p.clone(), fs::read_to_string(p).ok()?))).collect()
}
#[test]
fn a_rename_over_the_whole_corpus_answers_or_refuses() {
let Some(files) = corpus() else { return };
let sources = read(&files);
assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog");
// One real cross-file target: a module every workspace instantiates.
let Some((path, text)) =
sources.iter().find(|(p, _)| p.file_name().is_some_and(|n| n == "prim_fifo_sync.sv"))
else {
eprintln!("prim_fifo_sync.sv not in this corpus — skipping the cross-file probe");
return;
};
let offset = text.find("module prim_fifo_sync").map(|i| i + 7).expect("the module's name");
let started = Instant::now();
let outcome = rename(&sources, path, offset as u32, "prim_fifo_sync_renamed");
let elapsed = started.elapsed();
println!(
"corpus rename over {} files: {:?} in {:.2}s",
sources.len(),
outcome.as_ref().map(|e| (e.file_count(), e.edit_count())).map_err(String::as_str),
elapsed.as_secs_f64()
);
match outcome {
Ok(edit) => {
// Every edit must cover exactly the old name in the file it names.
for (file, edits) in &edit.edits {
let text = sources
.iter()
.find(|(p, _)| p == file)
.map(|(_, t)| t.as_str())
.expect("an edited file is an in-scope file");
for e in edits {
assert_eq!(
text.get(e.range.as_range()),
Some("prim_fifo_sync"),
"{}: an edit that does not cover the name",
file.display()
);
}
}
assert!(edit.file_count() > 1, "this module is instantiated in other files");
}
// A refusal is a correct answer too — the corpus really does declare
// some names twice — but it must be a sentence, not a panic.
Err(message) => assert!(message.ends_with('.'), "a refusal must read as a sentence"),
}
assert!(elapsed.as_secs() < 30, "a rename must stay interactive: {elapsed:?}");
}
#[test]
fn asking_at_offsets_all_over_a_real_file_never_panics() {
let Some(files) = corpus() else { return };
// One small file, alone in its scope: the question is robustness at odd
// offsets, not cross-file resolution, and every probe rebuilds an index.
let Some((path, text)) = files
.iter()
.filter_map(|p| Some((p, fs::read_to_string(p).ok()?)))
.find(|(_, text)| (2_000..8_000).contains(&text.len()) && text.contains("endmodule"))
else {
eprintln!("no small file in this corpus — skipping");
return;
};
let sources = vec![(path.clone(), text.clone())];
// A few hundred offsets spread over the file: the point is to hit
// whitespace, punctuation, mid-token, mid-comment and mid-directive
// positions, not to be exhaustive.
let step = (text.len() / 300).max(1);
let mut probed = 0usize;
let mut renameable = 0usize;
for offset in (0..text.len() as u32).step_by(step) {
probed += 1;
if prepare_rename(&sources, path, offset).is_ok() {
renameable += 1;
}
}
println!(
"{}: {renameable} of {probed} probed offsets are renameable",
path.file_name().and_then(|n| n.to_str()).unwrap_or("?")
);
assert!(renameable > 0, "a real file must have something renameable in it");
}
+841
View File
@@ -0,0 +1,841 @@
//! What rename does, and — more importantly — what it refuses to do.
//!
//! Every test drives the public API only: a little in-memory workspace of
//! `(path, text)` pairs, a cursor offset, a new name. Cursors are written as
//! `at(text, "after this", "name")` — the first whole-word occurrence of
//! `name` at or after `after this` — so a test says which occurrence it means
//! instead of counting bytes.
use std::path::{Path, PathBuf};
use vlog_refactor::{prepare_rename, rename, RefactorEdit};
/// A workspace of `(file name, text)` pairs, rooted at a fake directory.
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
files.iter().map(|(name, text)| (PathBuf::from("/rtl").join(name), text.to_string())).collect()
}
fn path(name: &str) -> PathBuf {
PathBuf::from("/rtl").join(name)
}
/// The offset of the first whole-word `name` at or after `prefix`.
fn at(text: &str, prefix: &str, name: &str) -> u32 {
let from = match prefix.is_empty() {
true => 0,
false => {
text.find(prefix).unwrap_or_else(|| panic!("`{prefix}` is not in the text"))
+ prefix.len()
}
};
let is_word = |b: Option<&u8>| b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
let bytes = text.as_bytes();
let mut search = from;
while let Some(hit) = text.get(search..).and_then(|s| s.find(name)) {
let start = search + hit;
let end = start + name.len();
if !is_word(start.checked_sub(1).and_then(|i| bytes.get(i))) && !is_word(bytes.get(end)) {
return start as u32;
}
search = start + 1;
}
panic!("`{name}` does not occur after `{prefix}`");
}
/// Rename in a one-file workspace and return the resulting text.
fn rename_one(text: &str, prefix: &str, name: &str, new_name: &str) -> Result<String, String> {
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, prefix, name), new_name)?;
Ok(apply(text, &edit, &path("m.sv")))
}
/// Apply a refactoring's edits for one file.
fn apply(text: &str, edit: &RefactorEdit, file: &Path) -> String {
let mut out = String::new();
let mut cursor = 0usize;
for e in edit.edits_for(file) {
out.push_str(&text[cursor..e.range.start as usize]);
out.push_str(&e.new_text);
cursor = e.range.end as usize;
}
out.push_str(&text[cursor..]);
out
}
// ----------------------------------------------------------------------
// every symbol kind
// ----------------------------------------------------------------------
#[test]
fn a_net_is_renamed_at_its_declaration_and_at_every_use() {
let text = "module m;\n wire a;\n assign a = 1;\n assign b = a & a;\nendmodule\n";
assert_eq!(
rename_one(text, "wire", "a", "sig").expect("renames"),
"module m;\n wire sig;\n assign sig = 1;\n assign b = sig & sig;\nendmodule\n"
);
}
#[test]
fn renaming_from_a_use_is_the_same_as_renaming_from_the_declaration() {
let text = "module m;\n wire a;\n assign a = 1;\nendmodule\n";
let from_declaration = rename_one(text, "wire", "a", "sig").expect("renames");
let from_use = rename_one(text, "assign", "a", "sig").expect("renames");
assert_eq!(from_declaration, from_use);
assert!(from_use.contains("wire sig;"));
}
#[test]
fn a_variable_a_parameter_a_localparam_and_a_genvar_all_rename() {
let text = concat!(
"module m #(parameter int W = 4) ();\n",
" localparam int K = W;\n",
" logic [W-1:0] v;\n",
" genvar g;\n",
" generate for (g = 0; g < K; g = g + 1) begin : b\n",
" assign v[g] = 1'b0;\n",
" end endgenerate\n",
"endmodule\n"
);
let renamed = rename_one(text, "parameter int", "W", "WIDTH").expect("parameter");
assert!(renamed.contains("parameter int WIDTH = 4"), "{renamed}");
assert!(renamed.contains("localparam int K = WIDTH;"), "{renamed}");
assert!(renamed.contains("logic [WIDTH-1:0] v;"), "{renamed}");
let renamed = rename_one(text, "localparam int", "K", "COUNT").expect("localparam");
assert!(renamed.contains("localparam int COUNT = W;"), "{renamed}");
assert!(renamed.contains("g < COUNT;"), "{renamed}");
let renamed = rename_one(text, "logic [W-1:0]", "v", "vec").expect("variable");
assert!(renamed.contains("logic [W-1:0] vec;"), "{renamed}");
assert!(renamed.contains("assign vec[g]"), "{renamed}");
let renamed = rename_one(text, "genvar", "g", "gi").expect("genvar");
assert!(renamed.contains("genvar gi;"), "{renamed}");
assert!(renamed.contains("for (gi = 0; gi < K; gi = gi + 1)"), "{renamed}");
assert!(renamed.contains("assign v[gi]"), "{renamed}");
}
#[test]
fn an_ansi_port_renames_everywhere_it_is_used() {
let text = "module m (input logic clk, output logic q);\n assign q = clk;\nendmodule\n";
let renamed = rename_one(text, "input logic", "clk", "clock").expect("renames");
assert_eq!(
renamed,
"module m (input logic clock, output logic q);\n assign q = clock;\nendmodule\n"
);
}
#[test]
fn a_non_ansi_port_renames_in_the_header_and_in_its_declaration() {
// The body declaration is a *reference* to the header port (the semantic
// layer's redeclaration rule), so both must move together.
let text = "module m (a, b);\n input a;\n output b;\n assign b = a;\nendmodule\n";
let renamed = rename_one(text, "module m (", "a", "in_a").expect("renames");
assert_eq!(
renamed,
"module m (in_a, b);\n input in_a;\n output b;\n assign b = in_a;\nendmodule\n"
);
}
#[test]
fn a_typedef_and_its_enum_variants_rename_independently() {
let text = concat!(
"module m;\n",
" typedef enum logic [1:0] { IDLE, BUSY } state_e;\n",
" state_e s;\n",
" assign s = IDLE;\n",
"endmodule\n"
);
let renamed = rename_one(text, "BUSY }", "state_e", "fsm_state_e").expect("typedef");
assert!(renamed.contains("} fsm_state_e;"), "{renamed}");
assert!(renamed.contains(" fsm_state_e s;"), "{renamed}");
assert!(renamed.contains("IDLE, BUSY"), "the variants are untouched: {renamed}");
let renamed = rename_one(text, "{", "IDLE", "ST_IDLE").expect("enum variant");
assert!(renamed.contains("{ ST_IDLE, BUSY }"), "{renamed}");
assert!(renamed.contains("assign s = ST_IDLE;"), "{renamed}");
}
#[test]
fn a_struct_member_renames_where_it_is_declared() {
let text = concat!(
"module m;\n",
" typedef struct packed { logic valid; logic [7:0] data; } bus_t;\n",
" bus_t b;\n",
"endmodule\n"
);
let renamed = rename_one(text, "packed {", "valid", "vld").expect("struct member");
assert!(renamed.contains("logic vld;"), "{renamed}");
}
#[test]
fn a_function_a_task_and_their_arguments_rename() {
let text = concat!(
"module m;\n",
" function automatic int twice(input int v);\n",
" twice = v + v;\n",
" endfunction\n",
" task do_it(input int n);\n",
" endtask\n",
" initial begin\n",
" do_it(twice(3));\n",
" end\n",
"endmodule\n"
);
let renamed = rename_one(text, "automatic int", "twice", "doubled").expect("function");
assert!(renamed.contains("int doubled(input int v)"), "{renamed}");
assert!(renamed.contains("doubled = v + v;"), "{renamed}");
assert!(renamed.contains("do_it(doubled(3));"), "{renamed}");
let renamed = rename_one(text, "twice(input int", "v", "value").expect("argument");
assert!(renamed.contains("twice(input int value)"), "{renamed}");
assert!(renamed.contains("twice = value + value;"), "{renamed}");
let renamed = rename_one(text, "task", "do_it", "run").expect("task");
assert!(renamed.contains("task run(input int n);"), "{renamed}");
assert!(renamed.contains("run(twice(3));"), "{renamed}");
}
#[test]
fn an_instance_name_renames() {
let text = concat!(
"module sub (input clk);\nendmodule\n",
"module top;\n wire c;\n sub u_sub (.clk(c));\nendmodule\n"
);
let renamed = rename_one(text, "module top", "u_sub", "u_child").expect("instance");
assert!(renamed.contains("sub u_child (.clk(c));"), "{renamed}");
}
#[test]
fn a_class_and_its_members_rename() {
let text = concat!(
"package p;\n",
" class item;\n",
" int count;\n",
" function int get();\n",
" return count;\n",
" endfunction\n",
" endclass\n",
"endpackage\n"
);
let renamed = rename_one(text, "int", "count", "n_items").expect("class member");
assert!(renamed.contains("int n_items;"), "{renamed}");
assert!(renamed.contains("return n_items;"), "{renamed}");
}
#[test]
fn a_named_block_label_renames() {
let text = concat!(
"module m;\n",
" initial begin : setup\n",
" #1;\n",
" end\n",
" initial disable setup;\n",
"endmodule\n"
);
let renamed = rename_one(text, "begin :", "setup", "init_block").expect("block label");
assert!(renamed.contains("begin : init_block"), "{renamed}");
assert!(renamed.contains("disable init_block;"), "{renamed}");
}
// ----------------------------------------------------------------------
// cross-file
// ----------------------------------------------------------------------
#[test]
fn a_module_name_renames_in_every_instantiation_in_every_file() {
let sub = "module sub (input clk);\nendmodule\n";
let top = "module top;\n wire c;\n sub u0 (.clk(c));\n sub u1 (.clk(c));\nendmodule\n";
let other = "module other;\n sub u2 ();\nendmodule\n";
let files = workspace(&[("sub.sv", sub), ("top.sv", top), ("other.sv", other)]);
let edit = rename(&files, &path("sub.sv"), at(sub, "module", "sub"), "child").expect("renames");
assert_eq!(edit.file_count(), 3, "all three files");
assert_eq!(edit.edit_count(), 4, "the declaration and three instantiations");
assert_eq!(apply(sub, &edit, &path("sub.sv")), "module child (input clk);\nendmodule\n");
assert!(apply(top, &edit, &path("top.sv")).contains("child u0 (.clk(c));"));
assert!(apply(other, &edit, &path("other.sv")).contains("child u2 ();"));
// Sorted by path, and each file's edits sorted by offset.
let paths: Vec<_> = edit.edits.iter().map(|(p, _)| p.clone()).collect();
let mut sorted = paths.clone();
sorted.sort();
assert_eq!(paths, sorted, "files come back in path order");
for (_, edits) in &edit.edits {
assert!(edits.windows(2).all(|w| w[0].range.end <= w[1].range.start), "sorted, disjoint");
}
}
#[test]
fn renaming_a_module_from_one_of_its_instantiations_updates_the_declaration_too() {
let sub = "module sub (input clk);\nendmodule\n";
let top = "module top;\n sub u0 (.clk(1'b0));\nendmodule\n";
let files = workspace(&[("sub.sv", sub), ("top.sv", top)]);
let edit = rename(&files, &path("top.sv"), at(top, "", "sub"), "child").expect("renames");
assert_eq!(apply(sub, &edit, &path("sub.sv")), "module child (input clk);\nendmodule\n");
assert!(apply(top, &edit, &path("top.sv")).contains("child u0"));
}
#[test]
fn a_package_member_renames_at_every_import_and_scope_use() {
let pkg = "package p;\n localparam int WIDTH = 8;\nendpackage\n";
let a = "module a;\n import p::*;\n wire [WIDTH-1:0] bus;\nendmodule\n";
let b = "module b;\n wire [p::WIDTH-1:0] bus;\nendmodule\n";
let c = "module c;\n import p::WIDTH;\n wire [WIDTH-1:0] bus;\nendmodule\n";
let files = workspace(&[("p.sv", pkg), ("a.sv", a), ("b.sv", b), ("c.sv", c)]);
let edit = rename(&files, &path("p.sv"), at(pkg, "", "WIDTH"), "BUS_W").expect("renames");
assert!(apply(pkg, &edit, &path("p.sv")).contains("localparam int BUS_W = 8;"));
assert!(apply(a, &edit, &path("a.sv")).contains("wire [BUS_W-1:0] bus;"));
assert!(apply(b, &edit, &path("b.sv")).contains("wire [p::BUS_W-1:0] bus;"));
let c_after = apply(c, &edit, &path("c.sv"));
assert!(c_after.contains("import p::BUS_W;"), "{c_after}");
assert!(c_after.contains("wire [BUS_W-1:0] bus;"), "{c_after}");
}
#[test]
fn a_package_name_renames_at_every_import_site() {
let pkg = "package p;\n localparam int K = 1;\nendpackage\n";
let a = "module a;\n import p::*;\n wire [K-1:0] bus;\nendmodule\n";
let files = workspace(&[("p.sv", pkg), ("a.sv", a)]);
let edit = rename(&files, &path("p.sv"), at(pkg, "package", "p"), "cfg_pkg").expect("renames");
assert!(apply(pkg, &edit, &path("p.sv")).contains("package cfg_pkg;"));
assert!(apply(a, &edit, &path("a.sv")).contains("import cfg_pkg::*;"));
}
#[test]
fn a_port_renames_inside_the_connection_lists_of_other_files() {
let sub = "module sub (input logic clk, input logic rst);\nendmodule\n";
let top = "module top;\n sub u0 (.clk(1'b0), .rst(1'b1));\nendmodule\n";
let files = workspace(&[("sub.sv", sub), ("top.sv", top)]);
let edit =
rename(&files, &path("sub.sv"), at(sub, "input logic", "clk"), "clock").expect("renames");
assert!(apply(sub, &edit, &path("sub.sv")).contains("input logic clock,"));
let after = apply(top, &edit, &path("top.sv"));
assert!(after.contains(".clock(1'b0)"), "{after}");
assert!(after.contains(".rst(1'b1)"), "the other connection is untouched: {after}");
}
// ----------------------------------------------------------------------
// refusals
// ----------------------------------------------------------------------
/// The refusal message for a rename that must not happen.
fn refusal(text: &str, prefix: &str, name: &str, new_name: &str) -> String {
rename_one(text, prefix, name, new_name).expect_err("this rename must be refused")
}
#[test]
fn an_invalid_or_reserved_new_name_is_refused() {
let text = "module m;\n wire a;\n assign a = 1;\nendmodule\n";
for bad in ["", " ", "2fast", "a b", "a+b", "module", "wire", "`MACRO", "a;"] {
let message = refusal(text, "wire", "a", bad);
assert!(
message.contains("identifier")
|| message.contains("keyword")
|| message.contains("empty"),
"`{bad}` refused with an unhelpful message: {message}"
);
}
}
#[test]
fn renaming_a_name_to_itself_is_refused() {
let text = "module m;\n wire a;\nendmodule\n";
assert!(refusal(text, "wire", "a", "a").contains("already has"));
}
#[test]
fn there_is_nothing_to_rename_on_whitespace_a_keyword_or_a_macro() {
let text = "`define WIDTH 8\nmodule m;\n wire a;\n initial $display(\"a\");\nendmodule\n";
let files = workspace(&[("m.sv", text)]);
for offset in [
at(text, "", "module"),
at(text, "", "WIDTH"),
0, // the backtick of `` `define ``
at(text, "", "initial"),
] {
let message = rename(&files, &path("m.sv"), offset, "renamed")
.expect_err("nothing to rename at {offset}");
assert!(message.contains("no symbol to rename"), "at {offset}: {message}");
}
}
#[test]
fn an_unresolved_name_is_refused_rather_than_guessed() {
// `p` is declared in this file, so `p::MISSING` is `NotFound`, not an
// external candidate: no index could change the answer.
let text = concat!(
"package p;\n localparam K = 1;\nendpackage\n",
"module m;\n wire w = p::MISSING;\nendmodule\n"
);
let message = refusal(text, "", "MISSING", "renamed");
assert!(message.contains("not resolved"), "{message}");
}
#[test]
fn a_name_declared_outside_the_indexed_files_is_refused() {
let text = "module m;\n import other_pkg::*;\n wire w = FROM_ELSEWHERE;\nendmodule\n";
let message = refusal(text, "", "FROM_ELSEWHERE", "renamed");
assert!(message.contains("outside the files vfmt indexes"), "{message}");
}
#[test]
fn a_name_that_could_only_come_from_a_base_class_is_refused() {
let text = concat!(
"package p;\n",
" class child extends uvm_object;\n",
" function void go();\n",
" inherited_thing = 1;\n",
" endfunction\n",
" endclass\n",
"endpackage\n"
);
let message = refusal(text, "", "inherited_thing", "renamed");
assert!(message.contains("base class"), "{message}");
}
#[test]
fn a_module_declared_in_two_files_is_refused_from_both_ends() {
let one = "module dup;\nendmodule\n";
let two = "module dup;\nendmodule\n";
let top = "module top;\n dup u0 ();\nendmodule\n";
let files = workspace(&[("one.sv", one), ("two.sv", two), ("top.sv", top)]);
// From a declaration.
let message = rename(&files, &path("one.sv"), at(one, "", "dup"), "renamed")
.expect_err("ambiguous declarations must be refused");
assert!(message.contains("more than one indexed file"), "{message}");
// And from the use, which the overlay answers ambiguously.
let message = rename(&files, &path("top.sv"), at(top, "", "dup"), "renamed")
.expect_err("an ambiguous use must be refused");
assert!(message.contains("more than one indexed file"), "{message}");
}
#[test]
fn a_file_outside_the_indexed_set_is_refused() {
let text = "module m;\n wire a;\nendmodule\n";
let files = workspace(&[("m.sv", text)]);
let message = rename(&files, &path("elsewhere.sv"), 20, "renamed")
.expect_err("an unindexed file must be refused");
assert!(message.contains("not one of the files vfmt indexes"), "{message}");
}
// ----------------------------------------------------------------------
// collisions — the check that makes the rest safe
// ----------------------------------------------------------------------
#[test]
fn renaming_onto_a_name_declared_in_the_same_scope_is_refused() {
let text = "module m;\n wire a;\n wire b;\n assign a = b;\nendmodule\n";
let message = refusal(text, "wire", "a", "b");
assert!(message.contains("would change what"), "{message}");
}
#[test]
fn renaming_onto_a_name_an_inner_scope_declares_is_refused() {
// The renamed net would be captured by the block's own `tmp` at the use
// inside the block.
let text = concat!(
"module m;\n",
" wire a;\n",
" initial begin : blk\n",
" int tmp;\n",
" tmp = a;\n",
" end\n",
"endmodule\n"
);
let message = refusal(text, "wire", "a", "tmp");
assert!(message.contains("would change what"), "{message}");
}
#[test]
fn renaming_onto_a_name_an_outer_scope_declares_is_refused() {
// The other direction: the module-level `outer` use inside the block
// would start naming the renamed local instead.
let text = concat!(
"module m;\n",
" wire outer;\n",
" initial begin : blk\n",
" int local_v;\n",
" local_v = 1;\n",
" if (outer) local_v = 2;\n",
" end\n",
"endmodule\n"
);
let message = refusal(text, "int", "local_v", "outer");
assert!(message.contains("would change what"), "{message}");
}
#[test]
fn a_collision_in_another_file_is_refused_too() {
// `top` already instantiates a module named `child`; renaming `sub` to
// `child` would make that instantiation ambiguous.
let sub = "module sub;\nendmodule\n";
let child = "module child;\nendmodule\n";
let top = "module top;\n sub u0 ();\n child u1 ();\nendmodule\n";
let files = workspace(&[("sub.sv", sub), ("child.sv", child), ("top.sv", top)]);
let message = rename(&files, &path("sub.sv"), at(sub, "", "sub"), "child")
.expect_err("a cross-file collision must be refused");
assert!(message.contains("would change what"), "{message}");
}
#[test]
fn a_collision_with_a_third_file_that_never_spells_the_old_name_is_refused() {
// QA's reproduction: `top.sv` instantiates `child` and never mentions
// `sub`, so it receives no edit — but after renaming `sub` to `child`
// its instantiation would name two modules. Its bytes are untouched; its
// meaning is not, and that is what the verification pass must see.
let sub = "module sub;\nendmodule\n";
let child = "module child;\nendmodule\n";
let top = "module top;\n child u1 ();\nendmodule\n";
let files = workspace(&[("sub.sv", sub), ("child.sv", child), ("top.sv", top)]);
let message = rename(&files, &path("sub.sv"), at(sub, "", "sub"), "child")
.expect_err("an untouched third file's meaning must still be checked");
assert!(message.contains("would change what"), "{message}");
assert!(message.contains("top.sv"), "the file whose meaning moved is named: {message}");
}
#[test]
fn a_third_file_that_merely_mentions_the_new_name_in_a_comment_is_not_a_collision() {
// The watch list is a text filter, so it pulls in files whose only
// mention is prose. Those must not turn into false refusals.
let sub = "module sub;\nendmodule\n";
let top = "// child is a good name for this\nmodule top;\n sub u0 ();\nendmodule\n";
let files = workspace(&[("sub.sv", sub), ("top.sv", top)]);
let edit = rename(&files, &path("sub.sv"), at(sub, "", "sub"), "child").expect("renames");
assert_eq!(edit.edit_count(), 2, "the declaration and the instantiation");
assert!(apply(top, &edit, &path("top.sv")).contains("// child is a good name"));
}
#[test]
fn a_name_that_only_shadows_somewhere_the_rename_never_reaches_is_allowed() {
// `n` exists inside `other`, but nothing the rename touches is in that
// scope, so there is no capture and no reason to refuse.
let text = concat!(
"module m;\n",
" wire a;\n",
" assign a = 1;\n",
"endmodule\n",
"module other;\n",
" int n;\n",
" initial n = 2;\n",
"endmodule\n"
);
let renamed = rename_one(text, "wire", "a", "n").expect("no collision here");
assert!(renamed.contains("wire n;"), "{renamed}");
assert!(renamed.contains(" int n;\n initial n = 2;"), "the other module is untouched");
}
// ----------------------------------------------------------------------
// preprocessor honesty
// ----------------------------------------------------------------------
#[test]
fn a_macro_of_the_same_name_is_warned_about_and_never_edited() {
let text = "`define a 1\nmodule m;\n wire a;\n assign a = 1;\nendmodule\n";
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, "wire", "a"), "sig").expect("renames");
let after = apply(text, &edit, &path("m.sv"));
assert!(after.starts_with("`define a 1\n"), "the macro is untouched: {after}");
assert!(after.contains("wire sig;"));
assert!(
edit.warnings.iter().any(|w| w.contains("macro")),
"the macro must be reported: {:?}",
edit.warnings
);
}
#[test]
fn the_name_inside_a_macro_body_is_warned_about() {
let text = concat!(
"`define SET_A assign a = 1;\n",
"module m;\n",
" wire a;\n",
" assign a = 0;\n",
"endmodule\n"
);
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, "wire", "a"), "sig").expect("renames");
assert!(apply(text, &edit, &path("m.sv")).contains("`define SET_A assign a = 1;"));
assert!(
edit.warnings.iter().any(|w| w.contains("body of macro `SET_A`")),
"{:?}",
edit.warnings
);
}
#[test]
fn the_name_inside_a_macro_invocations_arguments_is_warned_about() {
// A macro invocation is one opaque token, arguments included, so the `a`
// inside `` `BUMP(a) `` cannot be edited. Silence would be the real
// defect: the expansion still spells the old name.
let text = concat!(
"`define BUMP(x) x = x + 1\n",
"module m;\n",
" int a;\n",
" initial `BUMP(a);\n",
"endmodule\n"
);
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, "int", "a"), "b").expect("renames");
assert!(apply(text, &edit, &path("m.sv")).contains("`BUMP(a);"), "opaque stays opaque");
assert!(
edit.warnings.iter().any(|w| w.contains("arguments of the macro invocation `BUMP`")),
"the macro argument must be reported: {:?}",
edit.warnings
);
}
#[test]
fn a_macro_invocation_in_an_untouched_file_is_warned_about_too() {
let pkg = "package p;\n localparam int WIDTH = 8;\nendpackage\n";
let user = concat!(
"`define DECL(w) logic [w-1:0] bus\n",
"module u;\n",
" import p::*;\n",
" `DECL(WIDTH);\n",
"endmodule\n"
);
let files = workspace(&[("p.sv", pkg), ("u.sv", user)]);
let edit = rename(&files, &path("p.sv"), at(pkg, "", "WIDTH"), "BUS_W").expect("renames");
assert!(apply(user, &edit, &path("u.sv")).contains("`DECL(WIDTH);"), "opaque stays opaque");
assert!(
edit.warnings.iter().any(|w| w.contains("macro invocation") && w.contains("u.sv")),
"{:?}",
edit.warnings
);
}
#[test]
fn a_reference_inside_an_ifdef_arm_is_renamed_because_it_is_just_tokens() {
let text = concat!(
"module m;\n",
" wire a;\n",
"`ifdef SYNTHESIS\n",
" assign a = 1;\n",
"`else\n",
" assign a = 0;\n",
"`endif\n",
"endmodule\n"
);
let renamed = rename_one(text, "wire", "a", "sig").expect("renames");
assert_eq!(renamed.matches("assign sig").count(), 2, "both arms: {renamed}");
}
#[test]
fn every_end_label_is_renamed_with_the_declaration_it_closes() {
// Non-compiling output would be corruption by another name: an end label
// that no longer matches its declaration is illegal SystemVerilog.
let text = concat!(
"package p;\n",
" function automatic int f();\n",
" f = 1;\n",
" endfunction : f\n",
" task t();\n",
" endtask : t\n",
" class c;\n",
" endclass : c\n",
"endpackage : p\n",
"module m;\n",
" initial begin : blk\n",
" end : blk\n",
"endmodule : m\n"
);
let cases = [
("package", "p", "cfg_pkg", "endpackage : cfg_pkg"),
("automatic int", "f", "one", "endfunction : one"),
("task", "t", "run", "endtask : run"),
("class", "c", "item", "endclass : item"),
("begin :", "blk", "setup", "end : setup"),
("module", "m", "top", "endmodule : top"),
];
for (prefix, name, new_name, expected_label) in cases {
let renamed = rename_one(text, prefix, name, new_name).expect("renames");
assert!(renamed.contains(expected_label), "renaming {name}: {renamed}");
assert!(
!renamed.contains(&format!(": {name}\n")),
"no stale `{name}` label may survive: {renamed}"
);
}
}
#[test]
fn a_generate_block_label_renames_with_its_end_label() {
let text = concat!(
"module m;\n",
" generate if (1) begin : gblk\n",
" wire w;\n",
" end : gblk\n",
" endgenerate\n",
"endmodule\n"
);
let renamed = rename_one(text, "begin :", "gblk", "guarded").expect("renames");
assert!(renamed.contains("begin : guarded"), "{renamed}");
assert!(renamed.contains("end : guarded"), "{renamed}");
}
#[test]
fn an_end_label_of_a_different_construct_is_never_edited() {
// Two constructs called `inner`. Renaming the module must leave the
// block's `end : inner` exactly where it is — the label is bound to the
// construct it closes, not matched by text.
let text = concat!(
"module holder;\n",
" initial begin : inner\n",
" end : inner\n",
"endmodule\n",
"\n",
"module inner;\n",
"endmodule : inner\n"
);
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, "\nmodule inner", "inner"), "leaf")
.expect("renames");
let after = apply(text, &edit, &path("m.sv"));
assert!(
after.contains(
"begin : inner
end : inner"
),
"the block is untouched: {after}"
);
assert!(
after.contains(
"module leaf;
endmodule : leaf"
),
"{after}"
);
assert_eq!(edit.edit_count(), 2, "the declaration and its own label only");
}
#[test]
fn a_comment_or_string_that_looks_like_an_end_label_is_never_edited() {
let text = concat!(
"module m;\n",
" // endmodule : m\n",
" initial $display(\"endmodule : m\");\n",
"endmodule : m\n"
);
let renamed = rename_one(text, "module", "m", "top").expect("renames");
assert!(renamed.contains("// endmodule : m"), "the comment stays: {renamed}");
assert!(renamed.contains("$display(\"endmodule : m\")"), "the string stays: {renamed}");
assert!(renamed.ends_with("endmodule : top\n"), "the real label moves: {renamed}");
}
#[test]
fn a_mismatched_end_label_is_left_alone_and_says_which_construct_it_is() {
// `endmodule : wrong` is already illegal; vfmt neither edits it nor
// pretends it is fine.
let text = "module m;\n wire a;\nendmodule : wrong\n";
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, "module", "m"), "top").expect("renames");
assert_eq!(apply(text, &edit, &path("m.sv")), "module top;\n wire a;\nendmodule : wrong\n");
assert!(edit.warnings.is_empty(), "nothing spells `m` there: {:?}", edit.warnings);
}
#[test]
fn a_hierarchical_tail_is_left_alone_and_named_as_such() {
let text = concat!(
"module sub;\n wire sig;\nendmodule\n",
"module top;\n",
" sub u_sub ();\n",
" wire w;\n",
" assign w = u_sub.sig;\n",
"endmodule\n"
);
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, "wire", "sig"), "signal").expect("renames");
let after = apply(text, &edit, &path("m.sv"));
assert!(after.contains("wire signal;"), "{after}");
assert!(after.contains("u_sub.sig;"), "the tail is not resolved, so not edited: {after}");
assert!(
edit.warnings.iter().any(|w| w.contains("hierarchical or member tail")),
"{:?}",
edit.warnings
);
}
// ----------------------------------------------------------------------
// the shape of the result
// ----------------------------------------------------------------------
#[test]
fn renaming_and_renaming_back_gives_the_original_text() {
let text = "module m;\n wire a;\n assign a = 1;\n assign b = a;\nendmodule\n";
let once = rename_one(text, "wire", "a", "sig").expect("renames");
let files = workspace(&[("m.sv", once.as_str())]);
let back = rename(&files, &path("m.sv"), at(&once, "wire", "sig"), "a").expect("renames back");
assert_eq!(apply(&once, &back, &path("m.sv")), text);
}
#[test]
fn every_edit_writes_the_new_name_over_exactly_the_old_one() {
let text = "module m;\n wire aa;\n assign aa = aa & 1;\nendmodule\n";
let files = workspace(&[("m.sv", text)]);
let edit = rename(&files, &path("m.sv"), at(text, "wire", "aa"), "bbb").expect("renames");
assert_eq!(edit.edit_count(), 3);
for e in edit.edits_for(&path("m.sv")) {
assert_eq!(&text[e.range.as_range()], "aa", "an edit must cover exactly the old name");
assert_eq!(e.new_text, "bbb");
}
}
#[test]
fn a_comment_or_string_mentioning_the_name_is_never_touched() {
let text = concat!(
"module m;\n",
" // a is the signal\n",
" wire a;\n",
" initial $display(\"a\");\n",
" assign a = 1;\n",
"endmodule\n"
);
let renamed = rename_one(text, "wire", "a", "sig").expect("renames");
assert!(renamed.contains("// a is the signal"), "{renamed}");
assert!(renamed.contains("$display(\"a\")"), "{renamed}");
assert!(renamed.contains("wire sig;") && renamed.contains("assign sig = 1;"), "{renamed}");
}
#[test]
fn a_utf8_file_keeps_its_bytes_and_its_spans() {
let text = "module m;\n // é ✓ 🎉\n wire a;\n assign a = 1;\nendmodule\n";
let renamed = rename_one(text, "wire", "a", "senal").expect("renames");
assert!(renamed.contains("// é ✓ 🎉"), "{renamed}");
assert!(renamed.contains("wire senal;") && renamed.contains("assign senal = 1;"), "{renamed}");
}
// ----------------------------------------------------------------------
// prepareRename
// ----------------------------------------------------------------------
#[test]
fn prepare_returns_the_identifier_and_its_current_name() {
let text = "module m;\n wire abc;\n assign abc = 1;\nendmodule\n";
let files = workspace(&[("m.sv", text)]);
let offset = at(text, "assign", "abc");
let target = prepare_rename(&files, &path("m.sv"), offset + 1).expect("ok");
assert_eq!(target.name, "abc");
assert_eq!(&text[target.range.as_range()], "abc");
assert_eq!(target.range.start, offset);
}
#[test]
fn prepare_declines_exactly_what_rename_would_decline() {
let text = "`define WIDTH 8\nmodule m;\n wire a;\n wire w = UNKNOWN_NAME;\nendmodule\n";
let files = workspace(&[("m.sv", text)]);
for offset in [at(text, "", "module"), at(text, "", "WIDTH"), at(text, "", "UNKNOWN_NAME")] {
assert!(
prepare_rename(&files, &path("m.sv"), offset).is_err(),
"prepare must decline at {offset}"
);
}
assert!(prepare_rename(&files, &path("m.sv"), at(text, "wire", "a")).is_ok());
}
+44 -3
View File
@@ -40,6 +40,10 @@ pub(crate) enum Target {
ThisMember,
/// The `x` of `super.x`: always the base class's business.
SuperMember,
/// Exactly this declaration, with no lookup at all: an end label
/// (`endmodule : m`, `endfunction : f`, `end : blk`) names the construct
/// it closes and nothing else.
Declaration(SymbolId),
}
/// An out-of-body method definition (`function void cls::method(...)`), held
@@ -181,6 +185,36 @@ impl<'a> Binder<'a> {
self.pending.push(Pending { name: name.to_string(), name_span, scope, target });
}
/// `endmodule : m`, `endfunction : f`, `end : blk`: an end label names the
/// declaration it closes, so it is recorded as a use of exactly that
/// symbol — never looked up, so it can never attach to a same-named
/// declaration somewhere else. A label that does not spell the declared
/// name is an error the linter owns, and records nothing.
fn use_end_label(
&mut self,
scope: ScopeId,
body: ScopeId,
label: Option<&String>,
span: Option<TextRange>,
) {
let (Some(label), Some(span)) = (label, span) else {
return;
};
// `None` when the declaration was a redeclaration and bound no symbol
// of its own; the label is then left unrecorded, as it was before.
let Some(sym) = self.scopes[body.0 as usize].owner else {
return;
};
if self.symbols[sym.0 as usize].name != *label {
return;
}
let span = self.exact_or_empty(span, label);
if span.is_empty() {
return;
}
self.use_member(scope, label, span, Target::Declaration(sym));
}
/// `span` when it slices to exactly `name`, else an empty range at its
/// start. Guards the ranges this crate derives instead of receiving —
/// a source spelling `pkg :: mod` must cost a span, never mislocate one.
@@ -206,7 +240,7 @@ impl<'a> Binder<'a> {
fn bind_item(&mut self, item: &'a Item, scope: ScopeId) {
match &item.kind {
ItemKind::Module(m) => self.bind_module(m, item.span, scope),
ItemKind::Package { name, name_span, items, .. } => {
ItemKind::Package { name, name_span, items, end_label, end_label_span, .. } => {
let inner = self.declare_with_scope(
scope,
name,
@@ -216,6 +250,7 @@ impl<'a> Binder<'a> {
ScopeKind::Package,
);
self.bind_items(items, inner);
self.use_end_label(scope, inner, end_label.as_ref(), *end_label_span);
}
ItemKind::Import(paths) => {
for path in paths {
@@ -365,6 +400,7 @@ impl<'a> Binder<'a> {
PortList::None | PortList::Empty => {}
}
self.bind_items(&m.items, inner);
self.use_end_label(scope, inner, m.end_label.as_ref(), m.end_label_span);
}
/// A `#( ... )` header parameter list — module and class headers share it.
@@ -565,6 +601,7 @@ impl<'a> Binder<'a> {
_ => self.new_scope(ScopeKind::Generate, scope, b.span),
};
self.bind_items(&b.items, inner);
self.use_end_label(scope, inner, b.end_label.as_ref(), b.end_label_span);
}
fn bind_function(&mut self, f: &'a FunctionDecl, span: TextRange, scope: ScopeId) {
@@ -587,6 +624,7 @@ impl<'a> Binder<'a> {
);
self.bind_tf_args(&f.args, inner);
self.bind_stmts(&f.stmts, inner);
self.use_end_label(scope, inner, f.end_label.as_ref(), f.end_label_span);
}
fn bind_task(&mut self, t: &'a TaskDecl, span: TextRange, scope: ScopeId) {
@@ -604,6 +642,7 @@ impl<'a> Binder<'a> {
);
self.bind_tf_args(&t.args, inner);
self.bind_stmts(&t.stmts, inner);
self.use_end_label(scope, inner, t.end_label.as_ref(), t.end_label_span);
}
fn bind_tf_args(&mut self, args: &'a [TfArg], scope: ScopeId) {
@@ -659,6 +698,7 @@ impl<'a> Binder<'a> {
// nested classes — works here unchanged. Verbatim members
// (constraints, covergroups) stay opaque through the item arm.
self.bind_items(&c.items, inner);
self.use_end_label(scope, inner, c.end_label.as_ref(), c.end_label_span);
}
/// Record a unit name that may be scope-qualified: `base`, `pkg::base`.
@@ -840,8 +880,8 @@ impl<'a> Binder<'a> {
fn bind_stmt(&mut self, stmt: &'a Stmt, scope: ScopeId) {
match &stmt.kind {
StmtKind::Block { label, label_span, stmts, .. }
| StmtKind::ForkJoin { label, label_span, stmts, .. } => {
StmtKind::Block { label, label_span, stmts, end_label, end_label_span, .. }
| StmtKind::ForkJoin { label, label_span, stmts, end_label, end_label_span, .. } => {
let inner = match (label, *label_span) {
(Some(label), Some(ls)) => self.declare_with_scope(
scope,
@@ -854,6 +894,7 @@ impl<'a> Binder<'a> {
_ => self.new_scope(ScopeKind::Block, scope, stmt.span),
};
self.bind_stmts(stmts, inner);
self.use_end_label(scope, inner, end_label.as_ref(), *end_label_span);
}
StmtKind::If { cond, then, els, .. } => {
self.bind_expr(cond, scope);
+3
View File
@@ -10,6 +10,9 @@ use crate::model::{Resolution, Scope, ScopeId, Symbol, SymbolId, SymbolKind};
/// Resolve one pending use against the finished scope tree.
pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Resolution {
match &p.target {
// An end label names the construct it closes; the binder already knew
// which symbol that is, so there is nothing to look up.
Target::Declaration(id) => Resolution::Resolved(*id),
Target::Lexical => lexical(scopes, p.scope, &p.name),
Target::Package => named_at_file_scope(scopes, symbols, &p.name, SymbolKind::Package),
Target::Module => named_at_file_scope(scopes, symbols, &p.name, SymbolKind::Module),
+100
View File
@@ -539,3 +539,103 @@ endmodule
let s = analyze(&file, src);
assert!(s.references().iter().all(|r| r.name != "SOME_ASSERT" && r.name != "WIDTH"));
}
#[test]
fn an_end_label_is_a_use_of_the_declaration_it_closes() {
// Every construct that may carry one. The label is bound to its own
// construct directly, never looked up, so `references_of` on each
// declaration finds exactly its own label.
let src = "\
package p;
function automatic int f();
f = 1;
endfunction : f
task t();
endtask : t
class c;
endclass : c
endpackage : p
module m;
initial begin : blk
end : blk
generate if (1) begin : gblk
wire w;
end : gblk
endgenerate
endmodule : m
";
let s = sem(src);
for name in ["p", "f", "t", "c", "m", "blk", "gblk"] {
let id = symbol_id(&s, name);
let uses = s.references_of(id);
let labels: Vec<_> = uses
.iter()
.filter(|r| r.name_span.start > symbol_named(&s, name).name_span.start)
.filter(|r| src[r.name_span.as_range()] == *name)
.collect();
assert!(!labels.is_empty(), "the end label of `{name}` must be a use of it");
}
// And the spans really are the labels, not the declarations.
let end_of_m = nth(src, "endmodule : m", 0) + "endmodule : ".len() as u32;
let label = s.reference_at(end_of_m).expect("`endmodule : m` records a use");
assert_eq!(label.resolved(), Some(symbol_id(&s, "m")));
assert_eq!(&src[label.name_span.as_range()], "m");
}
#[test]
fn an_end_label_never_attaches_to_a_same_named_declaration_elsewhere() {
// Two different constructs called `inner`, in different scopes. A lexical
// lookup could pick either; binding a label to the construct it closes
// cannot.
let src = "\
module m;
initial begin : inner
end : inner
endmodule
module inner;
endmodule : inner
";
let s = sem(src);
let of_kind = |kind| {
s.symbols()
.iter()
.position(|sym| sym.name == "inner" && sym.kind == kind)
.map(|i| SymbolId(i as u32))
.unwrap_or_else(|| panic!("no {kind:?} named inner"))
};
let block_label = s.reference_at(nth(src, "end : inner", 0) + 6).expect("the block's label");
assert_eq!(block_label.resolved(), Some(of_kind(SymbolKind::Block)));
let module_label =
s.reference_at(nth(src, "endmodule : inner", 0) + 12).expect("the module's label");
assert_eq!(module_label.resolved(), Some(of_kind(SymbolKind::Module)));
}
#[test]
fn a_label_whose_name_is_already_bound_in_the_scope_records_nothing() {
// `begin : m` next to `wire m` is a redeclaration, which binds no symbol
// of its own (the "first declaration wins" rule). Rather than attach the
// `end : m` label to the *net*, nothing is recorded for it.
let src = "\
module top;
wire m;
initial begin : m
end : m
endmodule
";
let s = sem(src);
let labels: Vec<_> =
s.references().iter().filter(|r| r.name_span.start >= nth(src, "end : m", 0)).collect();
assert!(labels.is_empty(), "an ambiguous label is left unrecorded: {labels:?}");
}
#[test]
fn a_mismatched_end_label_records_nothing_rather_than_guessing() {
// `endmodule : wrong` is illegal SystemVerilog; the linter owns saying so,
// and nothing here pretends it names the module.
let src = "module m;\n wire a;\nendmodule : wrong\n";
let (file, _) = parse_source_tolerant(src);
let s = analyze(&file, src);
assert!(s.references().iter().all(|r| r.name != "wrong"));
}
+902
View File
@@ -0,0 +1,902 @@
# 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<TextEdit>)>, pub warnings: Vec<String> }
pub struct RenameTarget { pub range: TextRange, pub name: String }
pub fn prepare_rename(files: &[(PathBuf, String)], file: &Path, offset: u32)
-> Result<RenameTarget, String>;
pub fn rename(files: &[(PathBuf, String)], file: &Path, offset: u32, new_name: &str)
-> Result<RefactorEdit, String>;
```
`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"), <offset of "sub">, "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.
+5 -5
View File
@@ -55,15 +55,15 @@ the work is reviewed**. Owner-priority items first (2026-08-24).
sharing the current file's directory → same feature (M1)
### Rename
- [ ] **Rename any symbol** the semantic layer resolves — wire/reg/logic
- [x] **Rename any symbol** the semantic layer resolves — wire/reg/logic
nets and variables, ports, parameters/localparams, genvars, typedefs,
enum members, functions/tasks, modules, instances, packages, class
members — via LSP `textDocument/rename` → `docs/features/refactor-rename/README.md` (M2)
- [ ] **`prepareRename`** — reject up front what can't be renamed (keywords,
- [x] **`prepareRename`** — reject up front what can't be renamed (keywords,
macro uses, unresolved names), so the editor never offers a broken rename → M2
- [ ] **Cross-file rename** through the workspace index (module names update
- [x] **Cross-file rename** through the workspace index (module names update
every instantiation; package members update every import site) → M2
- [ ] **Rename safety**: refuse on collision with an existing name in any
- [x] **Rename safety**: refuse on collision with an existing name in any
affected scope, on invalid identifiers, and whenever any resulting file
would no longer parse — whole-edit-or-nothing, like the formatter → M2
- [ ] Rename in comments/strings as an *option* (rope's `docs=True`) — off
@@ -177,7 +177,7 @@ commit — in order:
- [x] Plan written; rope docs surveyed (overview: rename, extract, inline,
move, change signature, restructure, organize imports, SOA/DOA, history)
- [x] M1 filelist — done, QA clean, reviewed
- [ ] M2 refactor-rename
- [x] M2 refactor-rename — done, QA clean after one rework round, reviewed
- [ ] M3 refactor-ports
- [ ] M4 refactor-instantiate
- [ ] Backlog triage after M4
+6 -1
View File
@@ -24,6 +24,8 @@ looks like language knowledge in here is a bug or a `Handshake` request.
| `textDocument/definition` | `Semantics` then `ExternalResolutions` | `Ambiguous` returns every location |
| `textDocument/references` | `Semantics::references_of` | In-file only this round |
| `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` |
| `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits |
Deferred, deliberately, and named in Status/TODO below: ~~range formatting
@@ -34,7 +36,10 @@ UTF-16 `Range` to 1-based lines — see
**delivered by server-lint (round 13): lint findings publish as warnings in the
same notification as the parse errors, and `textDocument/codeAction` offers
their Safe fixes — see `docs/features/server-lint/README.md`**,
completion / rename / signature help, and cross-file references.
~~rename~~ **delivered by refactor-rename (M2 of the refactoring plan):
`textDocument/prepareRename` + `textDocument/rename`, edits computed in the new
`vlog_refactor` crate — see `docs/features/refactor-rename/README.md`**,
completion / signature help, and cross-file references.
(`vfmt.toml` discovery and `.gitignore`-aware indexing, deferred when this
was written, were delivered by vfmt-core-lift the same day — lead note.)
+27 -1
View File
@@ -165,7 +165,19 @@ region | generate block | for-generate header | for/foreach statement`.
- **A function's name is not also a variable.** `f = expr;` inside `function
f` resolves to the function symbol, which is where go-to-definition should
land anyway.
- **`endmodule : m` and other end labels record nothing.**
- ~~**`endmodule : m` and other end labels record nothing.**~~ **Changed
2026-08-24 by refactor-rename (lead-authorized):** an end label
(`endmodule`/`endinterface`/`endpackage`/`endfunction`/`endtask`/`endclass`
`: name`, and `end : label` / `join : label` on a named block or generate
block) is recorded as a *use* of the declaration it closes, through the new
`Target::Declaration(SymbolId)` — bound directly to that symbol, never
looked up, so a label can never attach to a same-named declaration
elsewhere. A label that does not spell the declared name, or whose
declaration was a redeclaration that bound no symbol of its own, still
records nothing. `endclocking` is unaffected: a clocking block is opaque to
this crate and declares no symbol. The parser already carried
`end_label_span` on every one of these nodes, so `vlog_parser` needed no
change.
- **`defparam` paths, `disable` targets and event names** are resolved with
the ordinary lexical rule (`disable blk` finds the named block).
- **Ordering inside a scope is not modeled**: `symbol_at` and lookup are
@@ -306,6 +318,20 @@ anywhere, and under 3 % unresolved on cleanly-parsed files.
## Work log
**2026-08-24 — refactor-rename dev agent (lead-authorized, cross-module).**
End labels are now references. `bind.rs` gains `Target::Declaration(SymbolId)`
and `Binder::use_end_label`, called from the module, package, class, function,
task, generate-block and statement-block/fork-join arms; `resolve.rs` answers
it with `Resolution::Resolved(id)` directly. Strictly additive: no existing
target, span or symbol changed, and no `vlog_parser` change was needed
(`end_label_span` was already on every node). The reason is
`docs/features/refactor-rename/README.md`: a rename that leaves
`endmodule : old_name` behind produces non-compiling SystemVerilog, and
fixing it by text matching would have broken the "every edit comes from a
resolved reference" rule. Three tests added to `tests/semantics.rs`
(all six labelled constructs; a label never attaching to a same-named
declaration elsewhere; a mismatched label recording nothing).
**2026-08-19 — dev agent.** Built the crate: `model.rs` (tables), `bind.rs`
(pass one), `resolve.rs` (pass two), `scan.rs` (name-span recovery),
`lib.rs` (`analyze` + queries). Key decisions, all argued above: