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 <[email protected]>
This commit is contained in:
1 parent
33f58196e3
commit
e338524f63
14 files changed
+5006
-84
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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<String> {
|
||||
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<CodeActionOrCommand> {
|
||||
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>), 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::<Position>(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<u32, String> {
|
||||
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<u32, String> {
|
||||
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<WorkspaceEdit, String> {
|
||||
let mut changes: HashMap<Uri, Vec<TextEdit>> = 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]);
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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<TextEdit>)],
|
||||
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<Print> = 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<PathBuf, Vec<TextRange>>,
|
||||
after: HashMap<PathBuf, Vec<TextRange>>,
|
||||
}
|
||||
|
||||
impl Excluded {
|
||||
fn new(scope: &Scope, edits: &[(usize, Vec<TextEdit>)]) -> 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<Vec<(TextRange, Piece)>> {
|
||||
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<Piece> = Vec::new();
|
||||
let mut next = 0usize;
|
||||
let mut written: Vec<Vec<(TextRange, Piece)>> = 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<Piece> = 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<TextEdit> {
|
||||
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
|
||||
|
||||
@@ -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.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -181,7 +181,7 @@ impl<'a> Scope<'a> {
|
||||
self.file_ids.get(i).copied().flatten()
|
||||
}
|
||||
|
||||
fn index_of(&self, path: &Path) -> Option<usize> {
|
||||
pub(crate) fn index_of(&self, path: &Path) -> Option<usize> {
|
||||
self.sources.iter().position(|(p, _)| *p == path)
|
||||
}
|
||||
|
||||
@@ -443,28 +443,20 @@ impl<'a> Scope<'a> {
|
||||
fn macro_warnings(&self, name: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
for i in 0..self.len() {
|
||||
let (Some(text), Some(file)) = (self.text(i), self.file_id(i)) else { continue };
|
||||
if !text.contains(name) {
|
||||
continue;
|
||||
}
|
||||
let Some(defines) = self.index.defines(file) else { continue };
|
||||
let lines = LineIndex::new(text);
|
||||
let where_ = display(self.path(i).unwrap_or(Path::new("?")));
|
||||
for define in defines.entries() {
|
||||
let line = lines.line_col(define.span.start).0;
|
||||
if define.name == name {
|
||||
let what = match define.kind {
|
||||
DefineKind::Define => "defined",
|
||||
DefineKind::Undef => "undefined",
|
||||
};
|
||||
out.push(format!(
|
||||
"`{name}` is also a macro {what} at {where_}:{line}; macro names and macro uses are never renamed."
|
||||
));
|
||||
} else if contains_word(&define.body, name) {
|
||||
out.push(format!(
|
||||
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<String> {
|
||||
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<DefineSite> {
|
||||
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<ArgumentSite> {
|
||||
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<DefineKind>,
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
|
||||
@@ -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<Vec<PathBuf>> {
|
||||
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());
|
||||
}
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
|
||||
|
||||
Reference in new issue
Block a user