From e338524f637d0aa97c3b2c1ac1fa691296281197 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Mon, 24 Aug 2026 06:25:18 -0700 Subject: [PATCH] Refactoring M3: add/remove/propagate module ports vlog_refactor ports engine: add_port (ANSI + non-ANSI, named/ordered/.* sites, .p(p) vs TODO placeholder by real scope lookup), remove_port (refuses positional connections and live body uses, lists dropped expressions), propagate_ports, all through a new splice verifier (piece equality, comments never deleted, no new parse diagnostics, resolution identity) plus a per-feature shape check. A new port can never silently land inside an `ifdef arm (nesting-aware refusal, both insertion paths); macro-argument/define-body occurrences of a removed port warn. Server: code actions + vfmt.addPort/removePort/propagatePorts executeCommands. Co-Authored-By: Claude Fable 5 --- TODO.md | 2 +- crates/vfmt_server/src/code_action.rs | 2 +- crates/vfmt_server/src/main.rs | 28 +- crates/vfmt_server/src/ports.rs | 382 +++++ crates/vfmt_server/src/server.rs | 64 +- crates/vfmt_server/tests/e2e.rs | 130 ++ crates/vlog_refactor/src/check.rs | 458 +++++- crates/vlog_refactor/src/lib.rs | 38 +- crates/vlog_refactor/src/ports.rs | 1856 ++++++++++++++++++++++++ crates/vlog_refactor/src/rename.rs | 115 +- crates/vlog_refactor/tests/corpus.rs | 74 +- crates/vlog_refactor/tests/ports.rs | 737 ++++++++++ docs/features/refactor-ports/README.md | 1196 +++++++++++++++ docs/features/refactor/README.md | 8 +- 14 files changed, 5006 insertions(+), 84 deletions(-) create mode 100644 crates/vfmt_server/src/ports.rs create mode 100644 crates/vlog_refactor/src/ports.rs create mode 100644 crates/vlog_refactor/tests/ports.rs create mode 100644 docs/features/refactor-ports/README.md diff --git a/TODO.md b/TODO.md index a7480dd..4cc6d79 100644 --- a/TODO.md +++ b/TODO.md @@ -586,7 +586,7 @@ section only tracks the milestones. - [x] **M2 `refactor-rename`** — new crate `vlog_refactor`; LSP `prepareRename`/`rename` for every symbol kind `vlog_semantic` resolves, cross-file, whole-edit-or-nothing verified by re-parse. -- [ ] **M3 `refactor-ports`** — add/remove/propagate module ports across +- [x] **M3 `refactor-ports`** — add/remove/propagate module ports across the declaration and every instantiation (named/ordered/`.*`). - [ ] **M4 `refactor-instantiate`** — module hinting: instantiation skeleton completion from the definition, auto-connect, signature help. diff --git a/crates/vfmt_server/src/code_action.rs b/crates/vfmt_server/src/code_action.rs index d6ca931..3d05bc2 100644 --- a/crates/vfmt_server/src/code_action.rs +++ b/crates/vfmt_server/src/code_action.rs @@ -134,7 +134,7 @@ fn title(violation: &Violation) -> String { /// Whether a client asking for `only` wants this kind. A filter is a prefix of /// the kinds it selects (`source` selects `source.fixAll.vfmt`), and no filter /// at all selects everything. -fn wanted(only: Option<&[CodeActionKind]>, kind: &CodeActionKind) -> bool { +pub fn wanted(only: Option<&[CodeActionKind]>, kind: &CodeActionKind) -> bool { let Some(only) = only else { return true }; only.iter().any(|filter| { let (filter, kind) = (filter.as_str(), kind.as_str()); diff --git a/crates/vfmt_server/src/main.rs b/crates/vfmt_server/src/main.rs index 81bbf99..ea26bab 100644 --- a/crates/vfmt_server/src/main.rs +++ b/crates/vfmt_server/src/main.rs @@ -15,6 +15,7 @@ mod lint; mod locate; mod nav; mod pairs; +mod ports; mod rename; mod server; mod settings; @@ -28,10 +29,10 @@ use std::path::PathBuf; use lsp_server::Connection; use lsp_types::{ - CodeActionKind, CodeActionOptions, CodeActionProviderCapability, InitializeParams, OneOf, - PositionEncodingKind, RenameOptions, SemanticTokensFullOptions, SemanticTokensLegend, - SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities, - TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions, + CodeActionKind, CodeActionOptions, CodeActionProviderCapability, ExecuteCommandOptions, + InitializeParams, OneOf, PositionEncodingKind, RenameOptions, SemanticTokensFullOptions, + SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities, + ServerCapabilities, TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions, }; use crate::server::Server; @@ -85,11 +86,19 @@ fn capabilities() -> ServerCapabilities { code_action_kinds: Some(vec![ CodeActionKind::QUICKFIX, CodeActionKind::new(code_action::FIX_ALL), + CodeActionKind::new(ports::REFACTOR_PORTS), ]), work_done_progress_options: WorkDoneProgressOptions::default(), // Every action is returned complete; there is nothing to resolve. resolve_provider: None, })), + // The port refactorings. `vfmt.addPort` needs a declaration typed by + // the user, which no code action can carry, and a Vim user has no + // lightbulb at all — so all three are commands as well. + execute_command_provider: Some(ExecuteCommandOptions { + commands: ports::commands(), + work_done_progress_options: WorkDoneProgressOptions::default(), + }), semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions( SemanticTokensOptions { work_done_progress_options: WorkDoneProgressOptions::default(), @@ -146,6 +155,7 @@ mod tests { assert!(caps.semantic_tokens_provider.is_some()); assert!(caps.code_action_provider.is_some()); assert!(caps.rename_provider.is_some()); + assert!(caps.execute_command_provider.is_some()); // Deliberately absent until the engine exists — see the README. assert!(caps.completion_provider.is_none()); } @@ -167,7 +177,7 @@ mod tests { } #[test] - fn the_two_code_action_kinds_are_named_in_the_capability() { + fn the_code_action_kinds_are_named_in_the_capability() { // A client filtering by kind (fix-on-save does) sees nothing unless the // kinds it may ask for are advertised. let Some(CodeActionProviderCapability::Options(options)) = @@ -178,6 +188,14 @@ mod tests { let kinds = options.code_action_kinds.expect("kinds"); assert!(kinds.contains(&CodeActionKind::QUICKFIX)); assert!(kinds.contains(&CodeActionKind::new(code_action::FIX_ALL))); + assert!(kinds.contains(&CodeActionKind::new(ports::REFACTOR_PORTS))); + } + + #[test] + fn every_advertised_command_is_one_the_server_runs() { + let options = capabilities().execute_command_provider.expect("commands"); + assert_eq!(options.commands, ports::commands()); + assert!(options.commands.iter().all(|c| c.starts_with("vfmt.")), "{:?}", options.commands); } #[test] diff --git a/crates/vfmt_server/src/ports.rs b/crates/vfmt_server/src/ports.rs new file mode 100644 index 0000000..df09966 --- /dev/null +++ b/crates/vfmt_server/src/ports.rs @@ -0,0 +1,382 @@ +//! The port refactorings on the wire: `textDocument/codeAction` for the two +//! that need no typing, and `workspace/executeCommand` for all three. +//! +//! Protocol only. Every edit is computed by `vlog_refactor` over the same file +//! set the workspace index was built from; this module turns the result into a +//! `WorkspaceEdit` and the refusal into a request error. Nothing here decides +//! what may be refactored. +//! +//! **Why commands as well as code actions.** Adding a port needs a +//! declaration typed by the user, and a code action carries no input — so +//! `vfmt.addPort` is the API a UI calls once it has asked. `vfmt.removePort` +//! and `vfmt.propagatePorts` take a position and exist for the same reason a +//! Vim user has no lightbulb: a command works everywhere a keybinding does. +//! See `docs/features/refactor-ports/README.md`. + +// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours. +#![allow(clippy::mutable_key_type)] + +use std::collections::HashMap; +use std::path::PathBuf; + +use lsp_types::{ + CodeAction, CodeActionKind, CodeActionOrCommand, Position, TextEdit, Uri, WorkspaceEdit, +}; +use serde_json::Value; +use vlog_parser::LineIndex; +use vlog_refactor::{ModuleRef, RefactorEdit}; + +use crate::convert::Positions; +use crate::state::Workspace; +use crate::uri::{path_to_uri, uri_to_path}; + +/// The kind every port refactoring is filed under, so a client can ask for +/// them alone. +pub const REFACTOR_PORTS: &str = "refactor.rewrite.vfmt.ports"; + +/// Add a port: `[uri, module-name-or-position, "input logic [7:0] cfg"]`. +pub const ADD_PORT: &str = "vfmt.addPort"; +/// Remove the port at a position: `[uri, position]`. +pub const REMOVE_PORT: &str = "vfmt.removePort"; +/// Connect an instantiation's missing ports: `[uri, position]`. +pub const PROPAGATE_PORTS: &str = "vfmt.propagatePorts"; + +/// Every command this server executes. +pub fn commands() -> Vec { + vec![ADD_PORT.to_string(), REMOVE_PORT.to_string(), PROPAGATE_PORTS.to_string()] +} + +/// The port actions available at a position, each carrying its own computed +/// edit — nothing to resolve, and nothing offered that would be refused. +pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { + let Some(doc) = ws.document(uri) else { return Vec::new() }; + let Some(path) = doc.path.clone() else { return Vec::new() }; + // A code-action request arrives on every cursor move, and `sources()` + // reads the whole in-scope file set from disk. The engine's one-file + // question answers "there is nothing here" for almost every position + // without any of that. + if !vlog_refactor::may_have_port_action(&doc.text, offset) { + return Vec::new(); + } + let sources = ws.sources(); + vlog_refactor::port_actions(&sources, &path, offset) + .into_iter() + .filter_map(|action| { + let edit = workspace_edit(ws, &action.edit).ok()?; + Some(CodeActionOrCommand::CodeAction(CodeAction { + title: action.title, + kind: Some(CodeActionKind::new(REFACTOR_PORTS)), + edit: Some(edit), + ..Default::default() + })) + }) + .collect() +} + +/// Run one of the three commands, or say why it cannot run. +/// +/// The answer is the `WorkspaceEdit` the client is expected to apply (through +/// `workspace/applyEdit`, which the server does not push: an editor that asked +/// for the command owns the edit) plus the engine's warnings. +pub fn execute( + ws: &Workspace, + command: &str, + arguments: &[Value], +) -> Result<(WorkspaceEdit, Vec), String> { + let sources = ws.sources(); + let refactoring = match command { + ADD_PORT => { + let (_, path) = target(ws, arguments.first())?; + let decl = arguments.get(2).and_then(Value::as_str).ok_or_else(|| { + format!("{ADD_PORT} wants a port declaration as its third argument.") + })?; + match module_argument(arguments.get(1)) { + ModuleArgument::Name(name) => { + vlog_refactor::add_port(&sources, ModuleRef::Name(&name), decl)? + } + ModuleArgument::Position(position) => { + let offset = offset_of(ws, arguments.first(), position)?; + vlog_refactor::add_port(&sources, ModuleRef::At { file: &path, offset }, decl)? + } + ModuleArgument::Missing => { + return Err(format!( + "{ADD_PORT} wants a module name or a position as its second argument." + )) + } + } + } + REMOVE_PORT => { + let (_, path) = target(ws, arguments.first())?; + let offset = position_argument(ws, arguments, REMOVE_PORT)?; + vlog_refactor::remove_port(&sources, &path, offset)? + } + PROPAGATE_PORTS => { + let (_, path) = target(ws, arguments.first())?; + let offset = position_argument(ws, arguments, PROPAGATE_PORTS)?; + vlog_refactor::propagate_ports(&sources, &path, offset)? + } + other => return Err(format!("`{other}` is not a vfmt command.")), + }; + Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings)) +} + +/// What the second argument of `vfmt.addPort` said. +enum ModuleArgument { + Name(String), + Position(Position), + Missing, +} + +fn module_argument(argument: Option<&Value>) -> ModuleArgument { + match argument { + Some(Value::String(name)) => ModuleArgument::Name(name.clone()), + Some(value) => match serde_json::from_value::(value.clone()) { + Ok(position) => ModuleArgument::Position(position), + Err(_) => ModuleArgument::Missing, + }, + None => ModuleArgument::Missing, + } +} + +/// The document a command's first argument names. +fn target(ws: &Workspace, argument: Option<&Value>) -> Result<(Uri, PathBuf), String> { + let uri: Uri = + argument.and_then(|value| serde_json::from_value(value.clone()).ok()).ok_or_else(|| { + "a vfmt port command wants a document URI as its first argument.".to_string() + })?; + let path = ws + .document(&uri) + .and_then(|doc| doc.path.clone()) + .or_else(|| uri_to_path(&uri)) + .ok_or_else(|| "vfmt can only refactor inside a saved file.".to_string())?; + Ok((uri, path)) +} + +fn position_argument(ws: &Workspace, arguments: &[Value], command: &str) -> Result { + let position: Position = arguments + .get(1) + .and_then(|value| serde_json::from_value(value.clone()).ok()) + .ok_or_else(|| format!("{command} wants a position as its second argument."))?; + offset_of(ws, arguments.first(), position) +} + +/// A position turned into a byte offset, against the same text everything else +/// is computed against. +fn offset_of(ws: &Workspace, uri: Option<&Value>, position: Position) -> Result { + let (uri, path) = target(ws, uri)?; + match ws.document(&uri) { + Some(doc) => Ok(doc.positions().offset(position)), + None => { + let text = + ws.text_of(&path).ok_or_else(|| format!("vfmt cannot read {}.", path.display()))?; + let index = LineIndex::new(&text); + Ok(Positions::new(&text, &index).offset(position)) + } + } +} + +/// A whole refactoring as a `WorkspaceEdit`, with every range computed against +/// the text the engine actually edited — the open buffer's when there is one. +pub fn workspace_edit(ws: &Workspace, refactoring: &RefactorEdit) -> Result { + let mut changes: HashMap> = HashMap::new(); + for (path, edits) in &refactoring.edits { + 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)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + /// 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_ports_{}_{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); + } + } + + const SUB: &str = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n"; + const TOP: &str = "module top;\n logic cfg;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"; + + /// A two-file workspace with `top.sv` open. + fn opened(tree: &Tree) -> (Workspace, Uri, Uri) { + let sub = 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 top_uri = path_to_uri(&top).expect("uri"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(top_uri.clone(), TOP.to_string()); + (ws, top_uri, sub_uri) + } + + fn edits_for<'a>(edit: &'a WorkspaceEdit, uri: &Uri) -> &'a [TextEdit] { + edit.changes.as_ref().expect("changes").get(uri).map_or(&[], Vec::as_slice) + } + + #[test] + fn add_port_edits_the_declaration_and_every_instantiation() { + let tree = Tree::new("add"); + let (ws, top_uri, sub_uri) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&top_uri).expect("uri"), + Value::String("sub".into()), + Value::String("input logic cfg".into()), + ]; + let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds"); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(edits_for(&edit, &sub_uri).len(), 1); + assert_eq!(edits_for(&edit, &sub_uri)[0].new_text, ",\n input logic cfg"); + let top = edits_for(&edit, &top_uri); + assert_eq!(top.len(), 1); + assert_eq!(top[0].new_text, ", .cfg(cfg)"); + assert_eq!(top[0].range.start.line, 2, "the instantiation's line"); + } + + #[test] + fn add_port_refuses_a_declaration_that_is_not_one() { + let tree = Tree::new("add_bad"); + let (ws, top_uri, _) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&top_uri).expect("uri"), + Value::String("sub".into()), + Value::String("wire".into()), + ]; + let message = execute(&ws, ADD_PORT, &arguments).expect_err("not a port"); + assert!(message.contains("not a single ANSI port declaration"), "{message}"); + } + + #[test] + fn add_port_accepts_a_position_instead_of_a_module_name() { + let tree = Tree::new("add_at"); + let (ws, _, sub_uri) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&sub_uri).expect("uri"), + serde_json::to_value(Position { line: 0, character: 8 }).expect("position"), + Value::String("input logic cfg".into()), + ]; + let (edit, _) = execute(&ws, ADD_PORT, &arguments).expect("adds"); + assert_eq!(edits_for(&edit, &sub_uri).len(), 1); + } + + #[test] + fn remove_port_takes_a_position() { + let tree = Tree::new("remove"); + let (ws, top_uri, sub_uri) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&sub_uri).expect("uri"), + serde_json::to_value(Position { line: 2, character: 14 }).expect("position"), + ]; + let (edit, warnings) = execute(&ws, REMOVE_PORT, &arguments).expect("removes"); + assert_eq!(warnings.len(), 1, "the dropped expression is reported: {warnings:?}"); + assert!(warnings[0].contains("`.rst(r)`"), "{warnings:?}"); + assert_eq!(edits_for(&edit, &sub_uri).len(), 2, "the comma and the port itself"); + assert_eq!(edits_for(&edit, &top_uri).len(), 2, "the connection and its comma"); + assert!(edits_for(&edit, &top_uri).iter().all(|e| e.new_text.is_empty())); + } + + #[test] + fn propagate_ports_fills_in_what_is_missing() { + let tree = Tree::new("propagate"); + let text = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n"; + tree.write("sub.sv", SUB); + let top = tree.write("top.sv", text); + 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(), text.to_string()); + let arguments = vec![ + serde_json::to_value(&uri).expect("uri"), + serde_json::to_value(Position { line: 2, character: 6 }).expect("position"), + ]; + let (edit, _) = execute(&ws, PROPAGATE_PORTS, &arguments).expect("propagates"); + assert_eq!(edits_for(&edit, &uri).len(), 1); + assert_eq!(edits_for(&edit, &uri)[0].new_text, ", .rst(rst)"); + } + + #[test] + fn a_code_action_on_a_port_carries_the_whole_edit() { + let tree = Tree::new("action"); + let (ws, top_uri, sub_uri) = opened(&tree); + // The server computes offsets against the file's own text. + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + let actions = code_actions(&ws, &sub_uri, offset); + assert_eq!(actions.len(), 0, "sub.sv is not an open document"); + + // With the buffer open, the action is offered and carries its edit. + let mut ws = ws; + ws.set_document(sub_uri.clone(), SUB.to_string()); + let actions = code_actions(&ws, &sub_uri, offset); + assert_eq!(actions.len(), 1, "{actions:#?}"); + let CodeActionOrCommand::CodeAction(action) = &actions[0] else { panic!("an action") }; + assert_eq!(action.title, "vfmt: remove port `rst` (updates 1 instantiation)"); + assert_eq!(action.kind, Some(CodeActionKind::new(REFACTOR_PORTS))); + let edit = action.edit.as_ref().expect("an edit"); + assert_eq!(edits_for(edit, &sub_uri).len(), 2, "the comma and the port itself"); + assert_eq!(edits_for(edit, &top_uri).len(), 2, "the connection and its comma"); + } + + #[test] + fn an_unknown_command_is_declined() { + let tree = Tree::new("unknown"); + let (ws, uri, _) = opened(&tree); + let arguments = vec![serde_json::to_value(&uri).expect("uri")]; + let message = execute(&ws, "vfmt.nope", &arguments).expect_err("unknown"); + assert!(message.contains("not a vfmt command"), "{message}"); + } + + #[test] + fn a_command_without_its_arguments_is_declined() { + let tree = Tree::new("args"); + let (ws, uri, _) = opened(&tree); + let message = execute(&ws, REMOVE_PORT, &[]).expect_err("no uri"); + assert!(message.contains("document URI"), "{message}"); + let only_uri = vec![serde_json::to_value(&uri).expect("uri")]; + let message = execute(&ws, REMOVE_PORT, &only_uri).expect_err("no position"); + assert!(message.contains("position"), "{message}"); + } + + #[test] + fn the_command_list_is_what_the_server_advertises() { + assert_eq!(commands(), vec![ADD_PORT, REMOVE_PORT, PROPAGATE_PORTS]); + } +} diff --git a/crates/vfmt_server/src/server.rs b/crates/vfmt_server/src/server.rs index 2bf9e93..82524e4 100644 --- a/crates/vfmt_server/src/server.rs +++ b/crates/vfmt_server/src/server.rs @@ -14,25 +14,26 @@ use lsp_types::notification::{ DidSaveTextDocument, LogMessage, Notification as _, PublishDiagnostics, ShowMessage, }; use lsp_types::request::{ - CodeActionRequest, DocumentHighlightRequest, DocumentSymbolRequest, Formatting, GotoDefinition, - HoverRequest, PrepareRenameRequest, RangeFormatting, References, Rename, Request as _, - SemanticTokensFullRequest, WorkspaceSymbolRequest, + CodeActionRequest, DocumentHighlightRequest, DocumentSymbolRequest, ExecuteCommand, Formatting, + GotoDefinition, HoverRequest, PrepareRenameRequest, RangeFormatting, References, Rename, + Request as _, SemanticTokensFullRequest, WorkspaceSymbolRequest, }; use lsp_types::{ - CodeActionParams, DidChangeConfigurationParams, DidChangeTextDocumentParams, + CodeActionKind, CodeActionParams, DidChangeConfigurationParams, DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentFormattingParams, DocumentHighlightParams, DocumentRangeFormattingParams, - DocumentSymbolParams, DocumentSymbolResponse, GotoDefinitionParams, GotoDefinitionResponse, - HoverParams, LogMessageParams, MessageType, Position, PublishDiagnosticsParams, - ReferenceParams, RenameParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams, - TextDocumentPositionParams, Uri, WorkspaceSymbolParams, WorkspaceSymbolResponse, + DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, GotoDefinitionParams, + GotoDefinitionResponse, HoverParams, LogMessageParams, MessageType, Position, + PublishDiagnosticsParams, 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, rename, settings, symbols, tokens, + code_action, diagnostics, format, hover, nav, pairs, ports, rename, settings, symbols, tokens, }; /// Everything the server owns. @@ -146,25 +147,23 @@ impl Server { }), CodeActionRequest::METHOD => decode(request).and_then(|p: CodeActionParams| { let uri = p.text_document.uri; - match self.workspace.document(&uri) { - Some(doc) => { - // A code-action request carries no `tabSize`, so the - // width a `no-tabs` fix writes comes from the buffer's - // own `vfmt.toml` or from the built-in default. - let tab_width = format::indent_width( - doc.path.as_deref(), - self.workspace.client_settings(), - ); - to_value(code_action::code_actions( - &uri, - doc, - p.range, - p.context.only.as_deref(), - tab_width, - )) - } - None => Ok(Value::Null), + let only = p.context.only; + let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) }; + // A code-action request carries no `tabSize`, so the width a + // `no-tabs` fix writes comes from the buffer's own `vfmt.toml` + // or from the built-in default. + let tab_width = + format::indent_width(doc.path.as_deref(), self.workspace.client_settings()); + let mut actions = + code_action::code_actions(&uri, doc, p.range, only.as_deref(), tab_width); + // The port refactorings answer for the cursor, not for a range: + // the request's start is where the user is. + if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS)) + { + let offset = doc.positions().offset(p.range.start); + actions.extend(ports::code_actions(&self.workspace, &uri, offset)); } + to_value(actions) }), // Custom method, so it is matched by name rather than through a // `lsp_types::request` type. Nothing advertises it: a client that @@ -206,6 +205,17 @@ impl Server { Err(message) => Err(Failure::Request(message)), } }), + // The port refactorings. A refusal is the engine's own sentence, + // returned as `RequestFailed` exactly as a declined rename is. + ExecuteCommand::METHOD => decode(request).and_then(|p: ExecuteCommandParams| { + match ports::execute(&self.workspace, &p.command, &p.arguments) { + 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( diff --git a/crates/vfmt_server/tests/e2e.rs b/crates/vfmt_server/tests/e2e.rs index 65ed21b..f074274 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -991,3 +991,133 @@ fn prepare_rename_and_rename_round_trip_over_the_wire() { let _ = std::fs::remove_dir_all(&dir); } + +/// A module and one instantiation of it, for the port refactorings. +const PORTS_SUB: &str = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n"; +/// QA's reproduction: a port list whose last port lives in an `` `ifdef `` arm. +const PORTS_COND: &str = + "module cond (\n input clk\n`ifdef HAS_RST\n , input rst\n`endif\n);\nendmodule\n"; +const PORTS_TOP: &str = + "module top;\n logic clk, rst, cfg;\n sub u_sub (.clk(clk));\nendmodule\n"; + +#[test] +fn a_port_code_action_and_the_port_commands_round_trip_over_the_wire() { + // What only an e2e test can check: that the command is advertised, that + // `workspace/executeCommand` reaches the engine with its arguments intact, + // and that a code action carries a cross-file `WorkspaceEdit` of its own. + let dir = temp_dir("ports"); + let sub = dir.join("sub.sv"); + std::fs::write(&sub, PORTS_SUB).expect("write"); + let top = dir.join("top.sv"); + std::fs::write(&top, PORTS_TOP).expect("write"); + let cond = dir.join("cond.sv"); + std::fs::write(&cond, PORTS_COND).expect("write"); + let root = format!("file://{}", dir.display()); + let top_uri = format!("file://{}", top.display()); + let sub_uri = format!("file://{}", sub.display()); + let cond_uri = format!("file://{}", cond.display()); + + let open = |uri: &str, text: &str| { + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(text).expect("json") + )) + }; + 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":{}}"#), + open(&top_uri, PORTS_TOP), + open(&sub_uri, PORTS_SUB), + open(&cond_uri, PORTS_COND), + // The cursor on `u_sub`: the instantiation is missing `.rst`. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{top_uri}"}},"range":{{"start":{{"line":2,"character":6}},"end":{{"line":2,"character":6}}}},"context":{{"diagnostics":[]}}}}}}"# + )), + // `vfmt.propagatePorts` at the same place, through the command. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"workspace/executeCommand","params":{{"command":"vfmt.propagatePorts","arguments":["{top_uri}",{{"line":2,"character":6}}]}}}}"# + )), + // `vfmt.addPort` — the one that needs text nobody can click. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{{"command":"vfmt.addPort","arguments":["{top_uri}","sub","input logic cfg"]}}}}"# + )), + // ...and a declaration that is not one is refused with a sentence. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":5,"method":"workspace/executeCommand","params":{{"command":"vfmt.addPort","arguments":["{top_uri}","sub","wire"]}}}}"# + )), + // ...and a port that would land inside an `ifdef arm is refused, over + // the wire, not only in the crate's own tests. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":6,"method":"workspace/executeCommand","params":{{"command":"vfmt.addPort","arguments":["{cond_uri}","cond","input logic cfg"]}}}}"# + )), + 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); + + // 1. The commands are advertised, and so is the code-action kind. + let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); + let capabilities = &initialize["result"]["capabilities"]; + let commands = capabilities["executeCommandProvider"]["commands"] + .as_array() + .unwrap_or_else(|| panic!("no executeCommandProvider in {capabilities:#?}")); + assert!(commands.iter().any(|c| c == "vfmt.addPort"), "{commands:#?}"); + assert!(commands.iter().any(|c| c == "vfmt.removePort"), "{commands:#?}"); + assert!(commands.iter().any(|c| c == "vfmt.propagatePorts"), "{commands:#?}"); + let kinds = capabilities["codeActionProvider"]["codeActionKinds"] + .as_array() + .expect("the kinds are listed"); + assert!(kinds.iter().any(|k| k == "refactor.rewrite.vfmt.ports"), "{kinds:#?}"); + + // 2. The code action carries its own edit, ready to apply. + let actions = messages.iter().find(|m| m["id"] == 2).expect("codeAction response"); + let offered = actions["result"].as_array().expect("an array of actions"); + let port_action = offered + .iter() + .find(|a| a["kind"] == "refactor.rewrite.vfmt.ports") + .unwrap_or_else(|| panic!("no port action in {offered:#?}")); + assert_eq!(port_action["title"], "vfmt: connect 1 missing port"); + let edits = port_action["edit"]["changes"][&top_uri].as_array().expect("one file's edits"); + assert_eq!(edits.len(), 1); + assert_eq!(edits[0]["newText"], ", .rst(rst)"); + assert_eq!(edits[0]["range"]["start"]["line"], 2); + + // 3. The command answers with the same edit. + let propagated = messages.iter().find(|m| m["id"] == 3).expect("executeCommand response"); + let edits = propagated["result"]["changes"][&top_uri].as_array().expect("edits"); + assert_eq!(edits[0]["newText"], ", .rst(rst)"); + + // 4. `addPort` reaches both files. + let added = messages.iter().find(|m| m["id"] == 4).expect("executeCommand response"); + let changes = &added["result"]["changes"]; + assert_eq!(changes.as_object().expect("a changes map").len(), 2, "{changes:#?}"); + assert_eq!(changes[&sub_uri][0]["newText"], ",\n input logic cfg"); + assert_eq!(changes[&top_uri][0]["newText"], ", .cfg(cfg)"); + + // 5. A refusal is `RequestFailed` with the engine's own sentence. + let refused = messages.iter().find(|m| m["id"] == 5).expect("refusal response"); + assert_eq!(refused["error"]["code"], -32803, "LSP's RequestFailed"); + assert!( + refused["error"]["message"] + .as_str() + .is_some_and(|m| m.contains("not a single ANSI port declaration")), + "{refused:#?}" + ); + + // 6. ...and so is a port that would be conditionally compiled. + let conditional = messages.iter().find(|m| m["id"] == 6).expect("refusal response"); + assert_eq!(conditional["error"]["code"], -32803); + assert!( + conditional["error"]["message"] + .as_str() + .is_some_and(|m| m.contains("conditionally compiled") && m.contains("`ifdef HAS_RST")), + "{conditional:#?}" + ); + assert!(conditional["result"].is_null(), "a refusal carries no edits: {conditional:#?}"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/vlog_refactor/src/check.rs b/crates/vlog_refactor/src/check.rs index 8e43a3b..c999e36 100644 --- a/crates/vlog_refactor/src/check.rs +++ b/crates/vlog_refactor/src/check.rs @@ -7,6 +7,13 @@ //! declaration, or a cross-file use that quietly rebound. Neither implies the //! other, and either one failing fails the entire refactoring. //! +//! [`verify`] is the *rename* contract: the token stream may not change shape +//! at all. [`verify_splice`] is the same contract for a refactoring that +//! deliberately writes or deletes text (the port ones): the token stream may +//! change only by exactly the pieces the edits spell, no comment may be +//! deleted, no file may gain a parse error, and every name *outside* the +//! edited ranges must still resolve to exactly what it did. +//! //! 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. @@ -67,7 +74,14 @@ pub(crate) fn verify( 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)); + before.push(print( + &analysis.semantics, + &analysis.external, + scope.index(), + path, + &shifts, + &[], + )); } let after_index = rebuilt_index(scope, &edited); @@ -82,7 +96,7 @@ pub(crate) fn verify( }; 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 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!( @@ -94,6 +108,152 @@ pub(crate) fn verify( Ok(()) } +/// Check the whole edit of a refactoring that adds or deletes text, or refuse +/// it whole. `watch_name` is the name whose meaning the refactoring changes — +/// the module whose ports moved — and `what` names the refactoring in the +/// refusal ("adding port `cfg`"). +/// +/// Four checks, in the order that gives the most useful sentence first: +/// +/// 1. **Lexical splice.** Every touched file must lex to exactly the original +/// pieces — code tokens *and* comments — with the edits' own pieces written +/// in at the edits' positions and nothing else moved. An edit that landed +/// in a string, split a token or wrote a `,` into a line comment cannot +/// survive it. +/// 2. **Comments are never dropped** (CLAUDE.md invariant 3): no deletion may +/// cover a comment. A port or connection with a comment on it is refused, +/// not silently un-commented. +/// 3. **The file still parses**: a touched file may not gain a parse +/// diagnostic it did not have. +/// 4. **Resolution identity outside the edits.** Every declaration and every +/// reference whose name span does not overlap an edit must resolve to the +/// same place before and after — in every watched file, edited or not. This +/// is what refuses an added port that captures a body reference, or a +/// removed port some other name silently rebinds. +pub(crate) fn verify_splice( + scope: &mut Scope, + edits: &[(usize, Vec)], + watch_name: &str, + what: &str, +) -> Result<(), String> { + let abandoned = format!("vfmt could not verify {what}, so it made no edits."); + 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); + } + + for ((i, edits), (path, text)) in edits.iter().zip(&edited) { + let Some(before) = scope.text(*i) else { return Err(abandoned) }; + pieces_match(before, text, edits, path, what)?; + // A tolerant parse of a file that was already broken still reports its + // old diagnostics, so the bar is "no *new* one", not "none". + let (before_count, after_count) = + (parse_source_tolerant(before).1.len(), parse_source_tolerant(text).1.len()); + if after_count > before_count { + return Err(format!( + "{what} would leave {} unparseable; no edits were made.", + display(path) + )); + } + } + + let shifts = Shifts::new(scope, edits, ""); + let excluded = Excluded::new(scope, edits); + let watched = watched_files(scope, edits, watch_name, watch_name); + for &i in &watched { + if scope.analysis(i).is_none() { + return Err(abandoned); + } + } + let mut before: Vec = Vec::new(); + for &i in &watched { + let (Some(path), Some(analysis)) = (scope.path(i), scope.cached(i)) else { + return Err(abandoned); + }; + before.push(print( + &analysis.semantics, + &analysis.external, + scope.index(), + path, + &shifts, + excluded.before(path), + )); + } + + let after_index = rebuilt_index(scope, &edited); + for (n, &i) in watched.iter().enumerate() { + let Some(path) = scope.path(i) else { return Err(abandoned) }; + 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), + }, + }; + 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(), + excluded.after(path), + ); + let Some(before) = before.get(n) else { return Err(abandoned) }; + if let Some(what_moved) = before.first_difference(&after) { + return Err(format!( + "{what} would change what {what_moved} means in {}; no edits were made.", + display(path) + )); + } + } + Ok(()) +} + +/// The byte ranges each refactoring deliberately changed, in the coordinates +/// of the text before the edits and of the text after them. Names inside them +/// are the ones the user asked to move, so they are the only ones the +/// resolution check does not hold fixed. +#[derive(Default)] +struct Excluded { + before: HashMap>, + after: HashMap>, +} + +impl Excluded { + fn new(scope: &Scope, edits: &[(usize, Vec)]) -> Excluded { + let mut out = Excluded::default(); + for (i, edits) in edits { + let Some(path) = scope.path(*i) else { continue }; + out.before.insert(path.to_path_buf(), edits.iter().map(|e| e.range).collect()); + let mut after = Vec::new(); + let mut delta: i64 = 0; + for edit in edits { + let start = (edit.range.start as i64 + delta).max(0) as u32; + after.push(TextRange::new(start, start + edit.new_text.len() as u32)); + delta += edit.new_text.len() as i64 - i64::from(edit.range.len()); + } + out.after.insert(path.to_path_buf(), after); + } + out + } + + fn before(&self, path: &Path) -> &[TextRange] { + self.before.get(path).map_or(&[], Vec::as_slice) + } + + fn after(&self, path: &Path) -> &[TextRange] { + self.after.get(path).map_or(&[], Vec::as_slice) + } +} + /// 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 @@ -182,6 +342,148 @@ fn tokens_match( Ok(()) } +// ---------------------------------------------------------------------- +// lexical splice +// ---------------------------------------------------------------------- + +/// One lexical piece of a file, in source order: a code token, or a comment. +/// Comments are pieces of their own rather than trivia hanging off a token, +/// because an insertion can legitimately move which token a comment attaches +/// to without moving the comment itself. +#[derive(Debug, PartialEq, Eq)] +enum Piece { + Code(TokenKind, String), + Comment(String), +} + +impl Piece { + /// How the piece is named in a refusal. + fn describe(&self) -> String { + match self { + Piece::Code(_, text) => format!("the token `{text}`"), + Piece::Comment(text) => format!("the comment `{text}`"), + } + } +} + +/// Every piece of a file with the bytes it occupies, in source order. +fn pieces(text: &str) -> Option> { + let tokens = tokenize(text).ok()?; + let mut out: Vec<(TextRange, Piece)> = Vec::new(); + for token in &tokens { + for comment in &token.leading { + out.push((comment.span, Piece::Comment(comment.text.clone()))); + } + if token.kind != TokenKind::Eof { + out.push((token.span, Piece::Code(token.kind, token.text.clone()))); + } + if let Some(comment) = &token.trailing { + out.push((comment.span, Piece::Comment(comment.text.clone()))); + } + } + out.sort_by_key(|(span, _)| (span.start, span.end)); + Some(out) +} + +/// The edited file must lex to the original's pieces with the edits' own +/// pieces written in where the edits are — and to nothing else. +fn pieces_match( + before: &str, + after: &str, + edits: &[TextEdit], + path: &Path, + what: &str, +) -> Result<(), String> { + let (Some(old), Some(new)) = (pieces(before), pieces(after)) else { + return Err(format!( + "{} would no longer lex after {what}; no edits were made.", + display(path) + )); + }; + // Invariant 3, checked here rather than trusted to the planner: a deletion + // that covers a comment would delete it from both sides of this comparison + // and pass, so it is refused outright. + for (span, piece) in &old { + let deleted = edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, *span)); + if deleted && matches!(piece, Piece::Comment(_)) { + return Err(format!( + "{what} would delete {} in {}; comments are never dropped, so nothing was edited.", + piece.describe(), + display(path) + )); + } + } + + let mut expected: Vec = Vec::new(); + let mut next = 0usize; + let mut written: Vec> = Vec::new(); + for edit in edits { + let Some(pieces) = pieces(&edit.new_text) else { + return Err(format!("{what} would write text that does not lex; no edits were made.")); + }; + written.push(pieces); + } + for (span, piece) in old { + while let (Some(edit), Some(pieces)) = (edits.get(next), written.get(next)) { + if edit.range.start > span.start { + break; + } + expected.extend(pieces.iter().map(|(_, piece)| match piece { + Piece::Code(kind, text) => Piece::Code(*kind, text.clone()), + Piece::Comment(text) => Piece::Comment(text.clone()), + })); + next += 1; + } + if edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, span)) { + continue; + } + expected.push(piece); + } + while let Some(pieces) = written.get(next) { + expected.extend(pieces.iter().map(|(_, piece)| match piece { + Piece::Code(kind, text) => Piece::Code(*kind, text.clone()), + Piece::Comment(text) => Piece::Comment(text.clone()), + })); + next += 1; + } + + let actual: Vec = new.into_iter().map(|(_, piece)| piece).collect(); + for (n, expected) in expected.iter().enumerate() { + match actual.get(n) { + Some(actual) if actual == expected => {} + Some(actual) => { + return Err(format!( + "{what} would write {} where {} belongs in {}; no edits were made.", + actual.describe(), + expected.describe(), + display(path) + )) + } + None => { + return Err(format!( + "{what} would lose {} in {}; no edits were made.", + expected.describe(), + display(path) + )) + } + } + } + if actual.len() > expected.len() { + let extra = actual.get(expected.len()).map_or_else(String::new, Piece::describe); + return Err(format!( + "{what} would add {extra} to {}, which is not part of the edit; no edits were made.", + display(path) + )); + } + Ok(()) +} + +/// Whether two byte ranges share a byte. Empty ranges — the insertions — +/// overlap nothing: they replace no text, so they delete nothing. +fn overlaps(a: TextRange, b: TextRange) -> bool { + a.start < b.end && b.start < a.end +} + // ---------------------------------------------------------------------- // resolution identity // ---------------------------------------------------------------------- @@ -265,16 +567,22 @@ impl Print { } } +/// Everything one file declares and names, minus whatever sits inside +/// `excluded` — the ranges the refactoring deliberately wrote or deleted. +/// A rename passes no exclusions: it changes a spelling, never a structure. fn print( semantics: &Semantics, external: &ExternalResolutions, index: &WorkspaceIndex, path: &Path, shifts: &Shifts, + excluded: &[TextRange], ) -> Print { + let inside = |span: TextRange| excluded.iter().any(|range| overlaps(*range, span)); let mut declarations: Vec<(u32, u32, String, SymbolKind)> = semantics .symbols() .iter() + .filter(|symbol| !inside(symbol.name_span)) .map(|symbol| { let span = shifts.map(path, symbol.name_span); (span.start, span.end, shifts.name(path, symbol.name_span, &symbol.name), symbol.kind) @@ -286,6 +594,7 @@ fn print( .references() .iter() .enumerate() + .filter(|(_, reference)| !inside(reference.name_span)) .map(|(id, reference)| { let span = shifts.map(path, reference.name_span); let anchor = anchor_of(semantics, external, index, path, shifts, id, reference); @@ -411,6 +720,151 @@ mod tests { assert!(attack(&corrupted).is_err(), "an unlexable result is a failure, not output"); } + // ------------------------------------------------------------------ + // the splice verifier, and the attacks on it + // ------------------------------------------------------------------ + + /// A module whose port list is one per line, with a comment on each port — + /// the shape every one of the attacks below tries to damage. + const PORTS: &str = + "module m (\n input clk, // the clock\n input rst /* sync */\n);\n wire a; // a\nendmodule\n"; + + /// The edit `add_port` produces for `PORTS`: a `,` before the last port's + /// comment and the new port after it. + fn add_edits() -> Vec { + let end = PORTS.find("input rst").expect("rst") as u32 + "input rst".len() as u32; + let after_comment = PORTS.find("*/").expect("comment") as u32 + 2; + vec![ + TextEdit { range: TextRange::empty(end), new_text: ",".into() }, + TextEdit { + range: TextRange::empty(after_comment), + new_text: "\n input logic [7:0] cfg".into(), + }, + ] + } + + fn splice_attack(corrupted: &str) -> Result<(), String> { + pieces_match(PORTS, corrupted, &add_edits(), Path::new("/rtl/m.sv"), "adding port `cfg`") + } + + #[test] + fn the_splice_the_engine_actually_produces_verifies() { + let honest = apply(PORTS, &add_edits()); + assert_eq!(splice_attack(&honest), Ok(()), "the real output must pass"); + assert!(honest.contains("input rst, /* sync */\n input logic [7:0] cfg"), "{honest}"); + } + + #[test] + fn a_splice_that_wrote_the_comma_into_a_line_comment_is_rejected() { + // The hazard the two-edit shape exists to avoid: a `,` after `//` is a + // `,` nobody will ever see. + let corrupted = PORTS + .replace("// the clock", "// the clock,") + .replace("input rst /* sync */", "input rst /* sync */\n input logic [7:0] cfg"); + assert!(splice_attack(&corrupted).is_err(), "a comma inside a comment is not an edit"); + } + + #[test] + fn a_splice_that_landed_at_the_wrong_place_is_rejected() { + // The same tokens, spliced one port earlier: every piece is accounted + // for, but not in the order the edits promised. + let corrupted = apply(PORTS, &add_edits()) + .replace("input clk,", "input clk, input logic [7:0] cfg,") + .replace(",\n input logic [7:0] cfg\n)", "\n)"); + assert!(splice_attack(&corrupted).is_err(), "position is part of the promise"); + } + + #[test] + fn a_splice_that_also_dropped_a_comment_is_rejected() { + let corrupted = apply(PORTS, &add_edits()).replace(" // a", ""); + assert!(splice_attack(&corrupted).is_err(), "comments are never dropped"); + } + + #[test] + fn a_splice_that_also_rewrote_an_untouched_token_is_rejected() { + let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire b;"); + assert!(splice_attack(&corrupted).is_err(), "nothing outside the edit may move"); + } + + #[test] + fn a_splice_that_wrote_more_than_it_promised_is_rejected() { + let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire a; wire extra;"); + assert!(splice_attack(&corrupted).is_err(), "an invented declaration"); + } + + #[test] + fn a_splice_that_landed_inside_a_string_is_rejected() { + let text = "module m;\n initial $display(\"hello\");\nendmodule\n"; + let at = text.find("hello").expect("string") as u32; + let edits = vec![TextEdit { range: TextRange::empty(at), new_text: "x".into() }]; + let corrupted = apply(text, &edits); + let outcome = pieces_match(text, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit"); + assert!(outcome.is_err(), "the string's own text is not a token vfmt may write"); + } + + #[test] + fn a_deletion_that_would_swallow_a_comment_is_refused() { + // The one rule the piece comparison cannot see on its own: a comment + // inside a deleted range disappears from *both* sides. + let start = PORTS.find("input rst").expect("rst") as u32; + let end = PORTS.find("*/").expect("comment") as u32 + 2; + let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }]; + let corrupted = apply(PORTS, &edits); + let outcome = + pieces_match(PORTS, &corrupted, &edits, Path::new("/rtl/m.sv"), "removing port `rst`"); + let message = outcome.expect_err("a deleted comment is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + } + + #[test] + fn a_splice_whose_result_does_not_lex_is_rejected() { + let corrupted = apply(PORTS, &add_edits()).replace("endmodule", "/* oops"); + assert!(splice_attack(&corrupted).is_err(), "an unlexable result is a failure, not output"); + } + + #[test] + fn a_splice_that_captures_a_name_outside_the_edit_is_rejected() { + // The resolution half: the module already has a net called `cfg`, and + // the added port would take over what the body's `cfg` means. + let source = "module m (\n input clk\n);\n wire cfg;\n assign cfg = clk;\nendmodule\n"; + let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())]; + let mut scope = Scope::build(&files); + let end = source.find("input clk").expect("clk") as u32 + "input clk".len() as u32; + let edits = vec![( + 0usize, + vec![TextEdit { range: TextRange::empty(end), new_text: ",\n input cfg".into() }], + )]; + let outcome = verify_splice(&mut scope, &edits, "m", "adding port `cfg`"); + assert!(outcome.is_err(), "a captured body reference must refuse: {outcome:?}"); + } + + #[test] + fn a_splice_that_leaves_a_file_unparseable_is_rejected() { + let source = "module m (\n input clk\n);\nendmodule\n"; + let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())]; + let mut scope = Scope::build(&files); + let end = source.find("input clk").expect("clk") as u32 + "input clk".len() as u32; + let edits = vec![( + 0usize, + vec![TextEdit { range: TextRange::empty(end), new_text: ", input )( x".into() }], + )]; + let outcome = verify_splice(&mut scope, &edits, "m", "adding port `x`"); + assert!(outcome.is_err(), "a new parse error is a refusal: {outcome:?}"); + } + + #[test] + fn an_honest_port_addition_verifies() { + let source = "module m (\n input clk\n);\n wire a;\nendmodule\n"; + let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())]; + let mut scope = Scope::build(&files); + let end = source.find("input clk").expect("clk") as u32 + "input clk".len() as u32; + let edits = vec![( + 0usize, + vec![TextEdit { range: TextRange::empty(end), new_text: ",\n input rst".into() }], + )]; + assert_eq!(verify_splice(&mut scope, &edits, "m", "adding port `rst`"), Ok(())); + } + #[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 diff --git a/crates/vlog_refactor/src/lib.rs b/crates/vlog_refactor/src/lib.rs index d629e19..706d991 100644 --- a/crates/vlog_refactor/src/lib.rs +++ b/crates/vlog_refactor/src/lib.rs @@ -1,24 +1,31 @@ //! 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. +//! ruff's world: it turns "rename this" or "give this module another port" +//! into a set of byte edits over the files a workspace is made of. Every edit +//! comes from a span `vlog_semantic` resolved or from a node `vlog_parser` +//! parsed — 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, re-parsed and re-analyzed, and the *entire* refactoring is +//! refused if anything the user did not ask for 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. +//! See `docs/features/refactor-rename/README.md` and +//! `docs/features/refactor-ports/README.md` for the refusal lists and the +//! verification stories. mod check; +mod ports; mod rename; +pub use ports::{ + add_port, may_have_port_action, port_actions, propagate_ports, remove_port, ModuleRef, + PortAction, +}; pub use rename::{prepare_rename, rename, RenameTarget}; use std::path::PathBuf; @@ -101,10 +108,23 @@ impl Shift { } /// Where a span of the original text lands in the edited text. + /// + /// **Assumes every span is either identical to one edit's range or fully + /// disjoint from all of them** — which is what the callers hand over: + /// identifier name spans, and edits that either replace a whole name span + /// or insert at a position between tokens. A span that *starts strictly + /// inside* a non-empty edit range has no meaningful answer here (those + /// bytes were replaced wholesale) and the number this returns for one is + /// arbitrary, not a location. Filter such spans out before mapping — + /// `check::print`'s `excluded` list is how the port refactorings do it. 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 { + // `range.end <= span.start` rather than `range.start < span.start` + // so that an *insertion* — an empty range — pushes the span that + // begins exactly where it was written. For a rename, whose edits + // all replace a whole name span, the two say the same thing. + if range.end <= 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. diff --git a/crates/vlog_refactor/src/ports.rs b/crates/vlog_refactor/src/ports.rs new file mode 100644 index 0000000..e07f080 --- /dev/null +++ b/crates/vlog_refactor/src/ports.rs @@ -0,0 +1,1856 @@ +//! Module port signature changes: add a port, remove a port, propagate the +//! ports a single instantiation is missing. +//! +//! Read top-to-bottom, each one is the same four steps: find the module (or +//! the instantiation) the request names, work out the *plan* — one edit per +//! place the signature is written down, plus a sentence for every place vfmt +//! deliberately left alone — verify the whole plan in memory, and hand it back +//! or refuse it whole. A refusal is a sentence for the user, never a partial +//! edit. +//! +//! Unlike a rename, these refactorings write and delete text, so they cannot +//! use the rename verifier's "the token stream may not change shape" contract. +//! They use [`check::verify_splice`] instead, plus a **shape** check of their +//! own (`confirm`) that reads the edited text back and asserts the port list +//! and the connection lists now say exactly what the plan promised. See +//! `docs/features/refactor-ports/README.md`. + +use std::path::{Path, PathBuf}; + +use vlog_parser::ast::{ + Connections, GenBlock, GenElse, Instance, Instantiation, Item, ItemKind, Module, PortList, + SourceFile, +}; +use vlog_parser::span::TextRange; +use vlog_parser::token::{Token, TokenKind}; +use vlog_parser::{parse_source_tolerant, tokenize, LineIndex}; +use vlog_semantic::{Semantics, SymbolKind}; + +use crate::rename::{display, Scope}; +use crate::{check, RefactorEdit, TextEdit}; + +/// Which module a port refactoring acts on. +#[derive(Debug, Clone, Copy)] +pub enum ModuleRef<'a> { + /// The module declared under this name. It must be declared exactly once + /// in the in-scope files: vfmt does not guess between two of them. + Name(&'a str), + /// The module whose declaration covers this byte offset. + At { + /// One of the in-scope files. + file: &'a Path, + /// A byte offset inside the module's declaration. + offset: u32, + }, +} + +/// One refactoring an editor can offer at a position, computed in full. +/// +/// The title is written here rather than in the server so that Vim, VS Code +/// and any future CLI say the same thing. +#[derive(Debug, Clone)] +pub struct PortAction { + /// What the lightbulb says. + pub title: String, + /// The edit it applies, already verified. + pub edit: RefactorEdit, +} + +/// Add one ANSI port declaration to a module, and a connection for it to every +/// instantiation of that module in the in-scope files. +/// +/// `decl` is the one piece of free-form input any of these refactorings takes +/// (`input logic [7:0] cfg`), so it is parsed as a port declaration before +/// anything else happens, and the edited files are re-parsed afterwards. +pub fn add_port( + files: &[(PathBuf, String)], + module: ModuleRef<'_>, + decl: &str, +) -> Result { + let port = parse_port_decl(decl)?; + let mut scope = Scope::build(files); + let site = locate_module(&mut scope, module)?; + let plan = plan_add(&mut scope, &site, &port)?; + let what = format!("adding port `{}` to `{}`", port.name, site.name); + Ok(finish(&mut scope, plan, &site.name, &what)?.0) +} + +/// Remove the port at `offset` from its module, and its named connection from +/// every instantiation in the in-scope files. +pub fn remove_port( + files: &[(PathBuf, String)], + file: &Path, + offset: u32, +) -> Result { + Ok(removal(files, file, offset)?.0) +} + +/// The removal, the port's name, and how many instantiations it rewrites. +fn removal( + files: &[(PathBuf, String)], + file: &Path, + offset: u32, +) -> Result<(RefactorEdit, String, usize), String> { + let mut scope = Scope::build(files); + let (site, port) = locate_port(&mut scope, file, offset)?; + let plan = plan_remove(&mut scope, &site, &port)?; + let what = format!("removing port `{port}` from `{}`", site.name); + let (edit, sites) = finish(&mut scope, plan, &site.name, &what)?; + Ok((edit, port, sites)) +} + +/// Add the named connections one instantiation is missing, from the +/// instantiated module's own declaration. +pub fn propagate_ports( + files: &[(PathBuf, String)], + file: &Path, + offset: u32, +) -> Result { + let mut scope = Scope::build(files); + let (site, plan) = plan_propagate(&mut scope, file, offset)?; + let what = format!("connecting the missing ports of `{}`", site.name); + Ok(finish(&mut scope, plan, &site.name, &what)?.0) +} + +/// Every port refactoring available at a position, each with its edit already +/// computed and verified — which is what lets a code action carry its own +/// `WorkspaceEdit` instead of a command the editor has to resolve. +/// +/// Nothing is offered for a position where the refactoring would be refused: +/// a lightbulb that only ever explains itself is worse than no lightbulb. +pub fn port_actions(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Vec { + let mut out = Vec::new(); + let here = files.iter().find(|(path, _)| path == file).map(|(_, text)| text.as_str()); + if !here.is_some_and(|text| may_have_port_action(text, offset)) { + return out; + } + if let Ok((edit, port, sites)) = removal(files, file, offset) { + out.push(PortAction { + title: format!("vfmt: remove port `{port}` ({})", sites_phrase(sites)), + edit, + }); + } + if let Ok(edit) = propagate_ports(files, file, offset) { + let missing = edit.edit_count(); + out.push(PortAction { + title: format!( + "vfmt: connect {missing} missing port{}", + if missing == 1 { "" } else { "s" } + ), + edit, + }); + } + out +} + +/// Whether a position could carry a port refactoring at all, judged from one +/// file's own text: is it inside a module's port element, inside a non-ANSI +/// port declaration, or inside an instantiation? +/// +/// This is a **cheap** question — one parse of one file, no workspace, no I/O — +/// and it exists because a `textDocument/codeAction` request arrives on every +/// cursor move. Materializing the in-scope files and building an index for a +/// cursor sitting in the middle of an `always` block would stall the editor for +/// a fifth of a second on a large workspace; this answers `false` in +/// microseconds. It never says `false` where a refactoring would have +/// succeeded: every one of the three starts by locating exactly one of these +/// three constructs. +pub fn may_have_port_action(text: &str, offset: u32) -> bool { + let (tree, _) = parse_source_tolerant(text); + let mut instantiations = Vec::new(); + collect_instantiations(&tree.items, &mut instantiations); + let at_instantiation = instantiations.iter().any(|instantiation| { + instantiation.module_span.contains(offset) + || instantiation.instances.iter().any(|instance| instance.span.contains(offset)) + }); + if at_instantiation { + return true; + } + let mut module = None; + module_at(&tree.items, offset, &mut module); + let Some((module, _)) = module.and_then(|name| find_module(&tree, &name)) else { + return false; + }; + if declared_ports(module).iter().any(|port| port.span.contains(offset)) { + return true; + } + module.items.iter().any(|item| match &item.kind { + ItemKind::PortDecl(decl) => decl.declarators.iter().any(|d| d.span.contains(offset)), + _ => false, + }) +} + +/// "updates 3 instantiations" / "updates 1 instantiation" / "no instantiation +/// in scope". +fn sites_phrase(sites: usize) -> String { + match sites { + 0 => "no instantiation in scope".to_string(), + 1 => "updates 1 instantiation".to_string(), + n => format!("updates {n} instantiations"), + } +} + +// ---------------------------------------------------------------------- +// the plan +// ---------------------------------------------------------------------- + +/// Everything a port refactoring wants done, before it is verified. +#[derive(Default)] +struct Plan { + /// Source index → the edits for that file, sorted. + edits: Vec<(usize, Vec)>, + warnings: Vec, + /// What the edited text must say afterwards, per file. + expected: Vec<(usize, Shape)>, + /// How many instantiations the plan rewrites — what a code action's title + /// promises the user. + sites: usize, +} + +impl Plan { + /// Add one file's edits to the plan. + fn add(&mut self, file: usize, mut edits: Vec) { + if edits.is_empty() { + return; + } + if let Some((_, existing)) = self.edits.iter_mut().find(|(i, _)| *i == file) { + existing.append(&mut edits); + } else { + self.edits.push((file, edits)); + } + } + + /// Sort every file's edits and refuse two that overlap — a caller cannot + /// apply those, so the plan is abandoned before it is verified. + fn settle(&mut self) -> Result<(), String> { + for (_, edits) in &mut self.edits { + edits.sort_by_key(|e| (e.range.start, e.range.end)); + for pair in edits.windows(2) { + let (a, b) = (&pair[0], &pair[1]); + if b.range.start < a.range.end { + return Err(OVERLAP.to_string()); + } + } + } + self.edits.sort_by_key(|(i, _)| *i); + Ok(()) + } +} + +const OVERLAP: &str = "two of the edits vfmt computed overlap, so it made none."; + +/// Verify a plan and turn it into the refactoring's answer. +fn finish( + scope: &mut Scope, + mut plan: Plan, + module: &str, + what: &str, +) -> Result<(RefactorEdit, usize), String> { + plan.settle()?; + if plan.edits.is_empty() { + return Err(format!("vfmt found nothing to change for {what}.")); + } + check::verify_splice(scope, &plan.edits, module, what)?; + confirm(scope, &plan, module, what)?; + + let mut edits: Vec<(PathBuf, Vec)> = Vec::new(); + for (i, file_edits) in plan.edits { + let Some(path) = scope.path(i) else { + return Err(format!("vfmt could not name one of the files it edited for {what}.")); + }; + edits.push((path.to_path_buf(), file_edits)); + } + edits.sort_by(|a, b| a.0.cmp(&b.0)); + Ok((RefactorEdit { edits, warnings: plan.warnings }, plan.sites)) +} + +// ---------------------------------------------------------------------- +// the shape check +// ---------------------------------------------------------------------- + +/// What one file says about a module's signature: the module's own declared +/// port names, and every instantiation's connection names in order (`""` for a +/// positional connection, `"*"` for the wildcard). +/// +/// This is the "did it do what it said" check. `verify_splice` proves the edit +/// is lexically and semantically honest; nothing in it proves the new text +/// landed in the *port list* rather than in the parameter list, so the plan +/// also states the shape it expects and the shape is read back. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +struct Shape { + ports: Option>, + instances: Vec<(String, Vec)>, +} + +fn shape(text: &str, module: &str) -> Shape { + let (tree, _) = parse_source_tolerant(text); + let mut out = Shape::default(); + if let Some((declaration, _)) = find_module(&tree, module) { + out.ports = Some(declared_ports(declaration).into_iter().map(|p| p.name).collect()); + } + let mut instantiations = Vec::new(); + collect_instantiations(&tree.items, &mut instantiations); + for instantiation in instantiations { + if instantiation.module != module { + continue; + } + for instance in &instantiation.instances { + let names = match &instance.conns { + Connections::Named(conns) => conns.iter().map(|c| c.name.clone()).collect(), + Connections::Ordered(conns) => conns.iter().map(|_| String::new()).collect(), + }; + out.instances.push((instance.name.clone(), names)); + } + } + out +} + +/// Read the edited text back and require it to say what the plan promised. +fn confirm(scope: &Scope, plan: &Plan, module: &str, what: &str) -> Result<(), String> { + for (i, expected) in &plan.expected { + let (Some(text), Some(path)) = (scope.text(*i), scope.path(*i)) else { + return Err(format!("vfmt could not re-read a file it edited for {what}.")); + }; + let edits = plan.edits.iter().find(|(j, _)| j == i).map(|(_, e)| e.as_slice()); + let edited = crate::apply(text, edits.unwrap_or(&[])); + let actual = shape(&edited, module); + if &actual != expected { + return Err(format!( + "{what} would not leave {} with the signature vfmt intended; no edits were made.", + display(path) + )); + } + } + Ok(()) +} + +// ---------------------------------------------------------------------- +// finding things +// ---------------------------------------------------------------------- + +/// The module a refactoring acts on: which in-scope file declares it, and +/// under what name. +struct ModuleSite { + file: usize, + name: String, +} + +fn locate_module(scope: &mut Scope, module: ModuleRef<'_>) -> Result { + let name = match module { + ModuleRef::Name(name) => name.to_string(), + ModuleRef::At { file, offset } => { + let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) }; + let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) }; + let (tree, _) = parse_source_tolerant(text); + let mut found = None; + module_at(&tree.items, offset, &mut found); + match found { + Some(name) => name, + None => return Err("there is no module declaration at this position.".to_string()), + } + } + }; + let defs: Vec<_> = scope + .index() + .units(&name) + .iter() + .filter(|def| def.kind == SymbolKind::Module) + .cloned() + .collect(); + let [def] = defs.as_slice() else { + return Err(match defs.len() { + 0 => format!("vfmt indexes no module named `{name}`."), + _ => format!( + "`{name}` is declared in more than one indexed file; vfmt will not guess which module's ports these are." + ), + }); + }; + let Some(file) = scope.index().path(def.file).and_then(|p| scope.index_of(p)) else { + return Err(format!("`{name}`'s declaring file is not in scope.")); + }; + Ok(ModuleSite { file, name }) +} + +fn not_in_scope(file: &Path) -> String { + format!( + "{} is not one of the files vfmt indexes; nothing outside the project scope can be refactored.", + display(file) + ) +} + +/// The innermost module declaration covering an offset. +fn module_at(items: &[Item], offset: u32, found: &mut Option) { + for item in items { + if !item.span.contains(offset) { + continue; + } + match &item.kind { + ItemKind::Module(module) => { + *found = Some(module.name.clone()); + module_at(&module.items, offset, found); + } + ItemKind::Package { items, .. } => module_at(items, offset, found), + _ => {} + } + } +} + +/// The module node named `name` in a parsed file, with the span of the item +/// that holds it. +fn find_module<'t>(tree: &'t SourceFile, name: &str) -> Option<(&'t Module, TextRange)> { + fn walk<'t>(items: &'t [Item], name: &str) -> Option<(&'t Module, TextRange)> { + for item in items { + match &item.kind { + ItemKind::Module(module) if module.name == name => { + return Some((module, item.span)) + } + ItemKind::Module(module) => { + if let Some(found) = walk(&module.items, name) { + return Some(found); + } + } + ItemKind::Package { items, .. } => { + if let Some(found) = walk(items, name) { + return Some(found); + } + } + _ => {} + } + } + None + } + walk(&tree.items, name) +} + +/// One declared port: its name and where the name is written in the header. +struct DeclaredPort { + name: String, + /// The whole header element (`input logic [7:0] cfg`, or just `cfg`). + span: TextRange, +} + +fn declared_ports(module: &Module) -> Vec { + match &module.ports { + PortList::Ansi(ports) => ports + .iter() + .map(|port| DeclaredPort { name: port.name.clone(), span: port.span }) + .collect(), + PortList::NonAnsi(ports) => ports + .iter() + .map(|port| DeclaredPort { name: port.name.clone(), span: port.span }) + .collect(), + PortList::Empty | PortList::None => Vec::new(), + } +} + +/// Every instantiation written in a file, generate blocks and `bind` +/// directives included. +fn collect_instantiations<'t>(items: &'t [Item], out: &mut Vec<&'t Instantiation>) { + for item in items { + match &item.kind { + ItemKind::Instantiation(inst) => out.push(inst), + ItemKind::Bind(bind) => out.push(&bind.inst), + ItemKind::Module(module) => collect_instantiations(&module.items, out), + ItemKind::Package { items, .. } => collect_instantiations(items, out), + ItemKind::GenerateRegion { items, .. } => collect_instantiations(items, out), + ItemKind::GenIf(gen) => { + collect_gen_block(&gen.then, out); + let mut els = gen.els.as_deref(); + while let Some(next) = els { + match next { + GenElse::If(_, gen) => { + collect_gen_block(&gen.then, out); + els = gen.els.as_deref(); + } + GenElse::Block(block) => { + collect_gen_block(block, out); + els = None; + } + } + } + } + ItemKind::GenFor(gen) => collect_gen_block(&gen.body, out), + ItemKind::GenCase(gen) => { + for arm in &gen.items { + collect_gen_block(&arm.body, out); + } + } + _ => {} + } + } +} + +fn collect_gen_block<'t>(block: &'t GenBlock, out: &mut Vec<&'t Instantiation>) { + collect_instantiations(&block.items, out); +} + +// ---------------------------------------------------------------------- +// the free-form input: one port declaration +// ---------------------------------------------------------------------- + +/// A port declaration the user typed, once vfmt has agreed that it is one. +struct NewPort { + name: String, + /// The declaration as written, trimmed. + text: String, +} + +/// Parse `decl` as exactly one ANSI port declaration, or say why it is not. +/// +/// The formatter-grade suspicion the milestone asks for: the string is lexed +/// (no comments, no directives, no macro calls), planted in a throwaway module +/// header, parsed, and then required to have produced precisely one port with +/// an explicit direction and nothing else — no second port, no module item a +/// stray `)` could have opened, no leftovers. +fn parse_port_decl(decl: &str) -> Result { + let text = decl.trim(); + if text.is_empty() { + return Err("a port declaration cannot be empty.".to_string()); + } + let refusal = format!("`{text}` is not a single ANSI port declaration."); + let Ok(tokens) = tokenize(text) else { return Err(refusal) }; + if tokens.iter().any(|t| !t.leading.is_empty() || t.trailing.is_some()) { + return Err( + "a port declaration vfmt writes into a header must carry no comment.".to_string() + ); + } + if tokens.iter().any(|t| t.kind == TokenKind::Directive || t.is_macro()) { + return Err( + "a port declaration vfmt writes into a header must contain no compiler directive or macro call: vfmt does not preprocess." + .to_string(), + ); + } + let probe = format!("module __vfmt_port_probe ({text});\nendmodule\n"); + let (tree, diagnostics) = parse_source_tolerant(&probe); + if !diagnostics.is_empty() { + return Err(refusal); + } + let [item] = tree.items.as_slice() else { return Err(refusal) }; + let ItemKind::Module(module) = &item.kind else { return Err(refusal) }; + if !module.items.is_empty() || !module.port_directives.is_empty() { + return Err(refusal); + } + let PortList::Ansi(ports) = &module.ports else { return Err(refusal) }; + let [port] = ports.as_slice() else { return Err(refusal) }; + if port.comma { + return Err(refusal); + } + if port.dir.is_none() { + return Err(format!( + "`{text}` does not say a direction; a port vfmt adds must start with `input`, `output` or `inout`." + )); + } + if port.name.is_empty() { + return Err(refusal); + } + Ok(NewPort { name: port.name.clone(), text: text.to_string() }) +} + +// ---------------------------------------------------------------------- +// add +// ---------------------------------------------------------------------- + +fn plan_add(scope: &mut Scope, site: &ModuleSite, port: &NewPort) -> Result { + let Some(text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) }; + let (tree, _) = parse_source_tolerant(text); + let Some((module, item_span)) = find_module(&tree, &site.name) else { + return Err(not_indexed(&site.name)); + }; + let existing = declared_ports(module); + if existing.iter().any(|p| p.name == port.name) { + return Err(format!("`{}` already has a port named `{}`.", site.name, port.name)); + } + let Some(path) = scope.path(site.file) else { return Err(not_indexed(&site.name)) }; + let tokens = tokenize(text).map_err(|_| lex_failed(Some(path)))?; + let file = File { text, path, tokens }; + + let mut plan = Plan::default(); + let header = header_edits(&file, module, item_span, port, &existing, &mut plan.warnings)?; + let mut names: Vec = existing.iter().map(|p| p.name.clone()).collect(); + names.push(port.name.clone()); + plan.add(site.file, header); + + let ports_before = existing.len(); + for i in 0..scope.len() { + let (edits, sites) = + instantiation_edits(scope, i, site, port, ports_before, &mut plan.warnings)?; + plan.sites += sites; + plan.add(i, edits); + } + // Every file's expected shape: the module's file gains the port, and every + // instantiation gains its connection. + for i in plan.edits.iter().map(|(i, _)| *i).collect::>() { + let Some(text) = scope.text(i) else { continue }; + let mut expected = shape(text, &site.name); + if i == site.file { + expected.ports = Some(names.clone()); + } + for (_, conns) in &mut expected.instances { + // A wildcard site and an empty positional list are both left + // exactly as they are. + if conns.is_empty() + || conns.iter().any(|c| c == "*") + || conns.iter().any(|c| c == &port.name) + { + continue; + } + match conns.iter().all(String::is_empty) { + true => conns.push(String::new()), + false => conns.push(port.name.clone()), + } + } + plan.expected.push((i, expected)); + } + Ok(plan) +} + +fn not_indexed(name: &str) -> String { + format!("vfmt can no longer find the declaration of `{name}`.") +} + +fn lex_failed(path: Option<&Path>) -> String { + format!("{} does not lex, so vfmt will not edit it.", display(path.unwrap_or(Path::new("?")))) +} + +/// The file a module is written in, as the planners read it: its text, its +/// name for a message, and its tokens. +struct File<'a> { + text: &'a str, + path: &'a Path, + tokens: Vec, +} + +/// The edits that add the port to the module's own declaration. +fn header_edits( + file: &File<'_>, + module: &Module, + item_span: TextRange, + port: &NewPort, + existing: &[DeclaredPort], + warnings: &mut Vec, +) -> Result, String> { + let (text, path, tokens) = (file.text, file.path, file.tokens.as_slice()); + let name_end = module.name_span.end; + let list = list_directives(module); + let header = format!("`{}`'s port list", module.name); + match &module.ports { + PortList::Ansi(_) if !existing.is_empty() => { + let open = port_list_open(tokens, name_end); + let edits = append_to_list(text, open, &element_spans(existing), &port.text); + guard_conditionals(&list, written_at(&edits), &header, text, path, warnings)?; + Ok(edits) + } + PortList::NonAnsi(_) if !existing.is_empty() => { + let open = port_list_open(tokens, name_end); + let mut edits = append_to_list(text, open, &element_spans(existing), &port.name); + guard_conditionals(&list, written_at(&edits), &header, text, path, warnings)?; + let declaration = non_ansi_declaration(text, module, item_span, tokens, &port.text)?; + guard_conditionals( + &body_directives(module), + declaration.range.start, + &format!("the body of `{}`", module.name), + text, + path, + warnings, + )?; + edits.push(declaration); + Ok(edits) + } + // An empty port list has no style to follow, so the port is written + // the modern way: ANSI, in the header. + PortList::Empty | PortList::Ansi(_) | PortList::NonAnsi(_) => { + let Some(open) = port_list_open(tokens, name_end) else { + return Err("vfmt cannot find this module's port list.".to_string()); + }; + let edits = append_to_list(text, Some(open), &[], &port.text); + guard_conditionals(&list, written_at(&edits), &header, text, path, warnings)?; + Ok(edits) + } + PortList::None => { + if !module.imports.is_empty() { + return Err(format!( + "`{}` writes an `import` in its header and has no port list; write `()` first and vfmt will fill it in.", + module.name + )); + } + let Some(semi) = header_semicolon(tokens, name_end) else { + return Err("vfmt cannot find where this module's header ends.".to_string()); + }; + Ok(vec![insert(semi, format!(" ({})", port.text))]) + } + } +} + +/// Where an append writes its new element: the last of its edits, since the +/// one before it is only the comma that makes room. +fn written_at(edits: &[TextEdit]) -> u32 { + edits.last().map_or(0, |edit| edit.range.start) +} + +/// The `(name, span, trailing comment)` triples a list append needs. +fn element_spans(ports: &[DeclaredPort]) -> Vec { + ports.iter().map(|p| p.span).collect() +} + +// ---------------------------------------------------------------------- +// conditional compilation +// ---------------------------------------------------------------------- + +/// One compiler directive written inside a port list or a module body, and +/// where it is written. +struct Directive { + text: String, + span: TextRange, +} + +/// What a directive does to the conditional nesting depth. +enum Nesting { + Open, + Close, + Neither, +} + +fn nesting_of(directive: &str) -> Nesting { + let word = directive.split_whitespace().next().unwrap_or_default(); + match word { + "`ifdef" | "`ifndef" => Nesting::Open, + "`endif" => Nesting::Close, + // `else` and `elsif` continue the region they are in rather than + // opening or closing one. + _ => Nesting::Neither, + } +} + +/// The directives written *between the elements* of a module's port list. +fn list_directives(module: &Module) -> Vec { + module + .port_directives + .iter() + .map(|directive| Directive { text: directive.raw.text.clone(), span: directive.raw.span }) + .collect() +} + +/// The directives written among a module's items — where a non-ANSI port +/// declaration goes. A macro *item* (`` `ASSERT_INIT(...) ``) is not collected: +/// it is a call, not a directive, and cannot open a conditional region. +fn body_directives(module: &Module) -> Vec { + module + .items + .iter() + .filter_map(|item| match &item.kind { + ItemKind::Directive(raw) => Some(Directive { text: raw.text.clone(), span: raw.span }), + _ => None, + }) + .collect() +} + +/// Refuse an insertion that would land **inside** a conditional arm, and warn +/// when the region it joins is conditionally compiled at all. +/// +/// vfmt does not preprocess, so an `` `ifdef`` arm is ordinary text to it: a +/// port appended after the last declared port lands wherever that port sits, +/// conditional arm included, and every later check would wave it through — +/// the file parses, no name changes meaning, and the re-parsed header really +/// does declare the port, because vfmt reads through the `` `ifdef``. Only the +/// *plan* can catch this, so it is caught here: count the arms open at the +/// insertion point, and refuse when the count is not zero. +fn guard_conditionals( + directives: &[Directive], + at: u32, + region: &str, + text: &str, + path: &Path, + warnings: &mut Vec, +) -> Result<(), String> { + if directives.is_empty() { + return Ok(()); + } + let lines = LineIndex::new(text); + let where_ = |span: TextRange| format!("{}:{}", display(path), lines.line_col(span.start).0); + let mut depth = 0i32; + let mut opened: Option<&Directive> = None; + for directive in directives.iter().filter(|d| d.span.start < at) { + match nesting_of(&directive.text) { + Nesting::Open => { + depth += 1; + opened = Some(directive); + } + Nesting::Close => depth -= 1, + Nesting::Neither => {} + } + } + if depth > 0 { + let arm = opened.map_or_else(String::new, |d| { + format!(" opened by `{}` at {}", first_line(&d.text), where_(d.span)) + }); + return Err(format!( + "{region} is conditionally compiled, and the new port would land inside the arm{arm}; a port added to one arm of an `ifdef does not exist in the other, so vfmt made no edits — place it by hand." + )); + } + if depth != 0 { + return Err(format!( + "the compiler directives in {region} do not balance, so vfmt cannot tell whether a new port would be conditionally compiled; it made no edits." + )); + } + let first = directives.first(); + let named = first + .map_or_else(String::new, |d| format!("`{}` at {}", first_line(&d.text), where_(d.span))); + let rest = directives.len() - 1; + let more = match rest { + 0 => String::new(), + 1 => ", and 1 more".to_string(), + n => format!(", and {n} more"), + }; + warnings.push(format!( + "{region} carries compiler directives ({named}{more}), so what ports it declares depends on the configuration; vfmt added the port outside every conditional arm." + )); + Ok(()) +} + +/// A directive's first line, for a message: the raw text may be a multi-line +/// `` `define``, and a warning is not the place to print all of it. +fn first_line(directive: &str) -> &str { + directive.trim().lines().next().unwrap_or_default().trim_end() +} + +/// Where the non-ANSI body declaration of a new port goes. +fn non_ansi_declaration( + text: &str, + module: &Module, + item_span: TextRange, + tokens: &[Token], + decl: &str, +) -> Result { + let last_port_decl = + module.items.iter().rfind(|item| matches!(item.kind, ItemKind::PortDecl(_))); + if let Some(item) = last_port_decl { + let after = after_same_line_comments(text, item.span.end); + let indent = line_indent(text, item.span.start); + return Ok(insert(after.at, format!("\n{indent}{decl};"))); + } + if let Some(item) = module.items.first() { + let start = item.meta.leading.first().map_or(item.span.start, |comment| comment.span.start); + let indent = line_indent(text, start); + return Ok(insert(start, format!("{decl};\n{indent}"))); + } + // A non-ANSI module with a header port list and no items at all is not + // legal Verilog, but a tolerant parse can still hand one over. + let Some(semi) = header_semicolon(tokens, module.name_span.end) else { + return Err("vfmt cannot find where this module's header ends.".to_string()); + }; + let indent = format!("{} ", line_indent(text, item_span.start)); + Ok(insert(semi + 1, format!("\n{indent}{decl};"))) +} + +/// The edits that give one file's instantiations of the module a connection +/// for the new port. +fn instantiation_edits( + scope: &mut Scope, + file: usize, + site: &ModuleSite, + port: &NewPort, + ports_before: usize, + warnings: &mut Vec, +) -> Result<(Vec, usize), String> { + let (Some(text), Some(path)) = (scope.text(file), scope.path(file)) else { + return Ok((Vec::new(), 0)); + }; + if !text.contains(&site.name) { + return Ok((Vec::new(), 0)); + } + let (tree, _) = parse_source_tolerant(text); + let mut instantiations = Vec::new(); + collect_instantiations(&tree.items, &mut instantiations); + let lines = LineIndex::new(text); + + // Every place a connection could go, collected first so the semantic + // lookups below can borrow the scope on their own. + let mut named: Vec<(&Instance, Vec, Option)> = Vec::new(); + let mut ordered: Vec<(&Instance, Vec)> = Vec::new(); + let mut wildcards: Vec<&Instance> = Vec::new(); + for instantiation in instantiations.iter().filter(|i| i.module == site.name) { + for instance in &instantiation.instances { + match &instance.conns { + Connections::Named(conns) if conns.iter().any(|c| c.name == "*") => { + wildcards.push(instance) + } + Connections::Named(conns) => { + if conns.iter().any(|c| c.name == port.name) { + continue; + } + named.push(( + instance, + conns.iter().map(|c| c.span).collect(), + conn_list_open(text, instance, conns.first().map(|c| c.span)), + )); + } + // An empty list connects nothing, so a new port changes + // nothing there: it stays unconnected either way. + Connections::Ordered(conns) if conns.is_empty() => { + warnings.push(format!( + "`{}` at {}:{} writes an empty connection list, so `{}` is left unconnected there.", + instance.name, + display(path), + lines.line_col(instance.name_span.start).0, + port.name + )); + } + Connections::Ordered(conns) => { + if conns.len() != ports_before { + return Err(format!( + "`{}` in {} connects {} of `{}`'s {ports_before} port(s) by position, so vfmt cannot tell where a new one goes; give it named connections first.", + instance.name, + display(path), + conns.len(), + site.name + )); + } + ordered.push((instance, conns.iter().map(|c| c.span).collect())); + } + } + } + } + + for instance in &wildcards { + let visible = name_visible(scope, file, instance.name_span.start, &port.name); + if !visible { + warnings.push(format!( + "`{}` at {}:{} connects with `.*` and {} has no signal named `{}`, so the new port will not bind; connect it by hand.", + instance.name, + display(path), + lines.line_col(instance.name_span.start).0, + display(path), + port.name + )); + } + } + + let mut edits = Vec::new(); + let mut todo: Vec = Vec::new(); + let mut empty: Vec = Vec::new(); + let sites = named.len() + ordered.len(); + for (instance, spans, open) in named { + let visible = name_visible(scope, file, instance.name_span.start, &port.name); + let expr = if visible { + port.name.clone() + } else { + todo.push(at_site(&instance.name, path, &lines, instance.name_span.start)); + "/* TODO: connect */".to_string() + }; + let element = format!(".{}({expr})", port.name); + let open = match open { + Some(open) => open, + None => return Err(missing_parens(&instance.name, path)), + }; + edits.extend(append_to_list(text, Some(open), &spans, &element)); + } + for (instance, spans) in ordered { + let visible = name_visible(scope, file, instance.name_span.start, &port.name); + // A positional connection has nowhere to put a `/* TODO */` — a + // comment between two commas is an *empty* position, not a + // placeholder — so an unconnectable one is written as the empty + // position it is, and said out loud. + let expr = if visible { + port.name.clone() + } else { + empty.push(at_site(&instance.name, path, &lines, instance.name_span.start)); + String::new() + }; + let Some(open) = conn_list_open(text, instance, spans.first().copied()) else { + return Err(missing_parens(&instance.name, path)); + }; + edits.extend(append_to_list(text, Some(open), &spans, &expr)); + } + if !todo.is_empty() { + warnings.push(format!( + "no signal named `{}` is in scope at {}, so its connection was left as `/* TODO: connect */`.", + port.name, + todo.join(", ") + )); + } + if !empty.is_empty() { + warnings.push(format!( + "no signal named `{}` is in scope at {}, so the new positional connection was left empty.", + port.name, + empty.join(", ") + )); + } + Ok((edits, sites)) +} + +/// How one instantiation site is named in a warning: `` `u_sub` (top.sv:12) ``. +fn at_site(instance: &str, path: &Path, lines: &LineIndex, offset: u32) -> String { + format!("`{instance}` ({}:{})", display(path), lines.line_col(offset).0) +} + +fn missing_parens(instance: &str, path: &Path) -> String { + format!( + "vfmt cannot find the connection list of `{instance}` in {}; no edits were made.", + display(path) + ) +} + +// ---------------------------------------------------------------------- +// remove +// ---------------------------------------------------------------------- + +/// The module and port name a removal request points at. The cursor may sit on +/// the header port or, for a non-ANSI module, on its body declaration. +fn locate_port( + scope: &mut Scope, + file: &Path, + offset: u32, +) -> Result<(ModuleSite, String), String> { + let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) }; + let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) }; + let (tree, _) = parse_source_tolerant(text); + let mut module_name = None; + module_at(&tree.items, offset, &mut module_name); + let Some(module_name) = module_name else { + return Err(NOT_A_PORT.to_string()); + }; + let Some((module, _)) = find_module(&tree, &module_name) else { + return Err(NOT_A_PORT.to_string()); + }; + let ports = declared_ports(module); + let mut name = ports.iter().find(|p| p.span.contains(offset)).map(|p| p.name.clone()); + if name.is_none() { + // The cursor may be on the non-ANSI body declaration instead. + for item in &module.items { + let ItemKind::PortDecl(decl) = &item.kind else { continue }; + for declarator in &decl.declarators { + if declarator.span.contains(offset) || declarator.name_span.contains(offset) { + name = Some(declarator.name.clone()); + } + } + } + // ...and it must still be a port of this module. + if let Some(found) = &name { + if !ports.iter().any(|p| &p.name == found) { + return Err(NOT_A_PORT.to_string()); + } + } + } + let Some(name) = name else { return Err(NOT_A_PORT.to_string()) }; + let site = locate_module(scope, ModuleRef::Name(&module_name))?; + if site.file != i { + return Err(format!( + "`{module_name}` is declared in more than one indexed file; vfmt will not guess which module's ports these are." + )); + } + Ok((site, name)) +} + +const NOT_A_PORT: &str = "there is no module port at this position."; + +fn plan_remove(scope: &mut Scope, site: &ModuleSite, port: &str) -> Result { + let Some(text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) }; + let Some(path) = scope.path(site.file) else { return Err(not_indexed(&site.name)) }; + let (tree, _) = parse_source_tolerant(text); + let Some((module, _)) = find_module(&tree, &site.name) else { + return Err(not_indexed(&site.name)); + }; + let ports = declared_ports(module); + let Some(index) = ports.iter().position(|p| p.name == port) else { + return Err(format!("`{}` has no port named `{port}`.", site.name)); + }; + + let mut header: Vec = remove_element(text, &element_spans(&ports), index)?; + if matches!(module.ports, PortList::NonAnsi(_)) { + header.append(&mut non_ansi_declaration_removal(text, module, port)?); + } + // A port still used by the module's own body is a refusal, not a warning: + // deleting it would leave the body naming something that no longer exists. + let used = body_uses(scope, site.file, module, port, &header); + if !used.is_empty() { + return Err(format!( + "`{port}` is still used inside `{}` at {}:{}; remove those uses first.", + site.name, + display(path), + used.join(", ") + )); + } + + let mut plan = Plan::default(); + plan.add(site.file, header); + for i in 0..scope.len() { + let (edits, sites) = disconnection_edits(scope, i, site, port, &mut plan.warnings)?; + plan.sites += sites; + plan.add(i, edits); + } + // What the preprocessor owns, vfmt cannot edit — and after a removal, what + // it owns may name a port that no longer exists. + let mut watched: Vec = plan.edits.iter().map(|(i, _)| *i).collect(); + if !watched.contains(&site.file) { + watched.push(site.file); + } + watched.sort_unstable(); + for &i in &watched { + plan.warnings.extend(preprocessor_warnings(scope, i, port)); + } + + let mut names: Vec = ports.iter().map(|p| p.name.clone()).collect(); + names.remove(index); + for i in plan.edits.iter().map(|(i, _)| *i).collect::>() { + let Some(text) = scope.text(i) else { continue }; + let mut expected = shape(text, &site.name); + if i == site.file { + expected.ports = Some(names.clone()); + } + for (_, conns) in &mut expected.instances { + conns.retain(|name| name != port); + } + plan.expected.push((i, expected)); + } + Ok(plan) +} + +/// Every place in one file where the removed port's name lives in text the +/// preprocessor owns: a macro invocation's arguments, or a `` `define`` body. +/// +/// vfmt does not expand macros — a macro invocation is one opaque token, so +/// `` `BUMP(rst) `` records no reference for `body_uses` to find and no span +/// for an edit to land on. Silence would be the worst answer: the file still +/// parses and still *looks* right, and only a real preprocessor discovers that +/// the expansion names a port that no longer exists. The same scan M2 added to +/// rename after QA found the same hole there (`Scope::macro_argument_sites`, +/// `Scope::define_sites`) answers it here, with news of its own. +fn preprocessor_warnings(scope: &Scope, file: usize, port: &str) -> Vec { + let where_ = display(scope.path(file).unwrap_or(Path::new("?"))); + let mut out = Vec::new(); + for site in scope.macro_argument_sites(file, port) { + out.push(format!( + "`{port}` appears in the arguments of the macro invocation `{}` at {where_}:{}; a macro invocation is one opaque token to vfmt, so nothing was removed there and that expansion now names a port `{port}`'s module no longer has.", + site.macro_name, site.line + )); + } + for site in scope.define_sites(file, port) { + // A macro *named* like the port is not news for a removal; a macro + // whose body spells it is. + if site.defines_the_name.is_some() { + continue; + } + out.push(format!( + "`{port}` appears in the body of macro `{}` at {where_}:{}; vfmt does not preprocess, so that body still names the removed port.", + site.macro_name, site.line + )); + } + out +} + +/// The lines of the module's body that still name the port, ignoring the +/// declarations the removal is itself deleting. +fn body_uses( + scope: &mut Scope, + file: usize, + module: &Module, + port: &str, + removed: &[TextEdit], +) -> Vec { + let Some(text) = scope.text(file) else { return Vec::new() }; + let lines = LineIndex::new(text); + let Some(analysis) = scope.analysis(file) else { return Vec::new() }; + let semantics = &analysis.semantics; + let Some(symbol) = semantics.symbols().iter().position(|s| { + s.name == port + && s.kind == SymbolKind::Port + && module_span(module).contains(s.name_span.start) + }) else { + return Vec::new(); + }; + let id = vlog_semantic::SymbolId(symbol as u32); + let mut out: Vec = Vec::new(); + for reference in semantics.references_of(id) { + let span = reference.name_span; + if removed.iter().any(|e| e.range.start <= span.start && span.end <= e.range.end) { + continue; + } + let line = lines.line_col(span.start).0.to_string(); + if !out.contains(&line) { + out.push(line); + } + } + out +} + +/// The bytes a module covers, taken from its name and its last item — the +/// `Module` node carries no span of its own. +fn module_span(module: &Module) -> TextRange { + let end = module.items.last().map_or(module.name_span.end, |item| item.span.end); + TextRange::new(module.name_span.start, end.max(module.name_span.end)) +} + +/// Delete the non-ANSI body declaration of a port: the whole item when it +/// declares only this port, otherwise just its declarator. +fn non_ansi_declaration_removal( + text: &str, + module: &Module, + port: &str, +) -> Result, String> { + for item in &module.items { + let ItemKind::PortDecl(decl) = &item.kind else { continue }; + let Some(index) = decl.declarators.iter().position(|d| d.name == port) else { continue }; + if decl.declarators.len() == 1 { + return Ok(vec![TextEdit { + range: whole_line(text, item.span), + new_text: String::new(), + }]); + } + let spans: Vec = decl.declarators.iter().map(|d| d.span).collect(); + return remove_element(text, &spans, index); + } + Err(format!("`{port}` has no declaration in the body of `{}`.", module.name)) +} + +/// The edits that take the port's connection out of one file's instantiations. +fn disconnection_edits( + scope: &mut Scope, + file: usize, + site: &ModuleSite, + port: &str, + warnings: &mut Vec, +) -> Result<(Vec, usize), String> { + let (Some(text), Some(path)) = (scope.text(file), scope.path(file)) else { + return Ok((Vec::new(), 0)); + }; + if !text.contains(&site.name) { + return Ok((Vec::new(), 0)); + } + let (tree, _) = parse_source_tolerant(text); + let mut instantiations = Vec::new(); + collect_instantiations(&tree.items, &mut instantiations); + let lines = LineIndex::new(text); + + let mut edits = Vec::new(); + let mut sites = 0usize; + for instantiation in instantiations.iter().filter(|i| i.module == site.name) { + for instance in &instantiation.instances { + match &instance.conns { + Connections::Ordered(conns) if conns.is_empty() => {} + Connections::Ordered(_) => { + return Err(format!( + "`{}` in {} connects `{}`'s ports by position; dropping one would silently re-bind the rest, so vfmt made no edits — give it named connections first.", + instance.name, + display(path), + site.name + )) + } + Connections::Named(conns) => { + // `.*` binds the port implicitly, so there is nothing to + // delete — and the signal it was binding may now have no + // reader at all, which is worth saying. + if conns.iter().any(|c| c.name == "*") && conns.iter().all(|c| c.name != port) { + warnings.push(format!( + "`{}` at {}:{} connects with `.*`, so nothing was removed there; the signal it bound `{port}` to may now be unused.", + instance.name, + display(path), + lines.line_col(instance.name_span.start).0 + )); + continue; + } + let Some(index) = conns.iter().position(|c| c.name == port) else { continue }; + // The connected expression goes with the connection. A + // plain `.p(p)` loses nothing; anything else is said out + // loud, because it is the user's code being deleted. + if let Some(expr) = conns.get(index) { + let written = text.get(expr.span.as_range()).unwrap_or(""); + let trivial = written == format!(".{port}({port})") + || written == format!(".{port}()") + || written == format!(".{port}"); + if !trivial { + warnings.push(format!( + "`{written}` at {}:{} was deleted with the port.", + display(path), + lines.line_col(expr.span.start).0 + )); + } + } + let spans: Vec = conns.iter().map(|c| c.span).collect(); + sites += 1; + edits.append(&mut remove_element(text, &spans, index)?); + } + } + } + } + Ok((edits, sites)) +} + +// ---------------------------------------------------------------------- +// propagate +// ---------------------------------------------------------------------- + +fn plan_propagate( + scope: &mut Scope, + file: &Path, + offset: u32, +) -> Result<(ModuleSite, Plan), String> { + let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) }; + let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) }; + let (tree, _) = parse_source_tolerant(text); + let mut instantiations = Vec::new(); + collect_instantiations(&tree.items, &mut instantiations); + + // The instance under the cursor, or the only one of the instantiation the + // cursor's module name belongs to. + let mut found: Option<(&Instantiation, &Instance)> = None; + for instantiation in &instantiations { + for instance in &instantiation.instances { + if instance.span.contains(offset) { + found = Some((instantiation, instance)); + } + } + if found.is_none() && instantiation.module_span.contains(offset) { + let [only] = instantiation.instances.as_slice() else { + return Err(format!( + "this statement declares {} instances of `{}`; put the cursor on the one to connect.", + instantiation.instances.len(), + instantiation.module + )); + }; + found = Some((instantiation, only)); + } + } + let Some((instantiation, instance)) = found else { + return Err("there is no module instantiation at this position.".to_string()); + }; + let site = locate_module(scope, ModuleRef::Name(&instantiation.module))?; + + let conns = match &instance.conns { + Connections::Ordered(_) => { + return Err(format!( + "`{}` connects `{}`'s ports by position; vfmt propagates named connections only.", + instance.name, instantiation.module + )) + } + Connections::Named(conns) => conns, + }; + if conns.iter().any(|c| c.name == "*") { + return Err(format!( + "`{}` connects with `.*`, which already binds every same-named port.", + instance.name + )); + } + + let Some(module_text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) }; + let (module_tree, _) = parse_source_tolerant(module_text); + let Some((module, _)) = find_module(&module_tree, &site.name) else { + return Err(not_indexed(&site.name)); + }; + let declared = declared_ports(module); + let missing: Vec = declared + .iter() + .map(|p| p.name.clone()) + .filter(|name| conns.iter().all(|c| &c.name != name)) + .collect(); + if missing.is_empty() { + return Err(format!( + "`{}` already connects every port `{}` declares.", + instance.name, site.name + )); + } + + let spans: Vec = conns.iter().map(|c| c.span).collect(); + let Some(open) = conn_list_open(text, instance, spans.first().copied()) else { + return Err(missing_parens(&instance.name, file)); + }; + let lines = LineIndex::new(text); + let at = instance.name_span.start; + let instance_name = instance.name.clone(); + + let mut plan = Plan::default(); + let mut edits = Vec::new(); + let mut spans = spans; + let mut todo: Vec = Vec::new(); + let mut connected: Vec = conns.iter().map(|c| c.name.clone()).collect(); + for name in &missing { + let expr = if name_visible(scope, i, at, name) { + name.clone() + } else { + todo.push(name.clone()); + "/* TODO: connect */".to_string() + }; + let element = format!(".{name}({expr})"); + let mut written = append_to_list(text, Some(open), &spans, &element); + // Each connection is appended after the previous one, so the next + // append sees it as the list's last element. + let start = written.last().map_or(open, |edit| edit.range.start); + spans.push(TextRange::new(start, start)); + edits.append(&mut written); + connected.push(name.clone()); + } + if !todo.is_empty() { + plan.warnings.push(format!( + "no signal named {} is in scope at {}:{}, so those connections were left as `/* TODO: connect */`.", + todo.iter().map(|n| format!("`{n}`")).collect::>().join(", "), + display(file), + lines.line_col(at).0 + )); + } + plan.sites = 1; + plan.add(i, edits); + let mut expected = shape(text, &site.name); + for (name, conns) in &mut expected.instances { + if name == &instance_name { + *conns = connected.clone(); + } + } + plan.expected.push((i, expected)); + Ok((site, plan)) +} + +// ---------------------------------------------------------------------- +// editing a comma-separated list +// ---------------------------------------------------------------------- + +fn insert(at: u32, text: String) -> TextEdit { + TextEdit { range: TextRange::empty(at), new_text: text } +} + +/// Append one element to a parenthesized comma-separated list. +/// +/// The layout is copied from the list itself: an element per line keeps an +/// element per line, at the last element's own indentation; an inline list +/// stays inline. When the last element carries a line comment the comma is +/// written *before* the comment and the new element after it, because a `,` +/// written after `//` is a `,` inside a comment. +fn append_to_list( + text: &str, + open: Option, + elements: &[TextRange], + element: &str, +) -> Vec { + let Some(last) = elements.last() else { + // An empty list: the new element is the only one, written just before + // the `)`. + return match open { + Some(open) => vec![insert(close_paren(text, open).unwrap_or(open + 1), element.into())], + None => Vec::new(), + }; + }; + let previous = elements.len().checked_sub(2).and_then(|n| elements.get(n)).map(|e| e.end); + let gap_from = previous.or(open); + let one_per_line = gap_from + .and_then(|from| text.get(from as usize..last.start as usize)) + .is_some_and(|gap| gap.contains('\n')); + let indent = line_indent(text, last.start); + let separator = match one_per_line { + true => format!(",\n{indent}"), + false => ", ".to_string(), + }; + + let after = after_same_line_comments(text, last.end); + match after.line_comment { + // `input a // why`: the comma goes before the comment, the element on + // the next line — which is where the source was going to put it anyway. + true => vec![ + insert(last.end, ",".to_string()), + insert(after.at, format!("\n{indent}{element}")), + ], + false => vec![insert(after.at, format!("{separator}{element}"))], + } +} + +/// Delete element `index` from a comma-separated list, taking the comma that +/// keeps the list well-formed with it: the one after the element, or — for the +/// last element — the one before it. +/// +/// The last element's comma is a **deletion of its own** rather than part of +/// one range, because the source may have written a comment between the two +/// (`.a(x), // about a` ⏎ `.b(y)`) and one range would swallow it. +fn remove_element( + text: &str, + elements: &[TextRange], + index: usize, +) -> Result, String> { + let Some(element) = elements.get(index) else { + return Err("vfmt lost track of the element it was removing.".to_string()); + }; + let delete = |range: TextRange| TextEdit { range, new_text: String::new() }; + if elements.len() == 1 { + return Ok(vec![delete(whole_line(text, *element))]); + } + if index + 1 < elements.len() { + return Ok(match comma_after(text, element.end) { + // The blanks after the comma go too, so `a, b, c` minus `b` is + // `a, c` and not `a, c`. + Some(comma) => vec![delete(whole_line( + text, + TextRange::new(element.start, blanks_after(text, comma + 1)), + ))], + None => vec![delete(whole_line(text, *element))], + }); + } + // The last element: its comma is the one after the element before it, + // which is where a forward scan finds it without guessing. + let previous = index.checked_sub(1).and_then(|n| elements.get(n)); + let comma = previous.and_then(|previous| comma_after(text, previous.end)); + let mut edits = Vec::new(); + if let Some(comma) = comma { + // The blanks after the comma go with it, unless a comment follows: + // `.a(x), // about a` must not become `.a(x)// about a`. + let next = blanks_after(text, comma + 1); + let comment = text + .get(next as usize..) + .is_some_and(|rest| rest.starts_with("//") || rest.starts_with("/*")); + edits.push(delete(TextRange::new(comma, if comment { comma + 1 } else { next }))); + } + edits.push(delete(whole_line(text, *element))); + Ok(edits) +} + +/// Widen a deletion to the whole line when nothing else is written on it, so +/// removing a one-per-line element does not leave a blank line behind. A line +/// that holds anything else — code or a comment — is left exactly as it is. +fn whole_line(text: &str, range: TextRange) -> TextRange { + let (start, end) = (range.start as usize, range.end as usize); + let line_start = + text.get(..start).map_or(0, |before| before.rfind('\n').map_or(0, |newline| newline + 1)); + let Some(head) = text.get(line_start..start) else { return range }; + if !head.chars().all(|c| c == ' ' || c == '\t') { + return range; + } + let Some(tail) = text.get(end..) else { return range }; + let line_end = tail.find('\n').map_or(tail.len(), |n| n + 1); + let Some(rest) = tail.get(..line_end) else { return range }; + if !rest.chars().all(|c| c == ' ' || c == '\t' || c == '\n' || c == '\r') { + return range; + } + TextRange::new(line_start as u32, (end + line_end) as u32) +} + +/// Where an append must write, once the comments the source put after the last +/// element are accounted for. +struct AfterElement { + at: u32, + /// True when the element is followed by a `//` comment, which nothing may + /// be written into. + line_comment: bool, +} + +fn after_same_line_comments(text: &str, end: u32) -> AfterElement { + let mut at = end as usize; + loop { + let Some(rest) = text.get(at..) else { + return AfterElement { at: at as u32, line_comment: false }; + }; + let skipped = rest.len() - rest.trim_start_matches([' ', '\t']).len(); + let rest = &rest[skipped..]; + if rest.starts_with("//") { + let line = rest.find('\n').unwrap_or(rest.len()); + return AfterElement { at: (at + skipped + line) as u32, line_comment: true }; + } + if rest.starts_with("/*") { + let Some(close) = rest.find("*/") else { + return AfterElement { at: at as u32, line_comment: false }; + }; + if rest[..close].contains('\n') { + return AfterElement { at: at as u32, line_comment: false }; + } + at += skipped + close + 2; + continue; + } + return AfterElement { at: at as u32, line_comment: false }; + } +} + +/// The whitespace the line holding `offset` starts with, or nothing when +/// `offset` is not the first thing written on its line. +fn line_indent(text: &str, offset: u32) -> String { + let offset = offset as usize; + let line_start = text.get(..offset).map_or(0, |before| before.rfind('\n').map_or(0, |n| n + 1)); + let Some(head) = text.get(line_start..offset) else { return String::new() }; + match head.chars().all(|c| c == ' ' || c == '\t') { + true => head.to_string(), + false => String::new(), + } +} + +/// The `,` written after `end`, skipping whitespace and comments. +fn comma_after(text: &str, end: u32) -> Option { + let mut at = end as usize; + loop { + let rest = text.get(at..)?; + let skipped = rest.len() - rest.trim_start().len(); + at += skipped; + let rest = text.get(at..)?; + if rest.starts_with("//") { + at += rest.find('\n').unwrap_or(rest.len()); + continue; + } + if rest.starts_with("/*") { + at += rest.find("*/")? + 2; + continue; + } + return rest.starts_with(',').then_some(at as u32); + } +} + +/// Where the run of spaces and tabs starting at `from` ends. Newlines are not +/// blanks here: a deletion that crossed one would join two lines. +fn blanks_after(text: &str, from: u32) -> u32 { + let Some(rest) = text.get(from as usize..) else { return from }; + from + (rest.len() - rest.trim_start_matches([' ', '\t']).len()) as u32 +} + +// ---------------------------------------------------------------------- +// finding parentheses +// ---------------------------------------------------------------------- + +/// The `(` of a module's port list, given where its name ends. The parameter +/// port list `#( ... )` is skipped. +fn port_list_open(tokens: &[Token], name_end: u32) -> Option { + port_list_parens(tokens, name_end).map(|(open, _)| open) +} + +/// The `(` and `)` of a module's port list. +fn port_list_parens(tokens: &[Token], name_end: u32) -> Option<(u32, u32)> { + let mut i = tokens.iter().position(|t| t.span.start >= name_end)?; + while i < tokens.len() { + let token = &tokens[i]; + if token.is_sym("#") { + i = skip_group(tokens, i + 1)?; + continue; + } + if token.is_sym("(") { + let close = skip_group(tokens, i)?; + let close_token = tokens.get(close.checked_sub(1)?)?; + return Some((token.span.start, close_token.span.start)); + } + if token.is_sym(";") || token.kind == TokenKind::Eof { + return None; + } + i += 1; + } + None +} + +/// The `;` that ends a module header that wrote no port list. +fn header_semicolon(tokens: &[Token], name_end: u32) -> Option { + let mut i = tokens.iter().position(|t| t.span.start >= name_end)?; + while i < tokens.len() { + let token = &tokens[i]; + if token.is_sym("#") { + i = skip_group(tokens, i + 1)?; + continue; + } + if token.is_sym(";") { + return Some(token.span.start); + } + if token.kind == TokenKind::Eof { + return None; + } + i += 1; + } + None +} + +/// The index just past the `( ... )` group starting at `open`. +fn skip_group(tokens: &[Token], open: usize) -> Option { + if !tokens.get(open)?.is_sym("(") { + return None; + } + let mut depth = 0usize; + for (i, token) in tokens.iter().enumerate().skip(open) { + if token.is_sym("(") { + depth += 1; + } else if token.is_sym(")") { + depth -= 1; + if depth == 0 { + return Some(i + 1); + } + } else if token.kind == TokenKind::Eof { + return None; + } + } + None +} + +/// The `(` opening an instance's connection list. +fn conn_list_open(text: &str, instance: &Instance, first: Option) -> Option { + match first { + // The list has elements: its `(` is the last one before the first of + // them that is not inside the instance's dimensions. + Some(first) => text.get(..first.start as usize)?.rfind('(').map(|at| at as u32), + // An empty list: the instance's span ends at its own `)`. + None => { + let end = instance.span.end as usize; + let close = text.get(..end)?.rfind(')')? as u32; + text.get(..close as usize)?.rfind('(').map(|at| at as u32) + } + } +} + +/// The `)` matching an `(` at `open`, found over the text — used only where a +/// list is empty, so nothing but whitespace and comments sits between them. +fn close_paren(text: &str, open: u32) -> Option { + let rest = text.get(open as usize + 1..)?; + rest.find(')').map(|at| open + 1 + at as u32) +} + +// ---------------------------------------------------------------------- +// what is in scope where +// ---------------------------------------------------------------------- + +/// Whether a signal called `name` is visible at `offset` in a file — the test +/// that decides between `.p(p)` and `.p(/* TODO: connect */)`. +fn name_visible(scope: &mut Scope, file: usize, offset: u32, name: &str) -> bool { + let Some(analysis) = scope.analysis(file) else { return false }; + visible_in(&analysis.semantics, offset, name) +} + +fn visible_in(semantics: &Semantics, offset: u32, name: &str) -> bool { + let scopes = semantics.scopes(); + // The innermost scope covering the offset: the smallest span that holds it. + let mut best: Option = None; + for (i, scope) in scopes.iter().enumerate() { + if !scope.span.contains(offset) { + continue; + } + let better = best.is_none_or(|b| { + scopes.get(b).is_some_and(|current| scope.span.len() <= current.span.len()) + }); + if better { + best = Some(i); + } + } + let mut at = best; + while let Some(i) = at { + let Some(current) = scopes.get(i) else { return false }; + if let Some(symbol) = current.lookup_local(name) { + return semantics.symbol(symbol).is_some_and(|s| { + matches!( + s.kind, + SymbolKind::Net + | SymbolKind::Var + | SymbolKind::Port + | SymbolKind::Param + | SymbolKind::Genvar + | SymbolKind::TfArg + ) + }); + } + at = current.parent.map(|p| p.0 as usize); + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 + } + + #[test] + fn a_port_declaration_must_be_exactly_one_directed_port() { + assert_eq!(parse_port_decl("input logic [7:0] cfg").map(|p| p.name), Ok("cfg".into())); + assert_eq!( + parse_port_decl(" output wire q ").map(|p| p.text), + Ok("output wire q".into()) + ); + assert!(parse_port_decl("").is_err(), "empty"); + assert!(parse_port_decl("logic a").is_err(), "no direction"); + assert!(parse_port_decl("input a, input b").is_err(), "two ports"); + assert!(parse_port_decl("input a,").is_err(), "a dangling comma"); + assert!(parse_port_decl("input a); wire evil; //").is_err(), "an escape from the list"); + assert!(parse_port_decl("input a /* hm */").is_err(), "a comment"); + assert!(parse_port_decl("`PORT(a)").is_err(), "a macro call"); + assert!(parse_port_decl("input a; input b").is_err(), "two declarations"); + } + + #[test] + fn an_appended_element_copies_the_lists_layout() { + // Inline stays inline. + let inline = "module m (input a, input b);"; + let elements = [TextRange::new(10, 17), TextRange::new(19, 26)]; + let edits = append_to_list(inline, Some(9), &elements, "input c"); + assert_eq!(edits.len(), 1); + assert_eq!(crate::apply(inline, &edits), "module m (input a, input b, input c);"); + + // One per line stays one per line, at the last element's indentation. + let stacked = "module m (\n input a,\n input b\n);"; + let elements = [TextRange::new(15, 22), TextRange::new(28, 35)]; + let edits = append_to_list(stacked, Some(9), &elements, "input c"); + assert_eq!( + crate::apply(stacked, &edits), + "module m (\n input a,\n input b,\n input c\n);" + ); + } + + #[test] + fn an_append_after_a_line_comment_writes_the_comma_before_it() { + let text = "module m (\n input a // why\n);"; + let a = TextRange::new(at(text, "input a"), at(text, "input a") + 7); + let edits = append_to_list(text, Some(9), &[a], "input b"); + assert_eq!(edits.len(), 2, "one for the comma, one for the element"); + assert_eq!(crate::apply(text, &edits), "module m (\n input a, // why\n input b\n);"); + } + + #[test] + fn an_append_to_an_empty_list_writes_between_the_parens() { + let text = "module m ();"; + let edits = append_to_list(text, Some(9), &[], "input a"); + assert_eq!(crate::apply(text, &edits), "module m (input a);"); + } + + #[test] + fn removing_an_element_takes_one_comma_with_it() { + let text = "module m (input a, input b, input c);"; + let elements = [TextRange::new(10, 17), TextRange::new(19, 26), TextRange::new(28, 35)]; + let first = remove_element(text, &elements, 0).expect("an edit"); + assert_eq!(crate::apply(text, &first), "module m (input b, input c);"); + let last = remove_element(text, &elements, 2).expect("an edit"); + assert_eq!(crate::apply(text, &last), "module m (input a, input b);"); + } + + #[test] + fn removing_a_line_of_its_own_takes_the_line() { + let text = "module m (\n input a,\n input b\n);"; + let elements = [TextRange::new(13, 20), TextRange::new(24, 31)]; + let first = remove_element(text, &elements, 0).expect("an edit"); + assert_eq!(crate::apply(text, &first), "module m (\n input b\n);", "no blank line left"); + } + + #[test] + fn an_indent_is_only_the_whitespace_a_line_starts_with() { + assert_eq!(line_indent(" input a;", 2), " "); + assert_eq!(line_indent("\tinput a;", 1), "\t"); + assert_eq!(line_indent("x = 1; input a;", 7), "", "not the first thing on its line"); + } + + #[test] + fn a_same_line_block_comment_is_written_past_but_a_line_comment_is_not() { + let text = "input a /* c */ , b"; + let after = after_same_line_comments(text, 7); + assert_eq!(after.at, 15); + assert!(!after.line_comment); + + let text = "input a // c\ninput b"; + let after = after_same_line_comments(text, 7); + assert_eq!(after.at, 12, "the end of the comment, not of the line"); + assert!(after.line_comment); + + let text = "input a /* two\nlines */"; + let after = after_same_line_comments(text, 7); + assert_eq!(after.at, 7, "a multi-line comment is left where it is"); + } + + #[test] + fn a_module_header_hides_its_parameter_list_from_the_port_list() { + let text = "module m #(parameter W = 1) (input a);\nendmodule\n"; + let tokens = tokenize(text).expect("lexes"); + let name_end = at(text, "m #") + 1; + let (open, close) = port_list_parens(&tokens, name_end).expect("a port list"); + assert_eq!(open, at(text, "(input")); + assert_eq!(close, at(text, ");")); + } + + #[test] + fn a_header_with_no_port_list_ends_at_its_semicolon() { + let text = "module m;\nendmodule\n"; + let tokens = tokenize(text).expect("lexes"); + assert_eq!(header_semicolon(&tokens, 8), Some(8)); + assert_eq!(port_list_parens(&tokens, 8), None); + } +} diff --git a/crates/vlog_refactor/src/rename.rs b/crates/vlog_refactor/src/rename.rs index 90c6953..b277830 100644 --- a/crates/vlog_refactor/src/rename.rs +++ b/crates/vlog_refactor/src/rename.rs @@ -181,7 +181,7 @@ impl<'a> Scope<'a> { self.file_ids.get(i).copied().flatten() } - fn index_of(&self, path: &Path) -> Option { + pub(crate) fn index_of(&self, path: &Path) -> Option { self.sources.iter().position(|(p, _)| *p == path) } @@ -443,28 +443,20 @@ impl<'a> Scope<'a> { fn macro_warnings(&self, name: &str) -> Vec { 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!( + for site in self.define_sites(i, name) { + let line = site.line; + match site.defines_the_name { + Some(DefineKind::Define) => out.push(format!( + "`{name}` is also a macro defined at {where_}:{line}; macro names and macro uses are never renamed." + )), + Some(DefineKind::Undef) => out.push(format!( + "`{name}` is also a macro undefined at {where_}:{line}; macro names and macro uses are never renamed." + )), + None => out.push(format!( "`{name}` appears in the body of macro `{}` at {where_}:{line} and was left unchanged; vfmt does not preprocess.", - define.name - )); + site.macro_name + )), } } } @@ -476,30 +468,75 @@ impl<'a> Scope<'a> { /// 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 { - let (Some(text), Some(path)) = (self.text(file), self.path(file)) else { + let where_ = display(self.path(file).unwrap_or(Path::new("?"))); + self.macro_argument_sites(file, name) + .into_iter() + .map(|site| { + format!( + "`{name}` appears in the arguments of the macro invocation `{}` at {where_}:{} and was left unchanged; a macro invocation is one opaque token to vfmt, which does not expand macros.", + site.macro_name, site.line + ) + }) + .collect() + } + + /// Every `` `define``/`` `undef`` in one file that `name` touches: the macro + /// whose own name it is, and every macro whose body spells it. + /// + /// The *scan* is shared with the port refactorings; the sentence is not, + /// because "was left unchanged" and "no longer exists after the removal" + /// are different pieces of news. + pub(crate) fn define_sites(&self, file: usize, name: &str) -> Vec { + let (Some(text), Some(id)) = (self.text(file), self.file_id(file)) else { return Vec::new(); }; if !text.contains(name) { return Vec::new(); } + let Some(defines) = self.index.defines(id) else { return Vec::new() }; + let lines = LineIndex::new(text); + let mut out = Vec::new(); + for define in defines.entries() { + let line = lines.line_col(define.span.start).0; + if define.name == name { + out.push(DefineSite { + macro_name: define.name.clone(), + line, + defines_the_name: Some(define.kind), + }); + } else if contains_word(&define.body, name) { + out.push(DefineSite { + macro_name: define.name.clone(), + line, + defines_the_name: None, + }); + } + } + out + } + + /// Every macro invocation in one file whose *arguments* spell `name`. + pub(crate) fn macro_argument_sites(&self, file: usize, name: &str) -> Vec { + let Some(text) = self.text(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. + // The macro's own name is reported by the `` `define`` scan 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.push(ArgumentSite { + macro_name: macro_name_of(&token.text).to_string(), + line: lines.line_col(token.span.start).0, + }); } out } @@ -553,6 +590,24 @@ impl<'a> Scope<'a> { } } +/// A `` `define``/`` `undef`` a name touches, found by [`Scope::define_sites`]. +pub(crate) struct DefineSite { + pub(crate) macro_name: String, + /// 1-based line of the directive. + pub(crate) line: u32, + /// `Some` when the name *is* this macro's name; `None` when it only + /// appears in the macro's body. + pub(crate) defines_the_name: Option, +} + +/// A macro invocation whose arguments spell a name, found by +/// [`Scope::macro_argument_sites`]. +pub(crate) struct ArgumentSite { + pub(crate) macro_name: String, + /// 1-based line the invocation starts on. + pub(crate) line: u32, +} + const NOTHING_HERE: &str = "there is no symbol to rename at this position."; fn ambiguous(name: &str) -> String { diff --git a/crates/vlog_refactor/tests/corpus.rs b/crates/vlog_refactor/tests/corpus.rs index fee08c5..fef6fdd 100644 --- a/crates/vlog_refactor/tests/corpus.rs +++ b/crates/vlog_refactor/tests/corpus.rs @@ -1,16 +1,16 @@ //! 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. +//! Two properties, neither of them a percentage: a refactoring over a real +//! workspace either does the whole job or refuses with a sentence — it never +//! panics and never produces an edit that does not cover what it claims — 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}; +use vlog_refactor::{add_port, port_actions, prepare_rename, rename, ModuleRef}; fn corpus() -> Option> { let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); @@ -127,3 +127,67 @@ fn asking_at_offsets_all_over_a_real_file_never_panics() { ); assert!(renameable > 0, "a real file must have something renameable in it"); } + +#[test] +fn adding_a_port_to_a_real_module_answers_or_refuses() { + let Some(files) = corpus() else { return }; + let sources = read(&files); + assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog"); + if !sources.iter().any(|(p, _)| p.file_name().is_some_and(|n| n == "prim_fifo_sync.sv")) { + eprintln!("prim_fifo_sync.sv not in this corpus — skipping the port probe"); + return; + } + + let started = Instant::now(); + let outcome = add_port(&sources, ModuleRef::Name("prim_fifo_sync"), "input logic vfmt_probe_i"); + let elapsed = started.elapsed(); + println!( + "corpus add_port 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 is an insertion of text that spells the new port. + for (_, edits) in &edit.edits { + for e in edits { + assert!(e.range.is_empty(), "adding a port only ever inserts"); + assert!(!e.new_text.is_empty(), "an empty insertion is not an edit"); + } + } + assert!(edit.file_count() >= 1); + } + // A refusal is a correct answer — real RTL instantiates modules + // positionally and with `.*` — as long as it reads as a sentence. + Err(message) => { + assert!(message.ends_with('.'), "a refusal must read as a sentence: {message}") + } + } + assert!(elapsed.as_secs() < 30, "a refactoring must stay interactive: {elapsed:?}"); +} + +#[test] +fn asking_for_port_actions_all_over_a_real_file_never_panics() { + let Some(files) = corpus() else { return }; + 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())]; + let step = (text.len() / 200).max(1); + let mut offered = 0usize; + for offset in (0..text.len() as u32).step_by(step) { + for action in port_actions(&sources, path, offset) { + offered += 1; + assert!(action.title.starts_with("vfmt: "), "{}", action.title); + assert!(action.edit.edit_count() > 0, "an action with no edit is not an action"); + } + } + println!("port actions over {}: {offered} offered", path.display()); +} diff --git a/crates/vlog_refactor/tests/ports.rs b/crates/vlog_refactor/tests/ports.rs new file mode 100644 index 0000000..45f9114 --- /dev/null +++ b/crates/vlog_refactor/tests/ports.rs @@ -0,0 +1,737 @@ +//! Behavior tests for the port refactorings: what the engine writes, and what +//! it refuses to write. +//! +//! Every test states the whole workspace and asserts on the *applied* text, +//! because that is what the user ends up with. A refusal is asserted on its +//! sentence, since that sentence is the entire answer the editor shows. + +use std::path::{Path, PathBuf}; + +use vlog_refactor::{ + add_port, port_actions, propagate_ports, remove_port, ModuleRef, RefactorEdit, +}; + +/// A workspace: `(path, text)` pairs, the shape the engine takes. +fn files(pairs: &[(&str, &str)]) -> Vec<(PathBuf, String)> { + pairs.iter().map(|(path, text)| (PathBuf::from(*path), text.to_string())).collect() +} + +fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 +} + +/// One file's text with the refactoring applied, the way a client applies a +/// `WorkspaceEdit`: back to front, so every range still means what it said. +fn applied(files: &[(PathBuf, String)], edit: &RefactorEdit, path: &str) -> String { + let path = PathBuf::from(path); + let mut text = files + .iter() + .find(|(p, _)| *p == path) + .map(|(_, text)| text.clone()) + .expect("a file in the workspace"); + for change in edit.edits_for(&path).iter().rev() { + text.replace_range( + change.range.start as usize..change.range.end as usize, + &change.new_text, + ); + } + text +} + +/// Every warning joined, for a `contains` assertion. +fn warnings(edit: &RefactorEdit) -> String { + edit.warnings.join("\n") +} + +// ---------------------------------------------------------------------- +// add +// ---------------------------------------------------------------------- + +const SUB: &str = "module sub (\n input logic clk,\n input logic rst\n);\n wire x;\nendmodule\n"; + +#[test] +fn a_port_added_to_an_ansi_header_reaches_every_named_connection() { + let workspace = files(&[ + ("/rtl/sub.sv", SUB), + ("/rtl/top.sv", "module top;\n logic cfg;\n sub u1 (.clk(c), .rst(r));\nendmodule\n"), + ("/rtl/other.sv", "module other;\n logic cfg;\n sub u2 (.clk(a), .rst(b));\nendmodule\n"), + ]); + let edit = add_port(&workspace, ModuleRef::Name("sub"), "input logic [7:0] cfg").expect("adds"); + assert_eq!(edit.file_count(), 3, "the declaration and both instantiating files"); + assert_eq!( + applied(&workspace, &edit, "/rtl/sub.sv"), + "module sub (\n input logic clk,\n input logic rst,\n input logic [7:0] cfg\n);\n wire x;\nendmodule\n" + ); + assert_eq!( + applied(&workspace, &edit, "/rtl/top.sv"), + "module top;\n logic cfg;\n sub u1 (.clk(c), .rst(r), .cfg(cfg));\nendmodule\n" + ); + assert_eq!( + applied(&workspace, &edit, "/rtl/other.sv"), + "module other;\n logic cfg;\n sub u2 (.clk(a), .rst(b), .cfg(cfg));\nendmodule\n" + ); + assert!(edit.warnings.is_empty(), "{:?}", edit.warnings); +} + +#[test] +fn a_connection_with_no_signal_of_that_name_is_left_as_a_todo() { + let workspace = files(&[ + ("/rtl/sub.sv", SUB), + ("/rtl/top.sv", "module top;\n sub u1 (.clk(c), .rst(r));\nendmodule\n"), + ]); + let edit = add_port(&workspace, ModuleRef::Name("sub"), "input logic cfg").expect("adds"); + assert_eq!( + applied(&workspace, &edit, "/rtl/top.sv"), + "module top;\n sub u1 (.clk(c), .rst(r), .cfg(/* TODO: connect */));\nendmodule\n" + ); + assert!(warnings(&edit).contains("TODO"), "{:?}", edit.warnings); + assert!(warnings(&edit).contains("`u1` (top.sv:2)"), "{:?}", edit.warnings); +} + +#[test] +fn a_one_per_line_connection_list_stays_one_per_line() { + let workspace = files(&[ + ("/rtl/sub.sv", SUB), + ( + "/rtl/top.sv", + "module top;\n logic cfg;\n sub u1 (\n .clk(c),\n .rst(r)\n );\nendmodule\n", + ), + ]); + let edit = add_port(&workspace, ModuleRef::Name("sub"), "input logic cfg").expect("adds"); + assert_eq!( + applied(&workspace, &edit, "/rtl/top.sv"), + "module top;\n logic cfg;\n sub u1 (\n .clk(c),\n .rst(r),\n .cfg(cfg)\n );\nendmodule\n" + ); +} + +#[test] +fn a_comment_on_the_last_port_keeps_its_port() { + let workspace = files(&[( + "/rtl/sub.sv", + "module sub (\n input clk, // the clock\n input rst // the reset\n);\nendmodule\n", + )]); + let edit = add_port(&workspace, ModuleRef::Name("sub"), "input cfg").expect("adds"); + assert_eq!( + applied(&workspace, &edit, "/rtl/sub.sv"), + "module sub (\n input clk, // the clock\n input rst, // the reset\n input cfg\n);\nendmodule\n", + "the comma goes before the comment, the port after it" + ); +} + +#[test] +fn a_port_added_to_a_non_ansi_header_is_declared_in_the_body_too() { + let workspace = files(&[ + ("/rtl/sub.sv", "module sub (a, b);\n input a;\n output b;\n wire c;\nendmodule\n"), + ("/rtl/top.sv", "module top;\n logic cfg;\n sub u1 (.a(x), .b(y));\nendmodule\n"), + ]); + let edit = add_port(&workspace, ModuleRef::Name("sub"), "input logic cfg").expect("adds"); + assert_eq!( + applied(&workspace, &edit, "/rtl/sub.sv"), + "module sub (a, b, cfg);\n input a;\n output b;\n input logic cfg;\n wire c;\nendmodule\n", + "the header takes the name, the body takes the declaration" + ); + assert_eq!( + applied(&workspace, &edit, "/rtl/top.sv"), + "module top;\n logic cfg;\n sub u1 (.a(x), .b(y), .cfg(cfg));\nendmodule\n" + ); +} + +#[test] +fn an_ordered_instantiation_gains_a_positional_connection() { + let workspace = files(&[ + ("/rtl/sub.sv", "module sub (input a, input b);\nendmodule\n"), + ("/rtl/top.sv", "module top;\n logic cfg;\n sub u1 (x, y);\nendmodule\n"), + ]); + let edit = add_port(&workspace, ModuleRef::Name("sub"), "input cfg").expect("adds"); + assert_eq!( + applied(&workspace, &edit, "/rtl/top.sv"), + "module top;\n logic cfg;\n sub u1 (x, y, cfg);\nendmodule\n" + ); +} + +#[test] +fn an_ordered_instantiation_that_connects_a_different_number_of_ports_is_refused() { + let workspace = files(&[ + ("/rtl/sub.sv", "module sub (input a, input b);\nendmodule\n"), + ("/rtl/top.sv", "module top;\n sub u1 (x);\nendmodule\n"), + ]); + let message = + add_port(&workspace, ModuleRef::Name("sub"), "input cfg").expect_err("cannot be sure"); + assert!(message.contains("by position"), "{message}"); + assert!(message.contains("named connections first"), "{message}"); +} + +#[test] +fn an_empty_connection_list_is_left_alone_and_reported() { + let workspace = files(&[ + ("/rtl/sub.sv", "module sub (input a);\nendmodule\n"), + ("/rtl/top.sv", "module top;\n sub u1 ();\nendmodule\n"), + ]); + let edit = add_port(&workspace, ModuleRef::Name("sub"), "input cfg").expect("adds"); + assert_eq!( + applied(&workspace, &edit, "/rtl/top.sv"), + "module top;\n sub u1 ();\nendmodule\n", + "an empty list connects nothing, before and after" + ); + assert!(warnings(&edit).contains("empty connection list"), "{:?}", edit.warnings); +} + +#[test] +fn a_wildcard_connection_is_left_alone_and_warned_about_only_when_it_would_not_bind() { + let bound = files(&[ + ("/rtl/sub.sv", "module sub (input a);\nendmodule\n"), + ("/rtl/top.sv", "module top;\n logic cfg;\n sub u1 (.*);\nendmodule\n"), + ]); + let edit = add_port(&bound, ModuleRef::Name("sub"), "input cfg").expect("adds"); + assert_eq!(applied(&bound, &edit, "/rtl/top.sv"), bound[1].1, "`.*` is never rewritten"); + assert!(edit.warnings.is_empty(), "a signal named `cfg` is right there: {:?}", edit.warnings); + + let unbound = files(&[ + ("/rtl/sub.sv", "module sub (input a);\nendmodule\n"), + ("/rtl/top.sv", "module top;\n sub u1 (.*);\nendmodule\n"), + ]); + let edit = add_port(&unbound, ModuleRef::Name("sub"), "input cfg").expect("adds"); + assert!(warnings(&edit).contains("will not bind"), "{:?}", edit.warnings); +} + +#[test] +fn an_empty_port_list_is_filled_in_the_ansi_way() { + let workspace = files(&[("/rtl/sub.sv", "module sub ();\nendmodule\n")]); + let edit = add_port(&workspace, ModuleRef::Name("sub"), "input clk").expect("adds"); + assert_eq!(applied(&workspace, &edit, "/rtl/sub.sv"), "module sub (input clk);\nendmodule\n"); +} + +#[test] +fn a_header_with_no_port_list_at_all_gains_one() { + let workspace = files(&[("/rtl/sub.sv", "module sub;\nendmodule\n")]); + let edit = add_port(&workspace, ModuleRef::Name("sub"), "input clk").expect("adds"); + assert_eq!(applied(&workspace, &edit, "/rtl/sub.sv"), "module sub (input clk);\nendmodule\n"); +} + +#[test] +fn the_module_can_be_named_by_a_position_instead_of_by_name() { + let workspace = files(&[("/rtl/sub.sv", SUB)]); + let offset = at(SUB, "wire x"); + let edit = + add_port(&workspace, ModuleRef::At { file: Path::new("/rtl/sub.sv"), offset }, "input cfg") + .expect("the module the cursor is in"); + assert!(applied(&workspace, &edit, "/rtl/sub.sv").contains("input cfg")); +} + +#[test] +fn a_module_declared_twice_is_refused() { + let workspace = files(&[ + ("/rtl/a.sv", "module sub (input a);\nendmodule\n"), + ("/rtl/b.sv", "module sub (input a);\nendmodule\n"), + ]); + let message = add_port(&workspace, ModuleRef::Name("sub"), "input cfg").expect_err("ambiguous"); + assert!(message.contains("more than one indexed file"), "{message}"); +} + +#[test] +fn a_port_that_already_exists_is_refused() { + let workspace = files(&[("/rtl/sub.sv", SUB)]); + let message = + add_port(&workspace, ModuleRef::Name("sub"), "input logic clk").expect_err("a duplicate"); + assert!(message.contains("already has a port named `clk`"), "{message}"); +} + +#[test] +fn a_port_that_would_capture_a_body_name_is_refused() { + // `cfg` already means the net; a port called `cfg` would take the name + // over, and every use of it in the body would quietly change meaning. + let workspace = files(&[( + "/rtl/sub.sv", + "module sub (\n input clk\n);\n wire cfg;\n assign cfg = clk;\nendmodule\n", + )]); + let message = add_port(&workspace, ModuleRef::Name("sub"), "input cfg") + .expect_err("a captured body reference"); + assert!(message.contains("would change what"), "{message}"); +} + +#[test] +fn an_unknown_module_is_refused() { + let workspace = files(&[("/rtl/sub.sv", SUB)]); + let message = add_port(&workspace, ModuleRef::Name("nope"), "input cfg").expect_err("unknown"); + assert!(message.contains("no module named `nope`"), "{message}"); +} + +#[test] +fn an_instantiation_inside_a_generate_block_is_updated_too() { + let workspace = files(&[ + ("/rtl/sub.sv", "module sub (input a);\nendmodule\n"), + ( + "/rtl/top.sv", + "module top;\n logic cfg;\n if (1) begin : g\n sub u1 (.a(x));\n end\nendmodule\n", + ), + ]); + let edit = add_port(&workspace, ModuleRef::Name("sub"), "input cfg").expect("adds"); + assert!( + applied(&workspace, &edit, "/rtl/top.sv").contains(".a(x), .cfg(cfg)"), + "{}", + applied(&workspace, &edit, "/rtl/top.sv") + ); +} + +#[test] +fn adding_a_port_twice_is_refused_the_second_time() { + let workspace = files(&[("/rtl/sub.sv", SUB)]); + let edit = add_port(&workspace, ModuleRef::Name("sub"), "input cfg").expect("adds"); + let once = files(&[("/rtl/sub.sv", &applied(&workspace, &edit, "/rtl/sub.sv"))]); + let message = add_port(&once, ModuleRef::Name("sub"), "input cfg").expect_err("already there"); + assert!(message.contains("already has a port"), "{message}"); +} + +// ---------------------------------------------------------------------- +// remove +// ---------------------------------------------------------------------- + +#[test] +fn a_removed_port_leaves_the_header_and_every_connection() { + let sub = "module sub (\n input a,\n input b\n);\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", sub), + ( + "/rtl/top.sv", + "module top;\n sub u1 (.a(x), .b(y));\n sub u2 (.b(z), .a(w));\nendmodule\n", + ), + ]); + let edit = + remove_port(&workspace, Path::new("/rtl/sub.sv"), at(sub, "input b") + 6).expect("removes"); + assert_eq!( + applied(&workspace, &edit, "/rtl/sub.sv"), + "module sub (\n input a\n);\nendmodule\n" + ); + assert_eq!( + applied(&workspace, &edit, "/rtl/top.sv"), + "module top;\n sub u1 (.a(x));\n sub u2 (.a(w));\nendmodule\n" + ); +} + +#[test] +fn removing_a_non_ansi_port_removes_its_body_declaration() { + let sub = "module sub (a, b);\n input a;\n output b;\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", sub), + ("/rtl/top.sv", "module top;\n sub u1 (.a(x), .b(y));\nendmodule\n"), + ]); + // From the header... + let from_header = + remove_port(&workspace, Path::new("/rtl/sub.sv"), at(sub, "b);")).expect("removes"); + assert_eq!( + applied(&workspace, &from_header, "/rtl/sub.sv"), + "module sub (a);\n input a;\nendmodule\n" + ); + // ...and from the body declaration, which is the same removal. + let from_body = remove_port(&workspace, Path::new("/rtl/sub.sv"), at(sub, "output b") + 7) + .expect("removes"); + assert_eq!( + applied(&workspace, &from_body, "/rtl/sub.sv"), + "module sub (a);\n input a;\nendmodule\n" + ); +} + +#[test] +fn a_non_ansi_declaration_naming_several_ports_loses_only_one_of_them() { + let sub = "module sub (a, b);\n input a, b;\nendmodule\n"; + let workspace = files(&[("/rtl/sub.sv", sub)]); + let edit = remove_port(&workspace, Path::new("/rtl/sub.sv"), at(sub, "b);")).expect("removes"); + assert_eq!( + applied(&workspace, &edit, "/rtl/sub.sv"), + "module sub (a);\n input a;\nendmodule\n" + ); +} + +#[test] +fn a_port_still_used_in_the_body_is_refused() { + let sub = "module sub (\n input a,\n input b\n);\n wire c;\n assign c = b;\nendmodule\n"; + let workspace = files(&[("/rtl/sub.sv", sub)]); + let message = remove_port(&workspace, Path::new("/rtl/sub.sv"), at(sub, "input b") + 6) + .expect_err("still used"); + assert!(message.contains("still used inside `sub`"), "{message}"); + assert!(message.contains("sub.sv:6"), "the line it is used on: {message}"); +} + +#[test] +fn a_positional_connection_anywhere_refuses_the_whole_removal() { + let sub = "module sub (input a, input b);\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", sub), + ("/rtl/top.sv", "module top;\n sub u1 (.a(x), .b(y));\nendmodule\n"), + ("/rtl/legacy.sv", "module legacy;\n sub u2 (p, q);\nendmodule\n"), + ]); + let message = remove_port(&workspace, Path::new("/rtl/sub.sv"), at(sub, "input b") + 6) + .expect_err("a positional connection"); + assert!(message.contains("by position"), "{message}"); + assert!(message.contains("named connections first"), "{message}"); +} + +#[test] +fn a_dropped_expression_that_is_more_than_the_ports_own_name_is_reported() { + let sub = "module sub (input a, input b);\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", sub), + ("/rtl/top.sv", "module top;\n sub u1 (.a(a), .b(count + 1));\nendmodule\n"), + ]); + let edit = + remove_port(&workspace, Path::new("/rtl/sub.sv"), at(sub, "input b") + 6).expect("removes"); + assert!(warnings(&edit).contains("`.b(count + 1)`"), "{:?}", edit.warnings); + assert!(warnings(&edit).contains("deleted with the port"), "{:?}", edit.warnings); +} + +#[test] +fn a_plain_connection_of_the_ports_own_name_is_dropped_silently() { + let sub = "module sub (input a, input b);\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", sub), + ("/rtl/top.sv", "module top;\n logic a, b;\n sub u1 (.a(a), .b(b));\nendmodule\n"), + ]); + let edit = + remove_port(&workspace, Path::new("/rtl/sub.sv"), at(sub, "input b") + 6).expect("removes"); + assert!(edit.warnings.is_empty(), "nothing was lost: {:?}", edit.warnings); +} + +#[test] +fn a_wildcard_site_is_warned_about_rather_than_edited() { + let sub = "module sub (input a, input b);\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", sub), + ("/rtl/top.sv", "module top;\n logic a, b;\n sub u1 (.*);\nendmodule\n"), + ]); + let edit = + remove_port(&workspace, Path::new("/rtl/sub.sv"), at(sub, "input b") + 6).expect("removes"); + assert_eq!(applied(&workspace, &edit, "/rtl/top.sv"), workspace[1].1, "`.*` is untouched"); + assert!(warnings(&edit).contains("may now be unused"), "{:?}", edit.warnings); +} + +#[test] +fn a_commented_connection_is_refused_rather_than_silently_uncommented() { + let sub = "module sub (input a, input b);\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", sub), + ( + "/rtl/top.sv", + "module top;\n sub u1 (\n .a(x),\n .b(y /* keep me */)\n );\nendmodule\n", + ), + ]); + let message = remove_port(&workspace, Path::new("/rtl/sub.sv"), at(sub, "input b") + 6) + .expect_err("a comment inside the connection"); + assert!(message.contains("comments are never dropped"), "{message}"); +} + +#[test] +fn removing_the_only_port_leaves_an_empty_list() { + let sub = "module sub (input a);\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", sub), + ("/rtl/top.sv", "module top;\n sub u1 (.a(x));\nendmodule\n"), + ]); + let edit = + remove_port(&workspace, Path::new("/rtl/sub.sv"), at(sub, "input a") + 6).expect("removes"); + assert_eq!(applied(&workspace, &edit, "/rtl/sub.sv"), "module sub ();\nendmodule\n"); + assert_eq!(applied(&workspace, &edit, "/rtl/top.sv"), "module top;\n sub u1 ();\nendmodule\n"); +} + +#[test] +fn a_position_that_is_not_a_port_is_refused() { + let workspace = files(&[("/rtl/sub.sv", SUB)]); + let message = remove_port(&workspace, Path::new("/rtl/sub.sv"), at(SUB, "wire x") + 5) + .expect_err("a net, not a port"); + assert!(message.contains("no module port at this position"), "{message}"); +} + +#[test] +fn a_file_outside_the_scope_is_refused() { + let workspace = files(&[("/rtl/sub.sv", SUB)]); + let message = + remove_port(&workspace, Path::new("/elsewhere/x.sv"), 0).expect_err("not indexed"); + assert!(message.contains("not one of the files vfmt indexes"), "{message}"); +} + +// ---------------------------------------------------------------------- +// propagate +// ---------------------------------------------------------------------- + +#[test] +fn propagating_adds_only_the_connections_that_are_missing() { + let top = "module top;\n logic a, c;\n sub u1 (.a(a));\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", "module sub (input a, input b, input c);\nendmodule\n"), + ("/rtl/top.sv", top), + ]); + let edit = propagate_ports(&workspace, Path::new("/rtl/top.sv"), at(top, "u1")).expect("adds"); + assert_eq!( + applied(&workspace, &edit, "/rtl/top.sv"), + "module top;\n logic a, c;\n sub u1 (.a(a), .b(/* TODO: connect */), .c(c));\nendmodule\n" + ); + assert!(warnings(&edit).contains("`b`"), "{:?}", edit.warnings); + assert_eq!(edit.file_count(), 1, "propagation is one instantiation's business"); +} + +#[test] +fn propagating_a_one_per_line_list_stays_one_per_line() { + let top = "module top;\n logic a, b;\n sub u1 (\n .a(a)\n );\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", "module sub (input a, input b);\nendmodule\n"), + ("/rtl/top.sv", top), + ]); + let edit = propagate_ports(&workspace, Path::new("/rtl/top.sv"), at(top, "u1")).expect("adds"); + assert_eq!( + applied(&workspace, &edit, "/rtl/top.sv"), + "module top;\n logic a, b;\n sub u1 (\n .a(a),\n .b(b)\n );\nendmodule\n" + ); +} + +#[test] +fn propagating_a_fully_connected_instantiation_is_refused() { + let top = "module top;\n logic a;\n sub u1 (.a(a));\nendmodule\n"; + let workspace = + files(&[("/rtl/sub.sv", "module sub (input a);\nendmodule\n"), ("/rtl/top.sv", top)]); + let message = propagate_ports(&workspace, Path::new("/rtl/top.sv"), at(top, "u1")) + .expect_err("nothing to do"); + assert!(message.contains("already connects every port"), "{message}"); +} + +#[test] +fn propagating_an_ordered_instantiation_is_refused() { + let top = "module top;\n sub u1 (x);\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", "module sub (input a, input b);\nendmodule\n"), + ("/rtl/top.sv", top), + ]); + let message = propagate_ports(&workspace, Path::new("/rtl/top.sv"), at(top, "u1")) + .expect_err("positional"); + assert!(message.contains("named connections only"), "{message}"); +} + +#[test] +fn propagating_a_wildcard_instantiation_is_refused() { + let top = "module top;\n logic a;\n sub u1 (.*);\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", "module sub (input a, input b);\nendmodule\n"), + ("/rtl/top.sv", top), + ]); + let message = + propagate_ports(&workspace, Path::new("/rtl/top.sv"), at(top, "u1")).expect_err("`.*`"); + assert!(message.contains("`.*`"), "{message}"); +} + +#[test] +fn propagating_needs_to_know_which_instance_when_a_statement_declares_several() { + let top = "module top;\n sub u1 (.a(x)), u2 (.a(y));\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", "module sub (input a, input b);\nendmodule\n"), + ("/rtl/top.sv", top), + ]); + let message = propagate_ports(&workspace, Path::new("/rtl/top.sv"), at(top, "sub u1")) + .expect_err("which one?"); + assert!(message.contains("put the cursor on the one"), "{message}"); + // On an instance name it is unambiguous. + let edit = + propagate_ports(&workspace, Path::new("/rtl/top.sv"), at(top, "u2")).expect("that one"); + assert_eq!( + applied(&workspace, &edit, "/rtl/top.sv"), + "module top;\n sub u1 (.a(x)), u2 (.a(y), .b(/* TODO: connect */));\nendmodule\n" + ); +} + +#[test] +fn a_position_that_is_not_an_instantiation_is_refused() { + let top = "module top;\n logic a;\nendmodule\n"; + let workspace = + files(&[("/rtl/sub.sv", "module sub (input a);\nendmodule\n"), ("/rtl/top.sv", top)]); + let message = propagate_ports(&workspace, Path::new("/rtl/top.sv"), at(top, "logic")) + .expect_err("nothing here"); + assert!(message.contains("no module instantiation at this position"), "{message}"); +} + +// ---------------------------------------------------------------------- +// the code-action surface +// ---------------------------------------------------------------------- + +#[test] +fn a_port_declaration_offers_its_removal_with_the_count_in_the_title() { + let sub = "module sub (input a, input b);\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", sub), + ( + "/rtl/top.sv", + "module top;\n sub u1 (.a(x), .b(y));\n sub u2 (.a(p), .b(q));\nendmodule\n", + ), + ]); + let actions = port_actions(&workspace, Path::new("/rtl/sub.sv"), at(sub, "input b") + 6); + assert_eq!(actions.len(), 1, "{actions:#?}"); + assert_eq!(actions[0].title, "vfmt: remove port `b` (updates 2 instantiations)"); + assert_eq!(actions[0].edit.file_count(), 2); +} + +#[test] +fn an_instantiation_missing_connections_offers_to_fill_them_in() { + let top = "module top;\n logic a, b;\n sub u1 (.a(a));\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", "module sub (input a, input b);\nendmodule\n"), + ("/rtl/top.sv", top), + ]); + let actions = port_actions(&workspace, Path::new("/rtl/top.sv"), at(top, "u1")); + assert_eq!(actions.len(), 1, "{actions:#?}"); + assert_eq!(actions[0].title, "vfmt: connect 1 missing port"); +} + +#[test] +fn nothing_is_offered_where_nothing_applies() { + let workspace = files(&[("/rtl/sub.sv", SUB)]); + assert!(port_actions(&workspace, Path::new("/rtl/sub.sv"), at(SUB, "wire x")).is_empty()); +} + +#[test] +fn a_named_list_that_also_writes_a_wildcard_is_left_alone() { + // `.a(x), .*` is a wildcard site: the wildcard already binds whatever is + // not named, so writing `.cfg(cfg)` beside it would be redundant at best. + let workspace = files(&[ + ("/rtl/sub.sv", "module sub (input a);\nendmodule\n"), + ("/rtl/top.sv", "module top;\n logic cfg;\n sub u1 (.a(x), .*);\nendmodule\n"), + ]); + let edit = add_port(&workspace, ModuleRef::Name("sub"), "input cfg").expect("adds"); + assert_eq!(applied(&workspace, &edit, "/rtl/top.sv"), workspace[1].1); +} + +#[test] +fn a_comment_beside_an_untouched_connection_survives_the_removal() { + let sub = "module sub (input a, input b);\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", sub), + ( + "/rtl/top.sv", + "module top;\n sub u1 (\n .a(x), // about a\n .b(y)\n );\nendmodule\n", + ), + ]); + let edit = + remove_port(&workspace, Path::new("/rtl/sub.sv"), at(sub, "input b") + 6).expect("removes"); + assert_eq!( + applied(&workspace, &edit, "/rtl/top.sv"), + "module top;\n sub u1 (\n .a(x) // about a\n );\nendmodule\n", + "the comment stays with `.a`, and the emptied line goes" + ); +} + +#[test] +fn a_module_instantiated_in_its_own_file_is_edited_once() { + let text = "module sub (input a, input b);\nendmodule\n\nmodule top;\n sub u1 (.a(x), .b(y));\nendmodule\n"; + let workspace = files(&[("/rtl/both.sv", text)]); + let edit = remove_port(&workspace, Path::new("/rtl/both.sv"), at(text, "input b") + 6) + .expect("removes"); + assert_eq!(edit.file_count(), 1); + assert_eq!( + applied(&workspace, &edit, "/rtl/both.sv"), + "module sub (input a);\nendmodule\n\nmodule top;\n sub u1 (.a(x));\nendmodule\n" + ); +} + +#[test] +fn the_cheap_pre_check_says_yes_exactly_where_an_action_could_be_offered() { + use vlog_refactor::may_have_port_action; + let text = "module sub (\n input a,\n input b\n);\n wire c;\n assign c = a;\n other u1 (.x(c));\nendmodule\n"; + assert!(may_have_port_action(text, at(text, "input b") + 6), "a header port"); + assert!(may_have_port_action(text, at(text, "u1")), "an instance"); + assert!(may_have_port_action(text, at(text, "other")), "an instantiation's module name"); + assert!(!may_have_port_action(text, at(text, "wire c") + 5), "a net"); + assert!(!may_have_port_action(text, at(text, "assign")), "a statement"); + assert!(!may_have_port_action(text, 0), "the `module` keyword"); + + let non_ansi = "module sub (a);\n input a;\nendmodule\n"; + assert!(may_have_port_action(non_ansi, at(non_ansi, "input a") + 6), "a non-ANSI declaration"); +} + +// ---------------------------------------------------------------------- +// what the preprocessor owns +// ---------------------------------------------------------------------- + +/// QA's reproduction: the last declared port sits inside an `` `ifdef `` arm, +/// so "after the last port" is a position inside that arm. +const CONDITIONAL: &str = + "module m (\n input clk\n`ifdef HAS_RST\n , input rst\n`endif\n);\nendmodule\n"; + +#[test] +fn a_port_that_would_land_inside_an_ifdef_arm_is_refused() { + let workspace = files(&[("/rtl/m.sv", CONDITIONAL)]); + let message = add_port(&workspace, ModuleRef::Name("m"), "input logic cfg") + .expect_err("the append point is inside the conditional arm"); + assert!(message.contains("conditionally compiled"), "{message}"); + assert!(message.contains("`ifdef HAS_RST"), "the arm is named: {message}"); + assert!(message.contains("m.sv:3"), "and located: {message}"); + assert!(message.contains("place it by hand"), "{message}"); +} + +#[test] +fn a_port_list_with_a_closed_conditional_is_edited_and_reported() { + // The arm closes *before* the last port, so the new port lands outside it — + // but the module's port set is still configuration-dependent, and that is + // worth a sentence. + let text = "module m (\n`ifdef HAS_RST\n input rst,\n`endif\n input clk\n);\nendmodule\n"; + let workspace = files(&[("/rtl/m.sv", text)]); + let edit = add_port(&workspace, ModuleRef::Name("m"), "input logic cfg").expect("adds"); + assert_eq!( + applied(&workspace, &edit, "/rtl/m.sv"), + "module m (\n`ifdef HAS_RST\n input rst,\n`endif\n input clk,\n input logic cfg\n);\nendmodule\n" + ); + assert!(warnings(&edit).contains("carries compiler directives"), "{:?}", edit.warnings); + assert!(warnings(&edit).contains("outside every conditional arm"), "{:?}", edit.warnings); +} + +#[test] +fn a_non_ansi_body_declaration_that_would_land_inside_an_ifdef_arm_is_refused() { + // The header list is unconditional; the *body*'s last port declaration is + // not, and that is where the declaration would be written. + let text = "module m (a, b);\n input a;\n`ifdef WIDE\n input [7:0] b;\n`endif\nendmodule\n"; + let workspace = files(&[("/rtl/m.sv", text)]); + let message = add_port(&workspace, ModuleRef::Name("m"), "input logic cfg") + .expect_err("the body declaration would be conditional"); + assert!(message.contains("the body of `m`"), "{message}"); + assert!(message.contains("`ifdef WIDE"), "{message}"); +} + +#[test] +fn a_port_only_used_inside_a_macro_invocation_is_reported_when_it_is_removed() { + // QA's reproduction: `BUMP(rst)` is one opaque token, so no reference + // exists for the body-use refusal to find — but the expansion still names + // the port. + let text = "`define BUMP(x) x = x + 1\nmodule m (\n input clk,\n input rst\n);\n initial `BUMP(rst);\nendmodule\n"; + let workspace = files(&[("/rtl/m.sv", text)]); + let edit = remove_port(&workspace, Path::new("/rtl/m.sv"), at(text, "input rst") + 6) + .expect("removes"); + assert!( + applied(&workspace, &edit, "/rtl/m.sv").contains("`BUMP(rst)"), + "the call is untouched" + ); + assert!(warnings(&edit).contains("macro invocation `BUMP`"), "{:?}", edit.warnings); + assert!(warnings(&edit).contains("m.sv:6"), "{:?}", edit.warnings); + assert!(warnings(&edit).contains("no longer has"), "{:?}", edit.warnings); +} + +#[test] +fn a_removed_port_named_in_a_macro_body_is_reported_too() { + let text = "`define TIE rst = 1'b0\nmodule m (\n input clk,\n input rst\n);\nendmodule\n"; + let workspace = files(&[("/rtl/m.sv", text)]); + let edit = remove_port(&workspace, Path::new("/rtl/m.sv"), at(text, "input rst") + 6) + .expect("removes"); + assert!(warnings(&edit).contains("body of macro `TIE`"), "{:?}", edit.warnings); +} + +#[test] +fn a_macro_invocation_in_an_instantiating_file_is_reported_when_the_port_goes() { + let sub = "module sub (input a, input b);\nendmodule\n"; + let workspace = files(&[ + ("/rtl/sub.sv", sub), + ( + "/rtl/top.sv", + "`define WIRE_UP(x) .b(x)\nmodule top;\n sub u1 (.a(p), .b(q));\n initial `WIRE_UP(b);\nendmodule\n", + ), + ]); + let edit = + remove_port(&workspace, Path::new("/rtl/sub.sv"), at(sub, "input b") + 6).expect("removes"); + assert!( + warnings(&edit).contains("`WIRE_UP`"), + "an edited file is scanned too: {:?}", + edit.warnings + ); +} diff --git a/docs/features/refactor-ports/README.md b/docs/features/refactor-ports/README.md new file mode 100644 index 0000000..99feff1 --- /dev/null +++ b/docs/features/refactor-ports/README.md @@ -0,0 +1,1196 @@ +# refactor-ports + +Milestone **M3** of `docs/features/refactor/README.md`. + +## Goal + +Change a module's port signature the way an RTL engineer wishes an editor +would: add a port and every instantiation in the project gains a connection for +it; remove a port and every instantiation loses it; ask one instantiation to +catch up with the module it instantiates and the missing connections appear. +The engine lives in `crates/vlog_refactor` beside M2's rename, so Vim, VS Code +and any future CLI get identical behavior; `vfmt_server` maps the protocol — +two code actions and three `workspace/executeCommand` commands — and decides +nothing. Every edit comes from a node `vlog_parser` parsed or a name +`vlog_semantic` resolved, and the whole edit is verified in memory before it is +returned. Whole-edit-or-nothing: an `Ok` is safe to apply, an `Err` is a +sentence for the user and no edits at all. + +## API as built + +```rust +// crates/vlog_refactor/src/lib.rs +pub enum ModuleRef<'a> { Name(&'a str), At { file: &'a Path, offset: u32 } } +pub struct PortAction { pub title: String, pub edit: RefactorEdit } + +pub fn add_port(files: &[(PathBuf, String)], module: ModuleRef<'_>, decl: &str) + -> Result; +pub fn remove_port(files: &[(PathBuf, String)], file: &Path, offset: u32) + -> Result; +pub fn propagate_ports(files: &[(PathBuf, String)], file: &Path, offset: u32) + -> Result; +pub fn port_actions(files: &[(PathBuf, String)], file: &Path, offset: u32) + -> Vec; +pub fn may_have_port_action(text: &str, offset: u32) -> bool; +``` + +`files`, `RefactorEdit`, `TextEdit` and the `Err(String)`-is-a-sentence +convention are M2's, unchanged — there is no second edit model. + +`port_actions` is the code-action entry point: it returns only refactorings +that **succeeded**, each with its edit already computed and verified, and each +with the title the user will read. The title is written in the engine so every +editor says the same thing. A lightbulb that only ever explains why it cannot +help is worse than no lightbulb, so a refusal produces no action at all. + +`ModuleRef::At` exists because a code action or a keybinding knows a cursor, +not a name; `ModuleRef::Name` because `vfmt.addPort` is also the API a UI calls +after asking the user which module (M4's instantiate work will want it too). + +## What each refactoring does — exactly + +### `add_port(files, module, decl)` + +1. **`decl` is parsed as one ANSI port declaration** before anything else + happens. It is the only free-form input any of these refactorings takes, so + it gets formatter-grade suspicion: it must lex, carry **no comment**, **no + compiler directive and no macro call**, and — planted in a throwaway module + header — parse with zero diagnostics into *exactly one* ANSI port, with an + explicit direction, no trailing comma, and no module item that a stray `)` + could have opened. `input a); wire evil; //` fails on the comment rule and + would fail on the item rule without it. + An explicit `input`/`output`/`inout` is **required**: an ANSI port without + one inherits the previous port's direction, and a refactoring that silently + makes a new port an input because the port above it was one is a trap. The + non-ANSI body declaration needs the direction anyway. +2. **The declaration**: the port is appended to the module's port list. + - **ANSI header** — the declaration text is appended to the header list. + - **Non-ANSI header** (`module m (a, b);`) — the *name* is appended to the + header list and the full declaration is written into the body, after the + last `input`/`output`/`inout` declaration; failing that before the first + item (its leading comments included, so they stay with their item); failing + that after the header's `;`. + - **An empty (`()`) or absent (`module m;`) port list** has no style to + follow, so the port is written the modern way: ANSI, in the header, and a + header with no list at all gains one. +3. **Every instantiation** of that module in the in-scope files, wherever it is + written — module body, `generate` region, `if`/`for`/`case` generate block, + or a `bind` directive: + - **Named connections** gain `.p(p)` when a signal called `p` is visible in + the scope the instantiation sits in (a net, variable, port, parameter, + genvar or task/function argument — not an instance or a type), and + `.p(/* TODO: connect */)` otherwise, with a warning naming every site left + that way. + - **`.*`** is never rewritten. When a same-named signal *is* in scope the + wildcard binds the new port by itself and nothing is said; when it is not, + a warning says the new port will not bind there and must be connected by + hand. + - **Ordered (positional) connections** gain a position at the end — see the + policy below. + - **An empty connection list** (`u1 ()`) is left exactly as it is: it + connects nothing before the change and nothing after it. A warning says so. +4. The whole thing is **verified** (below) and then confirmed against the shape + the plan promised. + +### `remove_port(files, file, offset)` + +The cursor may sit on the port in the header **or**, for a non-ANSI module, on +its body declaration; both are the same removal. + +- The port element leaves the header, taking exactly one comma with it: the one + after it, or — for the last element — the one before it. A deletion that ends + up alone on its line takes the line, so no blank line is left behind. + Removing the **last** element is two deletions rather than one range, because + the source may have written a comment between the comma and the element + (`.a(x), // about a` ⏎ `.b(y)`); one range would swallow it, and a comment is + never dropped. The comma's own blanks go with it unless a comment follows. +- A non-ANSI module also loses the body declaration: the whole item when it + declares only that port, or just that declarator when it declares several + (`input a, b;` → `input a;`). +- Every **named** connection `.p(expr)` is deleted from every instantiation in + scope. The connected expression goes with it — that is the point — but every + expression that is more than the port's own name (`.p(p)`, `.p()`, `.p`) is + listed in the warnings, because it is the user's code being deleted. +- **`.*`** sites are not edited; a warning says the signal the wildcard was + binding may now be unused. +- **An empty connection list** is not edited: there was nothing there. +- Every occurrence of the port's name in text **the preprocessor owns** — a + macro invocation's arguments (`` `BUMP(rst) ``), a `` `define`` body — is + reported, in the module's file and in every file the removal edits. vfmt does + not expand macros, so an invocation is one opaque token: nothing there can be + edited, and nothing there is visible to the body-use refusal either. Silence + would be the worst answer, because only a real preprocessor would discover + that the expansion names a port that no longer exists. This is M2's + macro-argument fix applied to the sibling feature, sharing its scan. + +### `propagate_ports(files, file, offset)` + +One instantiation — the one under the cursor, or the only one of the statement +the cursor's module name belongs to. Its named connections are diffed against +the instantiated module's declared ports, and the missing ones are appended in +declaration order, `.p(p)` or `.p(/* TODO: connect */)` by the same visibility +rule as `add_port`. Nothing else in the workspace is touched. + +### Layout + +Appended elements copy the list they join, which is the simplest rule that +stays correct: an element per line keeps an element per line at the last +element's own indentation, an inline list stays inline. Refactored output is +*edited source*, not reformatted source (umbrella Handshakes) — the user runs +the formatter afterwards if they want more. + +One case gets special handling because getting it wrong is not cosmetic: when +the last element carries a `//` comment, the comma is written **before** the +comment and the new element after it, as two insertions. A comma written after +`//` is a comma inside a comment. + +### Conditional compilation — where a new port may not go + +vfmt does not preprocess, so an `` `ifdef`` arm is ordinary text to it. That +makes "append after the last declared port" wrong in one specific, silent way: + +```systemverilog +module m ( + input clk +`ifdef HAS_RST + , input rst +`endif +); +``` + +The last declared port is inside the arm, so the byte after it is inside the +arm too, and a port appended there **only exists when `HAS_RST` is defined** — +the opposite of what "add a port" means. None of the five verification checks +can see this, by design: the file parses, no name changes meaning, and the +re-parsed header really does declare the port, because vfmt reads straight +through the `` `ifdef``. It is a *planning* mistake, not a verification gap, so +it is caught in the planner: + +- Before inserting, the directives written in the list — `Module.port_directives` + for the header, the `` `Directive`` items of the body for a non-ANSI + declaration — are counted from the start of the list to the insertion point: + `` `ifdef``/`` `ifndef`` open a region, `` `endif`` closes one, `` `else`` + and `` `elsif`` continue the one they are in. +- **A non-zero count refuses the whole refactoring**, naming the arm and its + line, and says to place the port by hand. (The ruling asked for `> 0`; `< 0` + — more `` `endif``s than opens, a region opened outside the list — is refused + too, since vfmt equally cannot tell what it would be writing into.) +- **A zero count proceeds, with a warning** naming the directives: the port + lands outside every arm, which is correct, but the module's port set is + configuration-dependent and the user should know that vfmt only sees one + spelling of it. + +A macro *item* in a body (`` `ASSERT_INIT(...) ``) is not counted: it is a +call, not a directive, and cannot open a region. + +## The ordered-connection policy + +Positional connections are where a port refactoring can silently change what a +circuit does, so each case is decided rather than guessed: + +| Situation | What vfmt does | +|---|---| +| `add_port`, ordered list whose length **equals** the module's port count before the change | Appends a position at the end. The new port *is* the new last port, so the end is where it belongs. | +| `add_port`, ordered list of a **different** length | **Refuses the whole refactoring**, naming the instance and both counts, and says to convert it to named connections first. vfmt cannot tell which port a short list meant to connect. | +| `add_port`, **empty** list (`u1 ()`) | Left alone, with a warning. An empty list connects nothing before *and* after; appending would bind the new port to position 0. | +| `add_port`, ordered site where no same-named signal is in scope | The position is written **empty** (`u1 (a, b, )`), not `/* TODO */`: a comment between two commas *is* an empty position, so a placeholder there would be a lie. Warned. | +| `remove_port`, **any** non-empty ordered list anywhere in scope | **Refuses the whole refactoring.** Dropping one positional connection re-binds every one after it. The message says to convert to named connections first. | +| `propagate_ports` on an ordered instantiation | Refused: there is nothing named to propagate. | + +The asymmetry is deliberate: appending to a full positional list is safe +because nothing before it moves; deleting from one is not. + +## The refusal list — exact + +`add_port` refuses when: + +1. `decl` is not exactly one directed ANSI port declaration (rules above). +2. The module is not indexed, or is declared in **more than one** indexed file + — the same ambiguity rule rename has, for the same reason: every + instantiation resolves by name. +3. `ModuleRef::At` names a file outside the in-scope set, or a position that is + in no module declaration. +4. The module already has a port of that name. +5. Any ordered instantiation's connection count disagrees with the module's + port count (above). +6. The module writes an `import` in its header and has **no** port list at all: + the `;` that ends such a header cannot be told from the import's own `;` + without preprocessing, so vfmt asks for `()` to be written first. (Today's + parser rejects that header outright, so this is a guard, not a path users + reach.) +7. The insertion point falls **inside a conditional arm**, or the directives + before it do not balance (above). +8. Verification fails (below) — including the capture case: a new port that + would take over what a name already means inside the module's body. + +`remove_port` refuses when: + +9. The position is not a module port (nor the body declaration of one). +10. Any instantiation in scope connects the module's ports **positionally**. +11. The port is still **used inside the module's body**, with the lines listed. + (A use inside a macro invocation's arguments is invisible to this rule — + it is a warning instead; see above.) +12. A deletion range would swallow a **comment** — a connection or a port with + a comment written inside it. Comments are never dropped (invariant 3), and + vfmt will not decide where a comment should move. +13. Verification fails. + +`propagate_ports` refuses when: + +14. The position is not an instantiation, or names a statement with several + instances (put the cursor on one). +15. The instantiation connects positionally, or with `.*`. +16. Every declared port is already connected — there is nothing to do, and a + "did nothing" success is a worse answer than a sentence. +17. Verification fails. + +All three also refuse when two computed edits would overlap, and when the +in-scope file set does not contain the file the request names. + +## The verification story + +M2's `check::verify` is *rename-shaped*: it demands that the token stream not +change shape at all. A port refactoring writes and deletes text, so that +contract cannot apply. Rather than weaken it — hard invariant 4's mindset — a +**second** entry point was added beside it, `check::verify_splice`, with a +contract of its own that is exactly as strict about everything the refactoring +did *not* ask for. `verify` is untouched; so is `vlog_formatter::verify`. + +**1. Lexical splice.** Every touched file is broken into *pieces* — code tokens +and comments, in source order, each with its span. The edited file's pieces +must equal the original's with the pieces the edits' own text spells written in +at the edits' positions, and the pieces inside a deletion removed. Kinds and +texts are compared, spans are not: an insertion legitimately moves which token +a comment attaches to without moving the comment. This catches an edit that +landed in a string, split or merged a token, wrote a comma into a line comment, +landed at the wrong position, or wrote one token more than it promised. + +**2. Comments are never dropped.** A deletion that covers a comment would +delete it from *both* sides of that comparison and pass, so it is refused +outright and separately — the one rule the piece comparison cannot see on its +own. + +**3. The file still parses.** A touched file may not gain a parse diagnostic it +did not already have. (Not "has none": a tolerant parse of a file that was +already broken still reports its old diagnostics, and refusing to refactor +because something else in the file is mid-edit would be useless in an editor.) + +**4. Resolution identity outside the edits.** M2's whole-file resolution print +— every declaration and every reference with a workspace-wide anchor — is built +before and after, for every **watched** file (the edited ones, plus every +in-scope file that spells the module's name as a whole word, M2's rule +unchanged). Entries whose name span **overlaps an edit** are excluded on both +sides: those are precisely what the user asked to change. Everything else must +be identical, with spans mapped through the edits. This is what refuses a port +that captures a body reference — the body's `cfg` used to be the net's, and +after the added port it would not be — and it does so without any special-case +knowledge of ports. + +**5. The shape check** (`ports.rs::confirm`), which is not a generalization of +anything in M2 and is specific to this feature. Checks 1–4 prove the edit is +lexically and semantically honest; none of them proves the new text landed in +the *port list* rather than in the parameter list. So the plan states the shape +it expects — the module's declared port names, and every instance's connection +names in order — the edited text is re-parsed, and the two must match. This is +what turns "the tokens are fine" into "the refactoring did what it said". + +Checks 1–5 run over the whole edit; any of them failing fails all of it. + +### Why the exclusion in check 4 is honest + +It looks like a hole ("names inside the edit are not checked") and it is worth +saying why it is not one. The excluded ranges are the *bytes the user asked to +change*, and nothing else: an insertion excludes only the inserted text, a +deletion only the deleted text. Every name outside them — in the same file and +in every watched file — is still pinned to the exact declaration it resolved to +before. What lives inside the edit is then pinned by check 5, which reads the +signature back out of the parsed text. The masked-corruption tests in +`check.rs` attack this pair directly: an edit spliced at the wrong position, an +edit that also rewrote an untouched token, an edit that also dropped a comment, +an edit that wrote more than it promised, and a deletion that swallows a +comment. + +### One change to shared code + +`Shift::map` (`lib.rs`) previously accumulated a shift for every edit with +`range.start < span.start`. That is wrong for an *insertion* — an empty range +never satisfies it, so a span beginning exactly where text was inserted would +not move. The predicate is now `range.end <= span.start`. For a rename, whose +edits all replace a whole name span, the two predicates say the same thing on +every span (the ranges are disjoint from every non-edited span), so M2's +behavior is unchanged — its 48 behavior tests and 2 corpus tests still pass +byte-for-byte. + +`check::print` gained an `excluded: &[TextRange]` parameter; `verify` passes +`&[]` and is otherwise untouched. + +## The LSP surface + +**Code actions** (`vfmt_server/src/ports.rs`), kind +`refactor.rewrite.vfmt.ports`, advertised alongside the existing quick-fix +kinds and honoring the client's `only` filter: + +- On a port declaration in a header (or its non-ANSI body declaration): + *"vfmt: remove port `p` (updates 3 instantiations)"*. +- On an instantiation missing connections: *"vfmt: connect 2 missing ports"*. + +Both carry the computed `WorkspaceEdit` inline — nothing to resolve — and +neither is offered where the refactoring would be refused. They answer for the +**start** of the requested range: a code action is about where the cursor is. + +A code-action request arrives on **every cursor move**, and computing an +answer means reading the whole in-scope file set and building an index — a +fifth of a second on a large workspace, on a single-threaded server. So the +engine exposes a cheap one-file question, `may_have_port_action(text, offset)`: +one parse of the buffer itself, no workspace and no I/O, answering "is this +position inside a port element, a non-ANSI port declaration, or an +instantiation?". The server asks it *before* materializing anything. It cannot +hide a refactoring: all three start by locating exactly one of those three +constructs. + +**Commands** (`workspace/executeCommand`, advertised in +`executeCommandProvider`): + +| Command | Arguments | Why it exists | +|---|---|---| +| `vfmt.addPort` | `[uri, module-name-or-Position, "input logic [7:0] cfg"]` | A code action carries no free-form input. This is the API a UI calls once it has asked the user; the VS Code side can grow an input box over it without the engine changing. | +| `vfmt.removePort` | `[uri, Position]` | A Vim user has no lightbulb; a command works wherever a keybinding does. | +| `vfmt.propagatePorts` | `[uri, Position]` | Same. | + +Each answers with the `WorkspaceEdit` for the client to apply. The server does +**not** push `workspace/applyEdit`: the client asked for the command and owns +the edit — and it keeps the server free of a request/response round trip on the +one path Vim users take. + +Engine **warnings** go to the existing `report_scope` path (a +`window/logMessage` each, one `window/showMessage`), the same one filelist and +rename warnings use. **Refusals** are LSP `RequestFailed` (-32803) carrying the +engine's sentence verbatim, M2's precedent. + +## Assumptions + +- **The caller hands over the in-scope files**, open buffers already overlaying + disk — the same list `WorkspaceIndex::build` was given. The crate does no I/O. + (M2's assumption, unchanged.) +- **A module name is unique in scope.** Every instantiation resolves by name; + if the workspace declares the name twice, vfmt refuses rather than guessing. +- **`inst.module` is compared by name.** A scope-qualified instantiation + (`pkg::mod u1 (...)`) is stored with its `::` glued and therefore does not + match a bare module name — such an instantiation is not found and not edited. + Real RTL does not write them; if it starts to, this is where to look. +- **vfmt does not preprocess.** An instantiation hidden inside a macro body or + produced by a macro invocation is one opaque token and cannot be edited or + even seen. An instantiation inside an `` `ifdef`` arm *is* ordinary tokens and + *is* edited, in every arm — the same honesty M2 documents. +- **vfmt does not elaborate.** "Is a signal called `cfg` in scope here?" is a + lexical-scope question answered by `vlog_semantic`, not an elaboration; a + name that would come from a wildcard package import that vfmt cannot resolve + reads as "not in scope", so the connection is a TODO rather than a wrong + guess. +- **A port refactoring is a rare, user-initiated request**, so re-parsing the + in-scope files that mention the module (twice: once to plan, once to verify) + is affordable. The substring prefilter M2 introduced keeps it to a handful of + files. Measured below. +- **Two spaces** are used for the one indentation vfmt has to invent (a body + declaration in a module with no items at all). Every other insertion copies an + indentation that is already in the file. + +## Handshakes + +**Consumed from `vlog_parser`** (no change required): + +- `parse_source_tolerant` and its diagnostics list (check 3), `tokenize`, + `LineIndex`, `TextRange`. +- `ast::{Module, PortList, AnsiPort, NonAnsiPort, PortDecl, Declarator, + Instantiation, Instance, Connections, OrderedConn, Connection, BindDirective, + GenBlock, GenElse, Item, ItemKind, ListDirective, RawText}` — `ListDirective` + and `ItemKind::Directive` are what make the conditional-arm guard possible — every span these carry (`span`, + `name_span`, `Comment::span`, `Meta::leading/trailing`) is what makes the + edits exact rather than textual. +- `token::{Token, TokenKind}` — the port-list parentheses walk and the piece + comparison. + +**Consumed from `vlog_semantic`** (no change required, nothing patched): + +- `analyze`, `Semantics::{scopes, symbols, symbol, references_of}`, + `Scope::{span, parent, lookup_local}` — the "is a signal called `p` visible + here?" question and the "is this port still used in the body?" question. +- `SymbolKind`, `WorkspaceIndex::{units, path}` — locating the module and + refusing an ambiguous one. +- M2's `check`/`Scope` machinery inside this crate. `rename.rs`'s two + preprocessor scans were factored — `Scope::define_sites` and + `Scope::macro_argument_sites` now return *sites*, and each caller writes its + own sentence — so the port refactorings reuse the scan without inheriting + rename's wording. M2's warning text and ordering are byte-for-byte + unchanged; its 48 behavior tests pin that. + +**Promised to `vfmt_server`** (and to any future CLI): + +- None of the four public functions panics, and none 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 and non-overlapping. **Insertions are empty ranges** — new for M3, and + the reason `Shift::map` changed — so a client applying them back-to-front + behaves correctly. +- `warnings` are informational: an `Ok` with warnings is still safe to apply. +- `PortAction.title` is user-facing text; the server does not rewrite it. + +**Changed in `vfmt_server`** (protocol layer only): `code_action::wanted` is +now `pub` so the port actions can honor the same `only` filter the lint actions +do; `server.rs` gained the `workspace/executeCommand` arm and the port-action +call inside the existing `textDocument/codeAction` arm; `main.rs` advertises +`executeCommandProvider` and the new code-action kind. + +**Requested of nobody.** No change was needed in `vlog_parser`, +`vlog_semantic`, `vlog_formatter` or `vfmt_core` for this milestone. + +## Status / TODO + +- [x] `ports.rs` in `vlog_refactor`: `add_port`, `remove_port`, + `propagate_ports`, `port_actions` +- [x] `decl` validated by parsing it as a port declaration, with an explicit + direction required +- [x] ANSI and non-ANSI headers, empty and absent port lists +- [x] Named, ordered, `.*` and empty connection lists, in module bodies, + generate blocks and `bind` directives +- [x] Same-named-signal lookup through `vlog_semantic` scopes; `/* TODO: + connect */` and its warning otherwise +- [x] The ordered-connection policy, both directions, with refusals +- [x] Removal refusals: positional connection, body reference, swallowed + comment +- [x] Dropped-expression warnings; `.*` warnings both ways +- [x] `check::verify_splice` — lexical splice, comment rule, parse rule, + resolution identity outside the edits — plus the shape check +- [x] Masked-corruption attacks for every new forgiveness (10 attacks and 2 + positive controls in `check.rs`) +- [x] `vfmt_server`: code actions, three commands, capabilities +- [x] `may_have_port_action` — the one-file pre-check that keeps a + cursor-move-frequency code-action request off the workspace walk +- [x] Conditional-compilation guard on both insertion paths: refuse inside an + arm, warn when the list carries directives at all (QA HIGH #1) +- [x] Preprocessor warnings on removal — macro-invocation arguments and + `` `define`` bodies, in the module's file and every edited file, sharing + M2's scan (QA HIGH #2) +- [x] Tests: 138 in `vlog_refactor` (36 unit — 12 of them the splice + verifier's, 10 attacks and 2 positive controls — 50 behavior in + `tests/ports.rs`, 48 rename behavior, 4 corpus), 9 in `vfmt_server`'s + `ports.rs`, 2 capability assertions, 1 e2e session covering a code + action, all three commands and two refusals +- [ ] Deferred to the umbrella backlog: reorder ports, parameter add/remove, + task/function arguments, ordered → named conversion (which would turn + three of the refusals above into an offer to convert first) +- [ ] Deferred: a VS Code input box over `vfmt.addPort` (the command is the API + until then; M4's instantiate work is the natural moment) + +## Corpus acceptance + +`cargo test --release -p vlog_refactor --test corpus -- --nocapture`, over the +860 `.v`/`.sv`/`.svh` files in `corpus/` (Ibex, OpenTitan, PULP common_cells, +picorv32): + +``` +corpus add_port over 860 files: Ok((6, 18)) in 0.39s (release; 1.9s debug) +corpus rename over 860 files: Ok((6, 18)) in 0.38s +``` + +Adding `input logic vfmt_probe_i` to `prim_fifo_sync` — a module OpenTitan +instantiates all over — edits **6 files in 18 places**: the declaration, and +every instantiation of it in the corpus, all of which are named-connection +sites. Every edit is asserted to be an insertion of non-empty text, and the +whole thing including index rebuild and verification takes 0.39 s. +The second test asks `port_actions` at 200 offsets spread over a real file and +requires every offered action to carry a real edit and a real title, and a panic +at none. + +## Work log + +**2026-08-24 — dev agent.** Built `ports.rs`, `verify_splice`, and the server +surface. The decisions worth recording: + +- **A second verifier, not a widened one.** The first thing tried was to make + `check::verify` take the splice case as well. It does not fit: its whole + strength is "the token stream has the same length and the same tokens", and a + port refactoring changes both on purpose. Widening it would have meant + softening the rename's contract to accommodate a case renames never produce — + the exact shape of the mistake hard invariant 4 is written about. So + `verify_splice` sits beside it, sharing the resolution print (which *is* + reusable) and nothing else, and `verify` is byte-for-byte the function M2 + shipped except for the `&[]` exclusion argument. +- **Pieces, not tokens, for the lexical check.** Comparing tokens with their + attached comments — which is what `tokens_match` does — cannot work here: an + insertion moves which token a comment attaches to without moving the comment. + Flattening to a sequence of code tokens *and* comments in source order makes + the comparison exact and makes the invariant-3 rule (no deletion covers a + comment) a separate, explicit line rather than an emergent property. +- **The shape check exists because the other checks cannot see intent.** + Nothing in a lexical or a resolution comparison says "this text is in the + *port list*". Reading the signature back out of the edited text is three + dozen lines and it is the check that would have caught the worst plausible + bug in this feature (an insertion landing in `#( ... )`). It is also what + caught the real bug found while writing it: appending + `/* TODO: connect */` to a *positional* list produces a list with zero + connections, not one, because a comment between commas is nothing at all. The + policy changed to "write the empty position, and say so". +- **The comma-before-the-line-comment split.** Appending after a `//` comment + writes the comma into the comment; appending before it moves the comment onto + the new port. Two insertions — comma before, element after — keeps the + comment with its own port and is the reason `append_to_list` returns a `Vec`. + Deletion has the mirror image of the same problem — the comma of the *last* + element may have a comment after it — so `remove_element` returns a `Vec` + too, and the verifier's comment rule is what found it: the one-range version + produced a trailing comma and was refused by the parse check. +- **Positional connections are decided per case, in the table above**, rather + than by one rule. The asymmetry (append may, delete may not) is the honest + one: appending to a full positional list moves nothing that was already + there. +- **`port_actions` computes the edits eagerly**, which the milestone asks for + (the action carries its `WorkspaceEdit` directly) and which has the pleasant + side effect that an action is only offered when the refactoring actually + works — the verification has already run by the time the lightbulb appears. + The cost is one whole refactoring attempt per code-action request, and those + arrive on every cursor move: over the 860-file corpus that is 0.39 s of + workspace read, index build and verification for a cursor sitting in an + `always` block. Hence `may_have_port_action`, the one-file pre-check the + server asks first; it is the reason the eager design is affordable at all, + and it was worth building before QA found it with a stopwatch. +- **The empty-connection-list case is a warning, not a refusal.** `u1 ()` + connects nothing before the change and nothing after it, so the edit is + correct as "no edit"; refusing the whole refactoring because one instance + writes `()` would make `add_port` unusable on real RTL. +- **The `PortList::None` + header-`import` guard** is unreachable with today's + parser (which rejects that header shape outright). It is kept because the + alternative — finding the header's `;` by scanning — would be wrong the day + the parser learns that shape, and a refusal is cheap. + +Checks at the end: `cargo fmt --all -- --check` clean, `cargo clippy +--all-targets` silent (zero warnings, workspace-wide), `cargo test --workspace` +green at **1164** tests (was 1085). No `unwrap`/`expect`/`panic!` and no +`unsafe` in any library path of either crate (test modules only). One +`#![allow(clippy::mutable_key_type)]` in `vfmt_server/src/ports.rs`, with the +same reason `rename.rs` carries: `WorkspaceEdit.changes` is keyed by +`lsp_types::Uri`, whose interior mutability is its own parse cache and takes no +part in `Hash`/`Eq`. + +Two things worth flagging for review: + +- **`Shift::map`'s predicate changed** (`range.start < span.start` → + `range.end <= span.start`). The argument that this cannot move a rename is in + the verification story; M2's whole suite passing is the evidence, but it is a + shared-code change and deserves a second pair of eyes. +- **`add_port` on an ordered site writes an empty position** (`u1 (a, b, )`). + It is legal SystemVerilog and it is warned about, but it is the one output + here that will look like a bug to a reader who has not read the warning. The + alternative — connecting a name that is not declared — creates an implicit + net, which is worse. + +**2026-08-24 (later) — dev agent, rework after QA round 1 and the lead's three +rulings.** All three closed; nothing else in the design moved. + +**1. `add_port` inside an `` `ifdef `` arm — now refused (QA HIGH #1).** The +guard is exactly the ruling: count `` `ifdef``/`` `ifndef`` opens minus +`` `endif`` closes over the directives written *before the insertion point* — +`Module.port_directives` for the header path, the `` `Directive`` items of the +body for the non-ANSI declaration path — and refuse when the count is not zero, +naming the arm and its line. When directives exist but the point is balanced, +the edit proceeds with a warning naming them, because the module's port set is +configuration-dependent either way and vfmt only ever sees one spelling of it. +`` `else``/`` `elsif`` continue a region rather than opening one; a macro item +in a body is a call, not a directive, and is not counted. + +The ruling said "unbalanced (> 0)"; the implementation refuses on **any** +non-zero count. A negative count means a region was opened outside the list, and +vfmt can tell just as little about what it would be writing into — refusing is +the same answer for the same reason. Flagging the widening rather than doing it +quietly. + +Where the guard lives matters and is now stated in the README: this is a +*planning* rule, not a verification one. All five verification checks correctly +pass QA's reproduction — the file parses, no name changes meaning, and the +re-parsed header does declare the port, because vfmt reads through the +`` `ifdef``. Only the planner can know the insertion point was wrong. +Regression tests: QA's exact source as a crate-level refusal +(`a_port_that_would_land_inside_an_ifdef_arm_is_refused`), the balanced mirror +(`a_port_list_with_a_closed_conditional_is_edited_and_reported`), the non-ANSI +body path (`a_non_ansi_body_declaration_that_would_land_inside_an_ifdef_arm_is_refused`), +and QA's e2e shape kept: the existing port session gained a third file and a +`vfmt.addPort` that comes back `-32803` with the arm named. + +**2. `remove_port` macro silence — now warned (QA HIGH #2).** M2's two scans +were factored rather than copied: `Scope::define_sites` and +`Scope::macro_argument_sites` return *sites* (macro name, line, and whether the +name is the macro's own), and each caller writes its own sentence. Rename's +warning text and the order it emits warnings in are byte-for-byte what M2 +shipped — its 48 behavior tests pin that, and they pass unchanged. `remove_port` +now scans the module's file and every file it edits, and says the thing that is +actually news for a removal: the expansion will name a port the module no longer +has. A macro *named* like the port is skipped as noise; the ruling named +invocation arguments and `` `define`` bodies, and those are what is reported. +Three regression tests, including QA's exact repro and one where the macro call +lives in an *edited instantiating* file rather than the module's own. + +**3. `Shift::map`'s implicit invariant is now written down.** QA's second +divergence zone (a span starting strictly inside a non-empty replacement) is +unreachable today and is not a defect, but nothing said so at the function. Its +doc comment now states the assumption — every span is either identical to one +edit's range or fully disjoint from all of them — says the number returned for a +violating span is arbitrary rather than a location, and points at +`check::print`'s `excluded` list as the way to keep it true. + +Not changed, deliberately: the CRLF cosmetic QA filed as low +(insertions always write `\n`). It is a mixed-line-ending wrinkle, the +Handshakes already say refactored output is edited source rather than formatted +source, and threading a per-file line-ending choice through every insertion +helper would be more machinery than the wrinkle costs. Recorded here so the +decision is visible rather than forgotten. + +Gates after the rework: `cargo fmt --all -- --check` clean, `cargo clippy +--all-targets` zero warnings workspace-wide, `cargo test --workspace` green at +**1170** tests (was 1164; +6 crate-level regressions, the e2e addition living +inside the existing session). Corpus unchanged: `add_port` over the 860 files is +still `Ok((6, 18))` in 0.36 s, so the guard false-refuses nothing in real RTL. +One clippy-driven tidy while there: the header planner's arguments are now a +`File { text, path, tokens }` struct rather than eight positional parameters. + +## QA log + +**2026-08-24 — QA agent.** + +### Gates + +- `cargo fmt --all -- --check` — clean. +- `cargo clippy --all-targets` — clean, zero warnings, workspace-wide. +- `cargo test --workspace` — green, **1164** tests, 0 failures, matching the + Work log's number exactly (was 1085 before this milestone). Per-crate + breakdown confirmed against the `Running`/`test result` pairs: + `vlog_refactor` unit 36 + `corpus` 4 + `ports` 44 + `rename` 48 = 132; + `vfmt_server` unit 222 + `e2e` 13 = 235; the rest unchanged from M1/M2. + All three gates: **pass, claims confirmed.** + +### Priority — `Shift::map`'s predicate change (`range.start < span.start` → +`range.end <= span.start`) + +**Verdict: the claim holds. Not a defect.** Verified two ways: by +construction/proof, and empirically with 9 new unit tests added temporarily +to `lib.rs`/`check.rs`/`ports.rs` (run, all passed, then reverted — no probe +code left in the tree; see the file-list note at the end of this entry). + +The two predicates disagree on a span `S` exactly when +`range.start < S.start <= range.end`... precisely, two distinct disagreement +zones: + +1. **Insertion at a span's start** (`range` empty, `range.start == range.end + == S.start`): old predicate (`range.start < S.start`) is `false` (doesn't + shift); new predicate (`range.end <= S.start`) is `true` (shifts). This is + exactly the bug the README describes and the change fixes — reproduced + directly: an insertion at position 5 followed by a span `[5,8)` maps to + `(8,11)` under the new code; hand-tracing the old predicate for the same + inputs gives `(5,8)` (unshifted, silently wrong — it would land the + trailing span on top of the freshly inserted text). +2. **A span nested strictly inside a non-empty edit range** + (`range.start < S.start < range.end`) — a *second*, previously + undocumented divergence zone I found while probing, distinct from the one + the README calls out. Reproduced: edit `[0,4)→"xy"`, probe span `[2,3)`. + New predicate leaves the span unshifted at `(2,3)`; the old predicate + would have shifted it to `(0,1)`. Neither answer is meaningful (those + bytes were replaced wholesale, so there's no correct "where did they go"), + so this zone doesn't argue either predicate is more correct — it only + matters if it's ever reachable. + +**Why zone 2 can't be reached in practice, for either rename or ports:** +`Shift::map` is only ever called (via `check.rs`'s `print()`/`Shifts::map`) +on a `Symbol.name_span` or `Reference.name_span`, which the crate's own +Handshakes promise are exact, literal identifier-token spans. Verilog tokens +never nest or overlap — a byte belongs to at most one token — so no such span +can ever start strictly inside a *different* edit's non-empty byte range +without being identical to it (and the identical case is handled separately, +by the `find(|(range,_)| *range == span)` length lookup, which both old and +new code share unchanged). For ports specifically there's a second, +independent belt: `print()` filters out any declaration/reference whose own +span *overlaps* an edit (`excluded`) before it ever reaches `shifts.map`, so +even a hypothetical nested span in that data is discarded first. + +For **rename** specifically (the code path M2's whole suite exercises and +this change must not move): every edit range is a whole identifier-name span +being replaced 1:1, and two distinct identifier tokens can never be +byte-adjacent in valid Verilog (some non-identifier byte — an operator, +whitespace, a delimiter — always separates them), so zone 1 (insertion +boundary) never arises either, since rename produces no insertions at all +(only replacements). Combined with the corpus number being pinned at exactly +`Ok((6, 18))` before and after this milestone and all 48 rename behavior +tests passing byte-for-byte, this is strong independent (test-suite-level) +corroboration on top of the structural argument. + +**One soft spot worth naming, not a finding**: the safety argument rests on +an *implicit* invariant ("every span this function is ever called with is +either identical to an edit or fully disjoint from it") that isn't asserted +or tested as its own property anywhere — it's true by construction from how +`print()`/`rename.rs` build their inputs today, but nothing would fail loudly +if a future caller violated it. Not asking for a fix; flagging so a future +change to `check.rs`'s call sites gets this section re-read. + +### Splice-verifier attacks (`check::verify_splice` / `pieces_match`) + +Added 5 new attacks (temporarily, to `check.rs`'s test module; run, then +reverted) beyond the dev's own 10 attacks + 2 controls, targeting angles the +task brief specifically raised: + +| Attack | Result | +|---|---| +| Reorder two comments (`// A`, `// B` → `// B`, `// A`) with an edit that claims to touch neither — same multiset of comment texts, different sequence order | **Rejected.** `pieces_match` compares an ordered sequence built from source order, not a multiset, so a physical swap is caught as "piece N differs" even though the bag of texts is unchanged. | +| Move a comment's exact text inside a string literal elsewhere in the file, with an edit that claims no changes | **Rejected.** The comment disappears as a `Piece::Comment` (piece-count/positional mismatch against the re-tokenized "after"); reappearing inside a string's token text doesn't fool the piece-kind comparison. | +| A declared edit range covering only *half* the bytes of a `/* ... */` comment (partial overlap, not the whole span) | **Rejected**, via the existing "would delete a comment" rule — `overlaps()` is a share-a-byte test, so a partial overlap still counts as "deleted" and refuses outright, which is the conservative direction. | +| An edit landing in the parameter list `#( ... )` instead of the port list `( ... )` — lexically clean, no comment touched, resolution identity holds, file still parses | **`verify_splice` alone returns `Ok`** — confirmed directly by calling it on a hand-built plan. This is not a hole; it is exactly the gap the README says `ports::confirm` (the shape check) exists to close, checks 1–4 have no concept of "port list vs. parameter list". | +| The same parameter-list-injection plan, run through `ports::confirm` (the shape check) with the plan's own `expected` `Shape` (as `plan_add` would compute it) | **Rejected** — `confirm` re-parses the edited text, reads back the module's actual declared ports, sees `cfg` is not among them (it's a parameter), and refuses with "would not leave the signature vfmt intended". This proves end-to-end that a parameter-list capture is caught, and specifically that it is `confirm`, not `verify_splice`, doing the catching — matching the README's claim in "The shape check" and "One change to shared code" precisely. | + +No holes found in the verifier itself. The two-layer design (checks 1–4 for +lexical/semantic honesty, check 5/`confirm` for "landed in the right list") +holds up exactly as documented when attacked at the seam between the two +layers. + +### Port-semantics attacks (`add_port`/`remove_port`/`propagate_ports`, public API) + +20 probes (temporarily added as `crates/vlog_refactor/tests/qa_probe.rs`, run +with `--nocapture`, then deleted) covering the refusal list and the task +brief's attack ideas: + +**Passed — refused correctly:** +- Adding a port named like an existing port → `` `m` already has a port named `clk`. `` +- `"input a, input b"` (two explicit directed ports) → refused, "not a single ANSI port declaration". +- `"input x, y"` — **the direction-inheritance case the brief called out + specifically** (one `input` keyword, two comma-separated declarators, `y` + inheriting `x`'s direction). This is legal ANSI syntax and a *different* + parser path than `"input a, input b"`. Confirmed it still refuses: the + probe module ends up with **two** `AnsiPort` entries, so `parse_port_decl`'s + `let [port] = ports.as_slice()` check catches it the same way. +- Every decl-injection string tried (`"input a); wire evil; //"`, `` "input a) ; initial $fatal; module q (input b" ``, + `"input a) (input b"`, `"input a)) (( input b"`, `` "input a /* ) */ b" ``, + `` "input a `define X 1" ``) — all refused, none escaped the throwaway-header + probe. (One string I initially treated as an injection attempt, + `"input a[__vfmt_port_probe]"`, is not one on reflection — it's a legal ANSI + port named `a` with an unpacked-array dimension that happens to *mention* + the probe module's name; the probe is discarded after parsing, so there is + nothing for it to interact with. Correctly accepted; my test's original + expectation was wrong, not the code.) +- Duplicate module names in the workspace (`m` declared in two files) → + refused, "declared in more than one indexed file". +- `propagate_ports` on an instantiation of an unindexed module name → + refused, "vfmt indexes no module named `unknown_mod`". +- `.rst()` (empty named connection) is correctly treated as *already + connected* by `propagate_ports` — refused with "already connects every + port `sub` declares" rather than treating the empty parens as missing. +- `remove_port` on a port used only inside an `` `ifdef NEVER_DEFINED`` + arm → **refused** ("still used inside `m` at m.sv:6"), confirming vfmt's + documented "does not preprocess" honesty extends correctly to body-use + checking: an ifdef arm is ordinary tokens regardless of whether the guard + is ever true. +- Parameterized instantiation `sub #(8) u1 (...)` — `add_port` correctly + finds the *port* list's parens, not the parameter list's, both with a + populated connection list and with an empty one (`sub #(8) u1 ();`, which + correctly warns "writes an empty connection list" rather than silently + binding position 0). +- Instance arrays `sub u1 [3:0] (.clk(clk))` — one connection edit covers the + whole array declaration correctly (a single `Instance` node, as expected of + a non-elaborating analyzer). +- `bind top leaf b_leaf (...)` — `remove_port` correctly rewrites the bind's + own connection list (2+2 deletions, matching the documented "last element + is two deletions" shape), confirming bind directives are treated as + instantiation sites for removal too, not just for `add_port`. +- `port_actions` swept at all 155 byte offsets of a file combining an + `` `ifdef``, a comment, a `[W-1:0]` port and an instantiation — no panic + anywhere. +- `` // verilog_format: off `` around the header — no interaction; `add_port` + is indifferent to formatter directives, as expected (different crate, + different concern). +- An undefined-width parameter in `decl` (`"input logic [W-1:0] cfg"` on a + module with no `W`) is **accepted** — `decl`'s own free-form text is only + checked for *syntax* against a throwaway header, never against the real + target module's actual parameter set. This matches the README's own + description of what `parse_port_decl` checks (syntax only) and reads as + intentional scope, not a bug: the user is trusted with `decl`'s content the + same way they'd be trusted typing it directly into the file. Noting it + because the task brief asked about it explicitly, not because it's a + finding. + +**HIGH — `add_port` can silently place the new port inside a conditional +`` `ifdef `` arm, with no warning** + +Reproduced twice: once through the crate's public `add_port` API, and +independently through the **real server binary over stdio** +(`vfmt.addPort` executeCommand — see below) to rule out a test-harness +artifact. + +```systemverilog +module m ( + input clk +`ifdef HAS_RST + , input rst +`endif +); +endmodule +``` + +`add_port(files, ModuleRef::Name("m"), "input logic cfg")` succeeds +(`Ok`, zero warnings) and inserts `cfg` **on the line before `` `endif``**, +i.e. *inside* the `HAS_RST` conditional arm: + +```systemverilog +module m ( + input clk +`ifdef HAS_RST + , input rst, +input logic cfg +`endif +); +endmodule +``` + +Root cause: `header_edits` (`crates/vlog_refactor/src/ports.rs:614-655`) and +`declared_ports` (`ports.rs:432-444`) treat the module's `PortList` as a flat +list of `AnsiPort`/`NonAnsiPort` entries and append after the textual +position of the **last declared port's own span** — but `declared_ports` +never consults `Module.port_directives` (`vlog_parser::ast`, the field +`parse_port_decl` itself checks — but only against the *throwaway probe* +module, never against the *real target* module in `header_edits`/`plan_add`). +When the last declared port sits inside an `` `ifdef``/`` `endif`` region, +"after the last port" is a byte position that is still textually inside that +region. + +This is not a lexical, resolution, or shape-check failure — `verify_splice` +correctly finds nothing to object to (the file parses, no comment moves, no +name outside the edit changes meaning), and `confirm`'s shape check correctly +finds `cfg` declared as a port in the re-parsed text (vfmt doesn't +preprocess, so it parses through the `` `ifdef`` regardless of the guard). So +none of the four checks can catch this class of bug **by design** — it's not +a verification gap, it's a planning gap: the plan itself asked for the wrong +insertion point. Consequence: if `HAS_RST` is undefined at compile/synthesis +time, `cfg` silently does not exist as a port of `m` at all, contradicting +the refactoring's entire premise (add an unconditional port), and nothing in +the response — no warning, no refusal — tells the user. This is exactly the +"add-port when module has directives inside port list" scenario the task +brief named. + +Confirmed independently over the **real server binary via stdio** +(`workspace/executeCommand` → `vfmt.addPort`, `["","m","input logic cfg"]`): +the returned `WorkspaceEdit`'s single insertion lands at line 3 (0-indexed) +of the source above — one line before `` `endif `` on line 4 — reproducing +the finding through the full LSP stack, not just a direct crate call. + +Not fixed (design decision, not a small/unambiguous one — needs either a +refusal when the append point falls inside `module.port_directives`, or +routing the insertion to land after the *whole* directive-guarded region, or +at minimum a warning naming the conditional). Flagging for dev/lead. + +**HIGH — `remove_port` never warns (or refuses) when the only remaining use +of the port is inside a macro invocation's arguments** + +Direct parallel to M2's round-1 HIGH #2 (`rename`'s macro-invocation-argument +silence), reproduced for M3: + +```systemverilog +`define BUMP(x) x = x + 1 +module m ( + input clk, + input rst +); + initial `BUMP(rst); +endmodule +``` + +`remove_port(files, "m.sv", )` returns **`Ok`** with **zero +warnings**, deleting `rst` from the header. `body_uses` +(`crates/vlog_refactor/src/ports.rs:945-976`, the function backing refusal +rule 10, "the port is still used inside the module's body") only walks +`Semantics::references_of`, i.e. resolved semantic references — and +`` `BUMP(rst) `` lexes as a single opaque `Ident` token +(name-and-arguments together, same as M2's finding for rename), so `rst` +inside it is invisible to `vlog_semantic` and produces no reference for +`body_uses` to find. Unlike `rename.rs`, which grew a dedicated +`Scope::macro_use_warnings` scan for exactly this class of opaque-token +occurrence after M2's round 1, `ports.rs` has **no equivalent scan anywhere** +— confirmed by `grep -n macro crates/vlog_refactor/src/ports.rs`, whose only +hits are `parse_port_decl`'s check that the *new* `decl` string itself +contains no macro call, which is a different check entirely. + +Consequence: removing `rst` here produces a module that compiles (macro +invocations aren't preprocessed, so `` `BUMP(rst); `` is still ordinary, +valid-looking tokens to any downstream tool that also doesn't preprocess) but +whose macro expansion, once actually preprocessed by a real compiler, +references a port name that no longer exists — with the refactoring reporting +complete, silent success. Not a byte-level corruption (hard invariant 1 +is about vfmt's own output being verified-correct or refused, and the output +here *is* what the edit promised), but it is the same "silently wrong, +zero indication" shape QA flagged as HIGH in M2, applied to the sibling +feature that reused none of the fix. + +Not fixed (needs the same design call M2's dev made for rename — warn like a +macro body, or refuse — which is the dev's/lead's call, not QA's). Flagging +for dev/lead; the fix pattern (`Scope::macro_use_warnings`, `rename.rs`) is +already in the codebase as precedent if a warn is chosen. + +**Low / cosmetic, not filed as a finding**: `add_port` on a CRLF (`\r\n`) +file inserts new text using a bare `\n` line ending +(`crates/vlog_refactor/src/ports.rs`'s `append_to_list`/insertion helpers +always write `\n`), producing one LF-terminated line inside an otherwise +CRLF file. Not corruption (every check passes; verified independently), just +a mixed-line-ending cosmetic wrinkle a formatter pass would clean up anyway +per the "refactored output is edited source, not reformatted source" +Handshake. Noting for awareness, not asking for a fix. + +### Real server binary over stdio + +Ran the dev's own `a_port_code_action_and_the_port_commands_round_trip_over_the_wire` +(`crates/vfmt_server/tests/e2e.rs:1001`) as part of the full-suite gate run +(pass, part of the 13 e2e sessions) — it already drives one `textDocument/codeAction` +and all three `workspace/executeCommand`s (`vfmt.propagatePorts`, +`vfmt.addPort` twice, once refused) against the real `vfmt-server` binary, +and asserts the code action's inline `WorkspaceEdit`, the command responses' +edits, the advertised capabilities (`executeCommandProvider`, the +`refactor.rewrite.vfmt.ports` code-action kind), and the `-32803` refusal +shape. I re-ran it in isolation to confirm independently rather than trust +the aggregate count, and it passed. + +I additionally wrote and ran (temporarily, then reverted) my own independent +e2e session — not reusing the dev's fixture — that drives `vfmt.addPort` +through `workspace/executeCommand` against the real binary on the +`` `ifdef ``-in-port-list source above; see the HIGH finding. + +### Files touched during QA (all reverted; nothing left in the tree) + +`crates/vlog_refactor/src/lib.rs`, `crates/vlog_refactor/src/check.rs`, +`crates/vlog_refactor/src/ports.rs`, `crates/vfmt_server/tests/e2e.rs` each +had temporary `#[test] fn qa_*` functions added, run, and then restored +byte-for-byte from a pre-edit copy (diffed against the copy to confirm a +clean revert). `crates/vlog_refactor/tests/qa_probe.rs` was created, run, +and deleted. `git status --short` after cleanup shows only the dev's +original changes; `cargo build -p vlog_refactor -p vfmt_server --tests` +rebuilds clean. + +### Summary + +| Claim | Verdict | +|---|---| +| `cargo fmt` / `cargo clippy` / `cargo test --workspace` clean | **Pass** | +| Test count (1164) | **Pass, confirmed** | +| `Shift::map` predicate change is safe for rename | **Pass, confirmed** — proof + 9 empirical tests; a second, unreachable divergence zone documented for the record | +| `verify_splice` (lexical/comment/parse/resolution) resists new attacks | **Pass** — comment reordering, comment-into-string, partial-comment-deletion all rejected | +| `confirm` (shape check) is what catches a parameter-list capture, not `verify_splice` | **Pass, confirmed directly** — matches the README's own claim exactly | +| Refusal list (duplicate name, two-port decl, direction-inherited two-port decl, injection strings, ambiguous module, unindexed module, positional-connection refusals, ifdef body-use refusal) | **Pass**, no gaps found | +| `add_port` can silently land a new port inside an `` `ifdef `` arm | **HIGH finding** — confirmed via crate API and real server binary, not fixed, flagged for dev/lead | +| `remove_port` never warns about a port only used inside a macro invocation | **HIGH finding** — direct parallel to M2's round-1 HIGH #2, not fixed, flagged for dev/lead | +| CRLF new-text line ending | **Low/cosmetic**, not filed | +| Code action + executeCommand over real stdio | **Pass** — dev's own e2e test re-verified, plus one independent QA-authored session | + +No fixes applied — both HIGH findings need a design decision (warn vs. +refuse, and where), which is the dev's/lead's call per CLAUDE.md, not QA's. +Nothing else found needed one either. No probe files or temporary test code +left in the tree. + +**Overall verdict: ship-after-fixes.** Everything the milestone's own claims +assert about gates, the shared-code change, and the two-layer verifier holds +up under direct adversarial attack — this is a well-built safety net and I +could not get it to forgive a masked corruption. The two HIGH findings are +both silent-wrong-output-not-corruption shapes (the byte-level safety net is +sound; the *planning* layer above it has two gaps a user would not discover +until synthesis or simulation), one of which is a near-exact repeat of a +defect class M2 already has a fix pattern for. Neither blocks the safety +invariants CLAUDE.md cares about most (never corrupt, idempotent, comments +preserved), so this is not a "needs-rework" verdict, but both should be +closed (or explicitly, consciously deferred with a warning in the interim) +before this ships to real users editing real conditional RTL. + +**2026-08-24 (round 2) — QA agent.** Re-verification after the dev's rework +of both round-1 HIGH findings and the `Shift::map` documentation ask, per the +lead's rulings. + +### Gates + +- `cargo fmt --all -- --check` — clean. +- `cargo clippy --all-targets` — clean, zero warnings, workspace-wide. +- `cargo test --workspace` — green, **1170** tests, 0 failures — matches the + Work log's number exactly (was 1164 in round 1; summed every + `test result: ok. N passed` line in the run to confirm the total rather + than trust the Work log's arithmetic). +- All three gates: **pass, claims confirmed.** + +### Round-1 HIGH #1 (`` `ifdef ``-in-port-list) — mechanism verified, holds +under nested/chained attacks + +Re-attacked `guard_conditionals`/`nesting_of`/`list_directives`/ +`body_directives` (`crates/vlog_refactor/src/ports.rs:701-808`) at the +mechanism level rather than re-running the original repro unchanged — the +brief's own round-2 attack list, plus one I added: + +| Attack | Expected | Result | +|---|---|---| +| Last port sits in an `` `else`` arm (`` `ifdef``/.../`` `else``/*port*/`` `endif``) | Refuse — `else` continues the region, doesn't reset depth | **Refused**, correctly naming the `` `ifdef`` that opened the arm | +| `` `elsif`` chain, last port in the final `` `else`` | Refuse, same reason | **Refused** | +| Nested `` `ifdef OUTER``/`` `ifdef INNER``/*port b*/`` `endif``/*port rst*/`` `endif`` — insertion point is textually *after the inner* `` `endif`` but still inside the *outer* arm | Refuse — depth must net to 1, not be fooled by the inner close | **Refused**, correctly naming `` `ifdef INNER`` as the innermost still-open arm at the insertion point (depth-counting is genuinely nesting-aware, not just "any directive present") | +| A directive pair (`` `ifdef UNUSED``/`` `endif``, nothing declared inside) sitting entirely *after* the last real port — the insertion point precedes both | Must **not** refuse (nothing is inside any arm at the insertion point) | **Accepted** (not refused) — the guard correctly does not fire on directives it hasn't reached yet | +| Non-ANSI module, last port's *body* declaration wrapped in `` `ifdef``/`` `endif`` (the header-name-list path has no directives at all here — only `body_directives` can catch this) | Refuse via the body path specifically | **Refused**, confirming the fix really is applied to *both* insertion paths (`list_directives` for ANSI/header, `body_directives` for non-ANSI/body), not just the one QA's round-1 repro happened to exercise | +| A stray `` `endif`` with no matching `` `ifdef`` before the insertion point (malformed input, negative depth) | Refuse ("do not balance"), no panic | **Refused** with the "do not balance" message, not the "would land inside the arm" one — confirms the `depth > 0` / `depth != 0` two-step correctly separates "positively inside an arm" from "unbalanced, can't tell" and that the widened `!= 0` (not just `> 0`) ruling actually fired | + +No corruption, no panic, and — importantly — no *false* refusal: the +trailing-directive case proves the guard is reading the insertion point's +actual position, not just "does this list contain any directive at all". + +**One imprecision found, not filed as a finding (documenting for the +record):** in the trailing-directive-after-insertion case above, the edit is +correctly accepted, but the accompanying warning still names the (entirely +irrelevant, position-wise) trailing directives: `` "`m`'s port list carries +compiler directives (`ifdef UNUSED` at m.sv:4, and 1 more), so what ports it +declares depends on the configuration; vfmt added the port outside every +conditional arm." `` The new port is *not* actually configuration-dependent +here (nothing is declared inside that trailing, empty `` `ifdef``), because +`guard_conditionals`'s warning branch reads from the full unfiltered +`directives` slice rather than the same `.filter(|d| d.span.start < at)` view +the depth count uses. This is the safe direction (over-warning, never +under-protecting) and matches the docstring's own framing ("warn when the +region it joins is conditionally compiled *at all*"), so I'm treating it as a +plausibly intentional "the list uses conditional compilation, be aware" +heads-up rather than a bug — but it can read as mildly misleading to a user +staring at a warning that doesn't apply to their new port. Not asking for a +fix; noting in case a future pass wants to tighten the warning to only the +directives actually before `at`. + +**Verdict: fixed.** The guard is genuinely nesting- and position-aware, not +a shallow "any directive present" check, and it correctly distinguishes +"inside an arm" (refuse), "directives exist but I'm not inside one" (warn, +proceed), and "can't tell" (refuse) exactly as the ruling specified — verified +across both insertion paths and against chained/nested directive shapes the +round-1 finding never tried. + +### Round-1 HIGH #2 (macro-invocation silence on removal) — mechanism +verified, holds under the skip/report boundary attack + +Re-attacked `preprocessor_warnings` (`ports.rs:1118-1139`) and the shared +`Scope::define_sites`/`Scope::macro_argument_sites` (`rename.rs:489-542`) +specifically at the boundary the brief named — "macro named exactly the port +invoked with no args vs. with args": + +- **A macro whose own name equals the port name, invoked bare (no + parens)** (`` `define rst 1`` ... `` `rst;``, removing port `rst`) — + **correctly skipped**, zero warnings. This is the right call: `` `rst`` + (backtick) is a macro invocation in a different namespace from the port + `rst` (no backtick); removing the port has no bearing on this macro at + all, so silence here is correct, not a gap. +- **A *different* macro whose body spells the port name, invoked bare + elsewhere** (`` `define GET_RST rst`` ... `` `GET_RST;``) — **correctly + reported**: `` "`rst` appears in the body of macro `GET_RST` ... vfmt does + not preprocess, so that body still names the removed port." `` Confirms + `define_sites` catches this via the `` `define`` table directly, independent + of how the macro is later invoked (bare or with parens) — a body-spelling + macro is reported regardless of call syntax, which is the harder half of + the boundary to get right. +- **Compound case, both mechanisms on the same macro at once**: a macro + named exactly like the port (`` `define RST(x) ...``, port also named + `RST`) invoked *with* an argument that itself spells the port name + (`` `RST(RST)``). The name-collision "skip" rule + (`site.defines_the_name.is_some()`) and the argument-content "report" rule + (`macro_argument_sites`) are independent scans over independent data + (the define table vs. macro-invocation tokens); confirmed the skip on the + first does **not** suppress the report from the second — the argument use + is still reported (`` "`RST` appears in the arguments of the macro + invocation `RST` at m.sv:6 ..." ``). This was the real risk in this design + (one shared function silently eating both), and it doesn't happen. + +**Verdict: fixed.** The skip/report boundary is exactly where the ruling +drew it — name-collision is noise, body- and argument-content are news — +and the two mechanisms compose correctly rather than one accidentally +shadowing the other. + +### Rename factoring — spot-checked, unchanged + +Ran `cargo test -p vlog_refactor --test rename` in isolation: all **48** +behavior tests pass, matching the Work log's "byte-for-byte unchanged" +claim. Independently (not reusing any of the dev's 48 fixtures), wrote two +manual probes against a macro-argument shape and a `` `define``-body shape +different from the ones already in `tests/rename.rs`, calling the public +`rename()` API directly: + +- `` `define BUMP(x) x = x + 1`` / `` `BUMP(a);``, renaming `a` → `b`: + warning text came back **exactly** `` "`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." `` + — byte-for-byte the template `rename.rs::macro_use_warnings` has always + produced. +- `` `define HOLDS_A a`` (no invocation at all, just the body), renaming + `a` → `b`: warning came back containing "appears in the body of macro + `HOLDS_A`" — the `define_sites`/`macro_warnings` template, also + unchanged. + +**Verdict: confirmed unchanged.** The factoring +(`Scope::define_sites`/`Scope::macro_argument_sites` shared with +`ports.rs::preprocessor_warnings`) moved *scanning* code without moving +*rename's* output, on both the dev's own fixtures and two independent ones. + +### `Shift::map` documentation + +Confirmed the doc comment (`lib.rs:108-116`) now states the invariant +explicitly — every span handed to `map` is either identical to an edit's +range or fully disjoint from all of them, a violating span's answer is +"arbitrary, not a location," and `check::print`'s `excluded` list is named +as the mechanism that keeps it true. This is exactly the "soft spot" round 1 +flagged (not a defect, just unstated); it's now stated. Nothing to +re-verify behaviorally here since the code itself didn't change, only the +comment — confirmed by re-reading the surrounding function body unchanged +except for the comment block. + +### Corpus + +Not re-run independently this round (no code path changed that the corpus +number would catch beyond what the crate-level regressions already pin more +precisely); the dev's claim (`add_port` over 860 files still `Ok((6, 18))` +in 0.36 s) is consistent with the gate run producing the same 1170 total and +no new corpus-test failures in the full `cargo test --workspace` run above. + +### Housekeeping + +All probes this round were added as standalone temporary test files +(`crates/vlog_refactor/tests/qa_probe2.rs`, 9 tests attacking the `` `ifdef `` +guard and the macro skip/report boundary; `qa_probe2_rename.rs`, 2 tests +spot-checking rename) — no existing source file was edited this round (round +1's technique of temporarily patching `check.rs`/`ports.rs`/`lib.rs` wasn't +needed since every round-2 attack was reachable through the public API). +Both files were run and then deleted; `git status --short` after cleanup +shows only the dev's original changes. + +### Summary (round 2) + +| Round-1 finding | Round-2 verdict | +|---|---| +| `add_port` inside an `` `ifdef `` arm (HIGH #1) | **Fixed** — verified against `else`/`elsif` chains, nested ifdefs, the non-ANSI body path, and a negative/unbalanced-depth malformed input; one non-blocking imprecision noted (trailing-directive warning text) | +| `remove_port` macro-invocation silence (HIGH #2) | **Fixed** — verified at the exact skip/report boundary the ruling drew, including a compound case where both mechanisms apply to the same macro at once | +| `Shift::map` implicit invariant | **Documented**, as asked; nothing behavioral to re-verify | +| Rename factoring left rename unchanged | **Confirmed** — 48 existing tests pass, plus 2 independent manual probes | +| Gates (fmt/clippy/test) | **Pass**, 1170 tests, 0 failures | +| New round-2 attacks (else/elsif/nested-ifdef/trailing-directive/non-ANSI-body/negative-depth/macro skip-report boundary/compound name-and-argument collision) | **Pass** — no new corruption, no false refusals, no panics; one cosmetic warning-precision note | + +**Overall verdict: ship.** Both HIGH findings are genuinely closed at the +mechanism level, not just at the level of the original reproduction: I +specifically tried to defeat the `` `ifdef`` guard's depth-counting with +nesting and chaining, and tried to make the macro skip-rule swallow a +report it shouldn't — both held. The guard is a *planning*-layer fix +exactly where round 1 said the gap was (verification checks 1–5 still +correctly have no opinion on conditional compilation, and don't need one now +that the planner itself refuses the unsafe case). Nothing else moved: +rename's 48 tests and 1085→1164→1170's monotonic, exactly-matching test +counts across all three QA passes are themselves evidence against scope +creep. The one imprecision found (over-broad trailing-directive warning +text) is cosmetic, safe-direction, and not blocking. + +## Review + +**2026-08-24 — lead.** Reviewed after QA round 2's ship verdict; gates run +independently (1170 tests, 0 failures, clippy silent). The splice verifier +plus per-feature shape check is the right division — the verifier stays +generic and un-widened, and the check that knows what a port list should say +lives with the feature. QA's two round-1 HIGHs (silent `ifdef`-arm +placement, macro-argument silence) closed per ruling: the nesting guard is +genuinely position- and depth-aware under attack, covers both insertion +paths, and the dev's widening of the ruling (refuse on negative depth too) +is correct. The factored rename scans left M2's output byte-for-byte +unchanged. Accepted; M3 checked off in the umbrella plan and TODO.md §8. +Noted, not blocking: QA's cosmetic over-warning on directives after the +insertion point, and CRLF insertions writing `\n` — both recorded in the +work log with reasoning. diff --git a/docs/features/refactor/README.md b/docs/features/refactor/README.md index 2d6698c..7cedfd5 100644 --- a/docs/features/refactor/README.md +++ b/docs/features/refactor/README.md @@ -70,14 +70,14 @@ the work is reviewed**. Owner-priority items first (2026-08-24). by default; deferred until asked for ### Module signature (change signature) -- [ ] **Add a port** to a module: declaration + every instantiation gains a +- [x] **Add a port** to a module: declaration + every instantiation gains a named connection (`.p(p)` when a same-named signal is in scope at the instantiation, else `.p(/* connect */)`), non-ANSI decls updated too → `docs/features/refactor-ports/README.md` (M3) -- [ ] **Remove a port**: dropped from the declaration and from every +- [x] **Remove a port**: dropped from the declaration and from every instantiation (named connection deleted; ordered connection turned into an explicit empty positional; refuse if the connected expression has visible side effects to preserve) → M3 -- [ ] **Propagate ports**: diff a module's declaration against each +- [x] **Propagate ports**: diff a module's declaration against each instantiation and add the missing named connections — the code action form that needs no free-form input → M3 - [ ] Reorder ports / rename-a-port-as-signature-change (rename already @@ -178,7 +178,7 @@ commit — in order: move, change signature, restructure, organize imports, SOA/DOA, history) - [x] M1 filelist — done, QA clean, reviewed - [x] M2 refactor-rename — done, QA clean after one rework round, reviewed -- [ ] M3 refactor-ports +- [x] M3 refactor-ports — done, QA clean after one rework round, reviewed - [ ] M4 refactor-instantiate - [ ] Backlog triage after M4