Files
lucisv/crates/vlog_refactor/src/ports/mod.rs
T
lucioandClaude Opus 5.5 7794d3938b TODO §65.1: rename and references through a generate block label; rename warnings and mentions scoped to the renamed declaration
A path segment naming a block (bare, indexed, nested, cross-file) is now a
reference to its label: vlog_semantic declares a `for` block's label in the
enclosing scope, makes `generate … endgenerate` no scope, gives a block a
member scope, walks an index in a path, and files blocks on a module's
hierarchical surface under `module.label` (FACTS_FORMAT 21). The LSP, CLI
and MCP rename/references get it through the engine; lucisv-mcp's `block`
refusal is lifted. No verifier normalization (attacks in
check/qa_block_paths.rs, qa_block_attacks.rs).

Reworks after QA: unresolved path segments warned in every file of the set;
sibling-arm members warned; a label beside a net is a duplicate-declaration;
function-local block keys never collide; file names path-qualified when base
names collide; rename warnings and lucisv-mcp mentions scoped to the
declaration's home set (rename/home.rs, scoped.rs), falling back to unscoped
on any doubt. TODO §65.4 and §65.6 filed.

docs/features/generate-label-rename. Workspace lib/bins/tests: 79 suites,
5 064 passed, 0 failed, 51 ignored (guard exit 0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:01:23 -07:00

513 lines
20 KiB
Rust

//! Module port signature changes: add a port, remove a port, propagate the
//! ports a single instantiation is missing.
//!
//! Read top-to-bottom, each one is the same four steps: find the module (or
//! the instantiation) the request names, work out the *plan* — one edit per
//! place the signature is written down, plus a sentence for every place lucisv
//! deliberately left alone — verify the whole plan in memory, and hand it back
//! or refuse it whole. A refusal is a sentence for the user, never a partial
//! edit.
//!
//! Unlike a rename, these refactorings write and delete text, so they cannot
//! use the rename verifier's "the token stream may not change shape" contract.
//! They use [`check::verify_splice`] instead, plus a **shape** check of their
//! own (`confirm`) that reads the edited text back and asserts the port list
//! and the connection lists now say exactly what the plan promised. See
//! `docs/features/refactor-ports/README.md`.
//!
//! This file is the surface and the spine: the entry points, and the [`Plan`]
//! every one of them fills, verifies (`finish`) and reads back (`confirm`).
//! `find` locates what a request points at, `add`, `remove` and `propagate`
//! are the three planners, and `list` is the comma-list editing and
//! parenthesis finding they share.
mod add;
mod ansi;
mod expand;
mod find;
mod list;
mod merge;
mod offer;
mod propagate;
mod remove;
pub(crate) use find::{find_module, visible_in};
pub use offer::{port_offers, port_offers_in, PortOffer, PortOfferKind};
use std::path::{Path, PathBuf};
use vlog_parser::ast::{Connections, ItemKind, Module, PortList, SourceFile};
use vlog_parser::parse_source_tolerant;
use crate::rename::Scope;
use crate::{check, RefactorEdit, TextEdit};
use add::{parse_port_decl, plan_add};
use ansi::plan_convert;
use expand::plan_expand;
use find::{collect_instantiations, declared_ports, locate_module, module_at};
use propagate::plan_propagate;
use remove::{locate_port, plan_remove};
/// Which module a port refactoring acts on.
#[derive(Debug, Clone, Copy)]
pub enum ModuleRef<'a> {
/// The module declared under this name. It must be declared exactly once
/// in the in-scope files: lucisv does not guess between two of them.
Name(&'a str),
/// The module whose declaration covers this byte offset.
At {
/// One of the in-scope files.
file: &'a Path,
/// A byte offset inside the module's declaration.
offset: u32,
},
}
/// One refactoring an editor can offer at a position, computed in full.
///
/// The title is written here rather than in the server so that Vim, VS Code
/// and any future CLI say the same thing.
#[derive(Debug, Clone)]
pub struct PortAction {
/// What the lightbulb says.
pub title: String,
/// The edit it applies, already verified.
pub edit: RefactorEdit,
}
/// Add one ANSI port declaration to a module, and a connection for it to every
/// instantiation of that module in the in-scope files.
///
/// `decl` is the one piece of free-form input any of these refactorings takes
/// (`input logic [7:0] cfg`), so it is parsed as a port declaration before
/// anything else happens, and the edited files are re-parsed afterwards.
pub fn add_port(
files: &[(PathBuf, String)],
module: ModuleRef<'_>,
decl: &str,
) -> Result<RefactorEdit, String> {
let port = parse_port_decl(decl)?;
let mut scope = Scope::build(files);
let site = locate_module(&mut scope, module)?;
let plan = plan_add(&mut scope, &site, &port)?;
let what = format!("adding port `{}` to `{}`", port.name, site.name);
Ok(finish(&mut scope, plan, &site.name, &what)?.0)
}
/// Remove the port at `offset` from its module, and its named connection from
/// every instantiation in the in-scope files.
pub fn remove_port(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
) -> Result<RefactorEdit, String> {
Ok(removal(files, file, offset)?.0)
}
/// The removal, the port's name, and how many instantiations it rewrites.
fn removal(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
) -> Result<(RefactorEdit, String, usize), String> {
let mut scope = Scope::build(files);
let (site, port) = locate_port(&mut scope, file, offset)?;
let plan = plan_remove(&mut scope, &site, &port)?;
let what = format!("removing port `{port}` from `{}`", site.name);
let (edit, sites) = finish(&mut scope, plan, &site.name, &what)?;
Ok((edit, port, sites))
}
/// Add the named connections one instantiation is missing, from the
/// instantiated module's own declaration.
pub fn propagate_ports(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
) -> Result<RefactorEdit, String> {
let mut scope = Scope::build(files);
let (site, plan) = plan_propagate(&mut scope, file, offset)?;
let what = format!("connecting the missing ports of `{}`", site.name);
Ok(finish(&mut scope, plan, &site.name, &what)?.0)
}
/// Write out the `.*` at `offset`: every port the instantiation does not
/// connect explicitly, bound to the same-named signal in the instantiating
/// scope (IEEE 1800 §23.3.2.4), in the module's declaration order.
///
/// A port with no such signal is one the wildcard never bound — a compiler
/// would have rejected the instantiation — so it is written `.name()` and
/// named in a warning. Nothing outside the cursor's own file is edited.
pub fn expand_wildcard(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
) -> Result<RefactorEdit, String> {
Ok(expansion(files, file, offset)?.0)
}
/// The expansion and how many connections it writes — what a code action's
/// title promises.
fn expansion(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
) -> Result<(RefactorEdit, usize), String> {
let mut scope = Scope::build(files);
let expansion = plan_expand(&mut scope, file, offset)?;
let what = format!("expanding the `.*` of `{}`", expansion.instance);
let edit = finish(&mut scope, expansion.plan, &expansion.site.name, &what)?.0;
Ok((edit, expansion.count))
}
/// Rewrite a Verilog-2001 header as an ANSI one: every port the header names
/// gains the direction, type, signing and dimensions its body declarations
/// gave it (IEEE 1800 §23.2.2.2), and those declarations go.
///
/// The header's own layout, commas and comments are untouched — what an ANSI
/// port adds is inserted around each name — and a comment on an absorbed
/// declaration moves onto the port it described. Nothing outside the module's
/// own file is edited.
pub fn convert_to_ansi(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
) -> Result<RefactorEdit, String> {
Ok(conversion(files, file, offset)?.0)
}
/// The conversion and how many ports it declares — what a code action's title
/// promises.
fn conversion(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
) -> Result<(RefactorEdit, usize), String> {
let mut scope = Scope::build(files);
let conversion = plan_convert(&mut scope, file, offset)?;
let what = format!("converting `{}`'s ports to ANSI", conversion.site.name);
let edit = finish(&mut scope, conversion.plan, &conversion.site.name, &what)?.0;
Ok((edit, conversion.count))
}
/// Every port refactoring available at a position, each with its edit already
/// computed and verified — which is what lets a code action carry its own
/// `WorkspaceEdit` instead of a command the editor has to resolve.
///
/// Nothing is offered for a position where the refactoring would be refused:
/// a lightbulb that only ever explains itself is worse than no lightbulb.
pub fn port_actions(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Vec<PortAction> {
let mut out = Vec::new();
let here = files.iter().find(|(path, _)| path == file).map(|(_, text)| text.as_str());
if !here.is_some_and(|text| may_have_port_action(text, offset)) {
return out;
}
if let Ok((edit, port, sites)) = removal(files, file, offset) {
out.push(PortAction {
title: format!("lucisv: remove port `{port}` ({})", sites_phrase(sites)),
edit,
});
}
if let Ok(edit) = propagate_ports(files, file, offset) {
let missing = edit.edit_count();
out.push(PortAction {
title: format!(
"lucisv: connect {missing} missing port{}",
if missing == 1 { "" } else { "s" }
),
edit,
});
}
if let Ok((edit, count)) = expansion(files, file, offset) {
out.push(PortAction {
title: format!(
"lucisv: expand .* ({count} connection{})",
if count == 1 { "" } else { "s" }
),
edit,
});
}
if let Ok((edit, count)) = conversion(files, file, offset) {
out.push(PortAction {
title: format!(
"lucisv: convert ports to ANSI ({count} port{})",
if count == 1 { "" } else { "s" }
),
edit,
});
}
out
}
/// Whether a position could carry a port refactoring at all, judged from one
/// file's own text: is it inside a module's port element, inside a non-ANSI
/// port declaration, or inside an instantiation?
///
/// This is a **cheap** question — one parse of one file, no workspace, no I/O —
/// and it exists because a `textDocument/codeAction` request arrives on every
/// cursor move. Materializing the in-scope files and building an index for a
/// cursor sitting in the middle of an `always` block would stall the editor for
/// a fifth of a second on a large workspace; this answers `false` in
/// microseconds. It never says `false` where a refactoring would have
/// succeeded: every one of the three starts by locating exactly one of these
/// three constructs.
///
/// Exactly [`port_action_modules`] asked for emptiness — one walk, two
/// readers, so the gate and the fan-out cannot come to disagree about which
/// positions carry an action.
pub fn may_have_port_action(text: &str, offset: u32) -> bool {
!port_action_modules(text, offset).is_empty()
}
/// Every module name a port refactoring at this position could act on: the
/// module an instantiation under the cursor names, or the module whose port
/// the cursor sits on.
///
/// [`may_have_port_action`]'s own walk, saying *which* module it found rather
/// than only that it found one — which is what lets a server hand
/// [`port_actions`] the handful of files that module fans out to instead of
/// the whole workspace. Empty for exactly the positions the gate refuses.
pub fn port_action_modules(text: &str, offset: u32) -> Vec<String> {
let (tree, _) = parse_source_tolerant(text);
port_action_modules_in(&tree, offset)
}
/// [`port_action_modules`] over a parse the caller already has.
///
/// The same walk and the same answer; only the parse moves. A server holds
/// the tolerant parse of the buffer it is answering about
/// (`lucisv_server::state::Document`), so asking it to parse the same bytes
/// again is a whole-file parse per cursor move — which is what take 5 §P1b
/// removes (`docs/features/perf5-p1/README.md`).
///
/// `tree` must be the tolerant parse of the same text the offsets index. This
/// selector reads **no** parse diagnostics, exactly as the text form does not:
/// a port refactoring is offered on a buffer that does not fully parse, and
/// the engine refuses later if it must.
pub fn port_action_modules_in(tree: &SourceFile, offset: u32) -> Vec<String> {
let mut instantiations = Vec::new();
collect_instantiations(&tree.items, &mut instantiations);
let named: Vec<String> = instantiations
.iter()
.filter(|instantiation| {
instantiation.module_span.contains(offset)
|| instantiation.instances.iter().any(|instance| instance.span.contains(offset))
})
.map(|instantiation| instantiation.module.clone())
.collect();
if !named.is_empty() {
return named;
}
let mut module = None;
module_at(&tree.items, offset, &mut module);
let Some((name, (module, _))) =
module.and_then(|name| Some((name.clone(), find_module(tree, &name)?)))
else {
return Vec::new();
};
if declared_ports(module).iter().any(|port| port.span.contains(offset)) {
return vec![name];
}
let on_body_declaration = module.items.iter().any(|item| match &item.kind {
ItemKind::PortDecl(decl) => decl.declarators.iter().any(|d| d.span.contains(offset)),
_ => false,
});
if on_body_declaration || in_non_ansi_header(module, offset) {
return vec![name];
}
Vec::new()
}
/// Whether the cursor is anywhere in the header of a module written the
/// Verilog-2001 way — the one position the ANSI conversion is offered at that
/// no other port refactoring cares about.
///
/// The header is everything from the module's keyword to the first item it
/// declares (that item's own leading comments included, since a cursor there
/// is still above the body). An ANSI module answers `false`: nothing would be
/// offered, and the gate exists to keep a cursor that carries no action from
/// materializing a workspace.
fn in_non_ansi_header(module: &Module, offset: u32) -> bool {
if !matches!(module.ports, PortList::NonAnsi(_)) {
return false;
}
let body = module.items.first().map(|item| {
item.meta.leading.first().map_or(item.span.start, |comment| comment.span.start)
});
offset < body.unwrap_or(u32::MAX)
}
/// The module whose declaration covers this offset — what
/// `ModuleRef::At { file, offset }` will resolve to.
///
/// The fan-out question for the *command* path, which takes a position
/// anywhere in a module rather than on one of its ports: `lucisv.addPort` with
/// a `Position` names the module the cursor is inside, and a server working
/// out which files that refactoring needs has to name it the same way
/// `locate_module` will.
pub fn enclosing_module(text: &str, offset: u32) -> Option<String> {
let (tree, _) = parse_source_tolerant(text);
let mut module = None;
module_at(&tree.items, offset, &mut module);
module
}
/// "updates 3 instantiations" / "updates 1 instantiation" / "no instantiation
/// in scope".
///
/// Public because a server may have to write the same sentence with a count of
/// its own: an offer that has not read the fan-out takes the number from its
/// workspace index instead of from the plan, and the two must not come to be
/// worded differently (`docs/features/lazy-code-action/README.md`).
pub fn sites_phrase(sites: usize) -> String {
match sites {
0 => "no instantiation in scope".to_string(),
1 => "updates 1 instantiation".to_string(),
n => format!("updates {n} instantiations"),
}
}
/// Whether a title's parenthesized tail is one [`sites_phrase`] wrote.
///
/// A server that recounts an offered title's instantiations from its index
/// must not recount a title counting something else: `lucisv: expand .* (3
/// connections)` says how many connections one `.*` becomes, which no
/// instantiation census can answer. One spelling of the phrase, and one
/// reader of it, both here.
pub fn is_sites_phrase(phrase: &str) -> bool {
phrase == sites_phrase(0) || phrase.starts_with("updates ")
}
/// Everything a port refactoring wants done, before it is verified.
#[derive(Default)]
struct Plan {
/// Source index → the edits for that file, sorted.
edits: Vec<(usize, Vec<TextEdit>)>,
warnings: Vec<String>,
/// What the edited text must say afterwards, per file.
expected: Vec<(usize, Shape)>,
/// How many instantiations the plan rewrites — what a code action's title
/// promises the user.
sites: usize,
}
impl Plan {
/// Add one file's edits to the plan.
fn add(&mut self, file: usize, mut edits: Vec<TextEdit>) {
if edits.is_empty() {
return;
}
if let Some((_, existing)) = self.edits.iter_mut().find(|(i, _)| *i == file) {
existing.append(&mut edits);
} else {
self.edits.push((file, edits));
}
}
/// Sort every file's edits and refuse two that overlap — a caller cannot
/// apply those, so the plan is abandoned before it is verified.
fn settle(&mut self) -> Result<(), String> {
for (_, edits) in &mut self.edits {
edits.sort_by_key(|e| (e.range.start, e.range.end));
for pair in edits.windows(2) {
let (a, b) = (&pair[0], &pair[1]);
if b.range.start < a.range.end {
return Err(OVERLAP.to_string());
}
}
}
self.edits.sort_by_key(|(i, _)| *i);
Ok(())
}
}
const OVERLAP: &str = "two of the edits lucisv computed overlap, so it made none.";
/// Verify a plan and turn it into the refactoring's answer.
fn finish(
scope: &mut Scope,
mut plan: Plan,
module: &str,
what: &str,
) -> Result<(RefactorEdit, usize), String> {
plan.settle()?;
if plan.edits.is_empty() {
return Err(format!("lucisv found nothing to change for {what}."));
}
check::verify_splice(scope, &plan.edits, module, what)?;
confirm(scope, &plan, module, what)?;
let mut edits: Vec<(PathBuf, Vec<TextEdit>)> = Vec::new();
for (i, file_edits) in plan.edits {
let Some(path) = scope.path(i) else {
return Err(format!("lucisv could not name one of the files it edited for {what}."));
};
edits.push((path.to_path_buf(), file_edits));
}
edits.sort_by(|a, b| a.0.cmp(&b.0));
Ok((RefactorEdit { edits, warnings: plan.warnings, created: Vec::new() }, plan.sites))
}
/// What one file says about a module's signature: the module's own declared
/// port names, and every instantiation's connection names in order (`""` for a
/// positional connection, `"*"` for the wildcard).
///
/// This is the "did it do what it said" check. `verify_splice` proves the edit
/// is lexically and semantically honest; nothing in it proves the new text
/// landed in the *port list* rather than in the parameter list, so the plan
/// also states the shape it expects and the shape is read back.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct Shape {
ports: Option<Vec<String>>,
instances: Vec<(String, Vec<String>)>,
}
fn shape(text: &str, module: &str) -> Shape {
let (tree, _) = parse_source_tolerant(text);
let mut out = Shape::default();
if let Some((declaration, _)) = find_module(&tree, module) {
out.ports = Some(declared_ports(declaration).into_iter().map(|p| p.name).collect());
}
let mut instantiations = Vec::new();
collect_instantiations(&tree.items, &mut instantiations);
for instantiation in instantiations {
if instantiation.module != module {
continue;
}
for instance in &instantiation.instances {
let names = match &instance.conns {
// An error element keeps its place in the fingerprint — it is
// an element of the list — but it names nothing, exactly as a
// positional connection names nothing.
Connections::Named(conns) => conns
.iter()
.map(|c| c.ok().map(|c| c.name.clone()).unwrap_or_default())
.collect(),
Connections::Ordered(conns) => conns.iter().map(|_| String::new()).collect(),
};
out.instances.push((instance.name.clone(), names));
}
}
out
}
/// Read the edited text back and require it to say what the plan promised.
fn confirm(scope: &Scope, plan: &Plan, module: &str, what: &str) -> Result<(), String> {
for (i, expected) in &plan.expected {
let (Some(text), Some(path)) = (scope.text(*i), scope.path(*i)) else {
return Err(format!("lucisv could not re-read a file it edited for {what}."));
};
let edits = plan.edits.iter().find(|(j, _)| j == i).map(|(_, e)| e.as_slice());
let edited = crate::apply(text, edits.unwrap_or(&[]));
let actual = shape(&edited, module);
if &actual != expected {
return Err(format!(
"{what} would not leave {} with the signature lucisv intended; no edits were made.",
scope.name_of(path)
));
}
}
Ok(())
}