Files
lucisv/crates/vlog_refactor/src/ports/remove.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

363 lines
15 KiB
Rust

//! Removing a port: the port under the cursor (header or non-ANSI body
//! declaration), the refusal when the module's own body still uses it, the
//! header and body deletions, the disconnection at every instantiation in
//! scope, and the news about macro text the preprocessor owns.
use std::path::Path;
use vlog_parser::ast::{Connections, ItemKind, ListElem, Module, PortList, SourceFile};
use vlog_parser::span::TextRange;
use vlog_parser::{parse_source_tolerant, LineIndex};
use vlog_semantic::SymbolKind;
use crate::rename::Scope;
use crate::TextEdit;
use super::add::{element_spans, not_indexed};
use super::find::{
collect_instantiations, declared_ports, find_module, locate_module, module_at, not_in_scope,
ModuleSite,
};
use super::list::{elem_spans, remove_element, whole_line};
use super::{shape, ModuleRef, Plan};
/// The module and port name a removal request points at. The cursor may sit on
/// the header port or, for a non-ANSI module, on its body declaration.
pub(super) fn locate_port(
scope: &mut Scope,
file: &Path,
offset: u32,
) -> Result<(ModuleSite, String), String> {
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
let (tree, _) = parse_source_tolerant(text);
let (module_name, name) = port_at(&tree, offset)?;
let site = locate_module(scope, ModuleRef::Name(&module_name))?;
if site.file != i {
return Err(ambiguous(&module_name));
}
Ok((site, name))
}
/// The module and port name the cursor sits on, read off one file's parse —
/// [`locate_port`] without the workspace half.
///
/// The cursor may be on the header port or, for a non-ANSI module, on its body
/// declaration. Split out so the code-action *offer* can ask the same question
/// of the buffer's own parse (take 5 §P1c, `ports::offer`).
pub(super) fn port_at(tree: &SourceFile, offset: u32) -> Result<(String, String), String> {
let mut module_name = None;
module_at(&tree.items, offset, &mut module_name);
let Some(module_name) = module_name else {
return Err(NOT_A_PORT.to_string());
};
let Some((module, _)) = find_module(tree, &module_name) else {
return Err(NOT_A_PORT.to_string());
};
let ports = declared_ports(module);
let mut name = ports.iter().find(|p| p.span.contains(offset)).map(|p| p.name.clone());
if name.is_none() {
// The cursor may be on the non-ANSI body declaration instead.
for item in &module.items {
let ItemKind::PortDecl(decl) = &item.kind else { continue };
for declarator in &decl.declarators {
if declarator.span.contains(offset) || declarator.name_span.contains(offset) {
name = Some(declarator.name.clone());
}
}
}
// ...and it must still be a port of this module.
if let Some(found) = &name {
if !ports.iter().any(|p| &p.name == found) {
return Err(NOT_A_PORT.to_string());
}
}
}
let Some(name) = name else { return Err(NOT_A_PORT.to_string()) };
Ok((module_name, name))
}
/// The sentence a module the in-scope files declare twice earns.
pub(super) fn ambiguous(module: &str) -> String {
format!(
"`{module}` is declared in more than one indexed file; lucisv will not guess which module's ports these are."
)
}
const NOT_A_PORT: &str = "there is no module port at this position.";
pub(super) fn plan_remove(
scope: &mut Scope,
site: &ModuleSite,
port: &str,
) -> Result<Plan, String> {
let Some(text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) };
let Some(path) = scope.path(site.file) else { return Err(not_indexed(&site.name)) };
let (tree, _) = parse_source_tolerant(text);
let Some((module, _)) = find_module(&tree, &site.name) else {
return Err(not_indexed(&site.name));
};
let ports = declared_ports(module);
let Some(index) = ports.iter().position(|p| p.name == port) else {
return Err(format!("`{}` has no port named `{port}`.", site.name));
};
let header: Vec<TextEdit> = header_removal(text, module, &ports, index, port)?;
// A port still used by the module's own body is a refusal, not a warning:
// deleting it would leave the body naming something that no longer exists.
let used = match scope.analysis(site.file) {
Some(analysis) => body_uses_in(text, &analysis.semantics, module, port, &header),
None => Vec::new(),
};
if !used.is_empty() {
return Err(format!(
"`{port}` is still used inside `{}` at {}:{}; remove those uses first.",
site.name,
scope.name_of(path),
used.join(", ")
));
}
let mut plan = Plan::default();
plan.add(site.file, header);
for i in 0..scope.len() {
let (edits, sites) = disconnection_edits(scope, i, site, port, &mut plan.warnings)?;
plan.sites += sites;
plan.add(i, edits);
}
// What the preprocessor owns, lucisv cannot edit — and after a removal, what
// it owns may name a port that no longer exists.
let mut watched: Vec<usize> = plan.edits.iter().map(|(i, _)| *i).collect();
if !watched.contains(&site.file) {
watched.push(site.file);
}
watched.sort_unstable();
for &i in &watched {
plan.warnings.extend(preprocessor_warnings(scope, i, port));
}
let mut names: Vec<String> = ports.iter().map(|p| p.name.clone()).collect();
names.remove(index);
for i in plan.edits.iter().map(|(i, _)| *i).collect::<Vec<_>>() {
let Some(text) = scope.text(i) else { continue };
let mut expected = shape(text, &site.name);
if i == site.file {
expected.ports = Some(names.clone());
}
for (_, conns) in &mut expected.instances {
conns.retain(|name| name != port);
}
plan.expected.push((i, expected));
}
Ok(plan)
}
/// Every place in one file where the removed port's name lives in text the
/// preprocessor owns: a macro invocation's arguments, or a `` `define`` body.
///
/// lucisv does not expand macros — a macro invocation is one opaque token, so
/// `` `BUMP(rst) `` records no reference for `body_uses` to find and no span
/// for an edit to land on. Silence would be the worst answer: the file still
/// parses and still *looks* right, and only a real preprocessor discovers that
/// the expansion names a port that no longer exists. The same scan M2 added to
/// rename after QA found the same hole there (`Scope::macro_argument_sites`,
/// `Scope::define_sites`) answers it here, with news of its own.
fn preprocessor_warnings(scope: &Scope, file: usize, port: &str) -> Vec<String> {
let where_ = scope.name_at(file);
let mut out = Vec::new();
for site in scope.macro_argument_sites(file, port) {
out.push(format!(
"`{port}` appears in the arguments of the macro invocation `{}` at {where_}:{}; a macro invocation is one opaque token to lucisv, so nothing was removed there and that expansion now names a port `{port}`'s module no longer has.",
site.macro_name, site.line
));
}
for site in scope.define_sites(file, port) {
// A macro *named* like the port is not news for a removal; a macro
// whose body spells it is.
if site.defines_the_name.is_some() {
continue;
}
out.push(format!(
"`{port}` appears in the body of macro `{}` at {where_}:{}; lucisv does not preprocess, so that body still names the removed port.",
site.macro_name, site.line
));
}
out
}
/// The header and body deletions the removal makes in the module's own file.
///
/// Split out of [`plan_remove`] so the code-action offer can make exactly the
/// same two decisions — and earn exactly the same refusals — without a
/// workspace (take 5 §P1c).
pub(super) fn header_removal(
text: &str,
module: &Module,
ports: &[super::find::DeclaredPort],
index: usize,
port: &str,
) -> Result<Vec<TextEdit>, String> {
let mut header = remove_element(text, &element_spans(ports), index)?;
if matches!(module.ports, PortList::NonAnsi(_)) {
header.append(&mut non_ansi_declaration_removal(text, module, port)?);
}
Ok(header)
}
/// The lines of the module's body that still name the port, ignoring the
/// declarations the removal is itself deleting.
///
/// `semantics` must be the analysis of `text` — [`Scope::analysis`]'s, or the
/// open buffer's own, which is the same thing computed once instead of twice.
pub(super) fn body_uses_in(
text: &str,
semantics: &vlog_semantic::Semantics,
module: &Module,
port: &str,
removed: &[TextEdit],
) -> Vec<String> {
let lines = LineIndex::new(text);
let Some(symbol) = semantics.symbols().iter().position(|s| {
s.name == port
&& s.kind == SymbolKind::Port
&& module_span(module).contains(s.name_span.start)
}) else {
return Vec::new();
};
let id = vlog_semantic::SymbolId(symbol as u32);
let mut out: Vec<String> = Vec::new();
for reference in semantics.references_of(id) {
let span = reference.name_span;
if removed.iter().any(|e| e.range.start <= span.start && span.end <= e.range.end) {
continue;
}
let line = lines.line_col(span.start).0.to_string();
if !out.contains(&line) {
out.push(line);
}
}
out
}
/// The bytes a module covers, taken from its name and its last item — the
/// `Module` node carries no span of its own.
fn module_span(module: &Module) -> TextRange {
let end = module.items.last().map_or(module.name_span.end, |item| item.span.end);
TextRange::new(module.name_span.start, end.max(module.name_span.end))
}
/// Delete the non-ANSI body declaration of a port: the whole item when it
/// declares only this port, otherwise just its declarator.
fn non_ansi_declaration_removal(
text: &str,
module: &Module,
port: &str,
) -> Result<Vec<TextEdit>, String> {
for item in &module.items {
let ItemKind::PortDecl(decl) = &item.kind else { continue };
let Some(index) = decl.declarators.iter().position(|d| d.name == port) else { continue };
if decl.declarators.len() == 1 {
return Ok(vec![TextEdit {
range: whole_line(text, item.span),
new_text: String::new(),
}]);
}
let spans: Vec<TextRange> = decl.declarators.iter().map(|d| d.span).collect();
return remove_element(text, &spans, index);
}
Err(format!("`{port}` has no declaration in the body of `{}`.", module.name))
}
/// The edits that take the port's connection out of one file's instantiations.
fn disconnection_edits(
scope: &mut Scope,
file: usize,
site: &ModuleSite,
port: &str,
warnings: &mut Vec<String>,
) -> Result<(Vec<TextEdit>, usize), String> {
let (Some(text), Some(path)) = (scope.text(file), scope.path(file)) else {
return Ok((Vec::new(), 0));
};
if !text.contains(&site.name) {
return Ok((Vec::new(), 0));
}
let (tree, _) = parse_source_tolerant(text);
disconnections_in(text, &scope.name_of(path), &tree, &site.name, port, warnings)
}
/// [`disconnection_edits`] over a parse the caller already has, so the offer
/// can earn the by-position refusal and count the sites it would rewrite
/// without building a workspace (take 5 §P1c).
pub(super) fn disconnections_in(
text: &str,
shown: &str,
tree: &SourceFile,
module: &str,
port: &str,
warnings: &mut Vec<String>,
) -> Result<(Vec<TextEdit>, usize), String> {
let mut instantiations = Vec::new();
collect_instantiations(&tree.items, &mut instantiations);
let lines = LineIndex::new(text);
let mut edits = Vec::new();
let mut sites = 0usize;
for instantiation in instantiations.iter().filter(|i| i.module == module) {
for instance in &instantiation.instances {
match &instance.conns {
Connections::Ordered(conns) if conns.is_empty() => {}
Connections::Ordered(_) => {
return Err(format!(
"`{}` in {} connects `{}`'s ports by position; dropping one would silently re-bind the rest, so lucisv made no edits — give it named connections first.",
instance.name,
shown,
module
))
}
Connections::Named(conns) => {
// `.*` binds the port implicitly, so there is nothing to
// delete — and the signal it was binding may now have no
// reader at all, which is worth saying.
// An error element names no port either way.
let named = || conns.iter().filter_map(ListElem::ok);
if named().any(|c| c.name == "*") && named().all(|c| c.name != port) {
warnings.push(format!(
"`{}` at {}:{} connects with `.*`, so nothing was removed there; the signal it bound `{port}` to may now be unused.",
instance.name,
shown,
lines.line_col(instance.name_span.start).0
));
continue;
}
let Some(index) =
conns.iter().position(|c| c.ok().is_some_and(|c| c.name == port))
else {
continue;
};
// The connected expression goes with the connection. A
// plain `.p(p)` loses nothing; anything else is said out
// loud, because it is the user's code being deleted.
if let Some(expr) = conns.get(index).and_then(ListElem::ok) {
let written = text.get(expr.span.as_range()).unwrap_or("");
let trivial = written == format!(".{port}({port})")
|| written == format!(".{port}()")
|| written == format!(".{port}");
if !trivial {
warnings.push(format!(
"`{written}` at {}:{} was deleted with the port.",
shown,
lines.line_col(expr.span.start).0
));
}
}
let spans: Vec<TextRange> = elem_spans(conns, |c| c.span);
sites += 1;
edits.append(&mut remove_element(text, &spans, index)?);
}
}
}
}
Ok((edits, sites))
}