Files
lucisv/crates/vlog_refactor/src/check/implicit.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

805 lines
34 KiB
Rust

//! What the rename verifier learns about implicit connections (`.name` and
//! `.*`), and why it had to learn it.
//!
//! The rename contract was "the token stream may not change shape", and the
//! resolution print compares references and declarations — and neither sees
//! an implicit binding, because nothing is written for one: `.*` records no
//! reference, and `.d` records only the port half. That is exactly how a
//! rename used to cut `.*`/`.d` bindings and verify clean (M3 QA finding 1).
//! So the fix is in two halves, and this is the second:
//!
//! 1. **The edits may insert, but only connection text.** A rename that
//! rewrites implicit connections writes `(net)` after a shorthand or
//! `.port(net)` into a list — never anything else. [`insertions_match`]
//! holds such a file to the splice contract (the pieces, comments and
//! attributes never dropped, no new parse error) *plus* a shape rule: every
//! replacement is the old name becoming the new one, and every insertion
//! is one of four connection templates spelling only those two names.
//! 2. **Every implicit binding is printed, before and after.** For every
//! instance in a watched file, [`bindings`] lists what each connection's
//! port half and net half name — the net half of `.name` and of each port
//! `.*` reaches looked up exactly where the language looks it up. The two
//! lists must be equal, which is what refuses a dangling `.*`, a `.d` left
//! pointing at nothing, a `.*` that starts binding the new name, and a
//! connection added twice.
//!
//! Only bindings whose port or net spells the old or the new name are
//! printed: a rename adds and removes declarations of those two names alone,
//! so a lookup of any other name — and a port of any other name — cannot
//! move. That is the watched-file argument, applied one level down.
use std::path::{Path, PathBuf};
use vlog_parser::ast::{Connection, ExprKind, ListElem, SourceFile};
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
use vlog_parser::{parse_source_tolerant, tokenize};
use vlog_semantic::{
resolve_external, ExternalResolutions, Semantics, Surface, SymbolKind, WorkspaceIndex,
};
use super::ledger::{pieces_match, Split};
use super::{anchor_of, Anchor, Shifts};
use crate::rename::sites::{binds_implicitly, may_connect_implicitly, nearest, sites, Site};
use crate::rename::Scope;
use crate::TextEdit;
/// The rename's lexical contract for a file whose edits insert connection
/// text: the old name replaced by the new one, the four connection templates
/// inserted — each **where a connection list takes it** — and nothing else
/// changed.
pub(super) fn insertions_match(
before: &str,
after: &str,
edits: &[TextEdit],
names: [&str; 2],
shown: &str,
) -> Result<(), String> {
let refusal = |what: &str| format!("the rename would {what} in {shown}; no edits were made.");
let Ok(old_tokens) = tokenize(before) else {
return Err(refusal("edit a file lucisv cannot lex"));
};
let slots = Slots::of(before);
for edit in edits {
let honest = match edit.range.is_empty() {
true => template(&edit.new_text, names).is_some(),
false => replaces_one_name(&old_tokens, edit, names),
};
if !honest {
return Err(refusal(&format!("write `{}`, which is not a rename", edit.new_text)));
}
if edit.range.is_empty() && !slots.takes(before, edit, edits, names) {
let outside = format!("write `{}` outside a connection list", edit.new_text);
return Err(refusal(&outside));
}
}
let split = Split::read(before, after, edits, shown, "the rename")?;
pieces_match(&split, edits, shown, "the rename")?;
let grew = parse_source_tolerant(after).1.len() > parse_source_tolerant(before).1.len();
match grew {
true => Err(refusal("leave a connection list that does not parse")),
false => Ok(()),
}
}
/// A replacement is the one identifier token spelling the old name, replaced
/// by the new name.
fn replaces_one_name(
tokens: &[vlog_parser::token::Token],
edit: &TextEdit,
names: [&str; 2],
) -> bool {
let [old, new] = names;
let covered: Vec<_> =
tokens.iter().filter(|t| super::ledger::overlaps(t.span, edit.range)).collect();
matches!(covered.as_slice(), [only] if only.kind == TokenKind::Ident
&& only.span == edit.range
&& only.text == old
&& edit.new_text == new)
}
/// The four things a rename may insert.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Template {
/// `(X)`: a shorthand's net, written out.
Tail,
/// `,`: the comma before a `//` comment on a list's last element.
Comma,
/// `.X(Y)`: a connection after that comment, the comma already written.
Connection,
/// `, .X(Y)`: a connection appended to a list.
Appended,
}
/// Which template an insertion spells — `X` and `Y` the old or the new name,
/// no comment — or `None`.
fn template(text: &str, names: [&str; 2]) -> Option<Template> {
let tokens = tokenize(text).ok()?;
let mut code: Vec<&str> = Vec::new();
for token in &tokens {
if !token.leading.is_empty() || token.trailing.is_some() {
return None;
}
match token.kind {
TokenKind::Eof => {}
TokenKind::Ident if names.contains(&token.text.as_str()) => code.push("name"),
TokenKind::Symbol => code.push(token.text.as_str()),
_ => return None,
}
}
match code.as_slice() {
["(", "name", ")"] => Some(Template::Tail),
[","] => Some(Template::Comma),
[".", "name", "(", "name", ")"] => Some(Template::Connection),
[",", ".", "name", "(", "name", ")"] => Some(Template::Appended),
_ => None,
}
}
#[cfg(test)]
fn is_connection_text(text: &str, names: [&str; 2]) -> bool {
template(text, names).is_some()
}
/// Where a rename may insert into one file, read off the **before** tree with
/// the walk the engine plans with (`rename::sites`), so the plan and the
/// check cannot disagree about what a connection list is (QA M3.5 finding 1:
/// the template check alone admitted `,` into a positional list, `(d)` after
/// a call argument, `, .din(d)` into a `#(...)` override).
struct Slots {
/// The end of every shorthand connection's name (`.d` → after `d`).
tails: Vec<u32>,
/// Every named list holding `.*`: the end of its last element, and its
/// closing `)`.
lists: Vec<(u32, u32)>,
}
impl Slots {
fn of(before: &str) -> Slots {
let (tree, _) = parse_source_tolerant(before);
let mut out = Slots { tails: Vec::new(), lists: Vec::new() };
for site in sites(&tree.items) {
// A list holding text the parser could not read has no slot at
// all: an error element's span may stop short of its own `)`,
// so an append "after the last element" lands inside it, and the
// parse check cannot tell — one diagnostic before, one after
// (QA M3.5 finding 4). The engine already refuses such lists.
if site.unreadable().next().is_some() {
continue;
}
let shorthands = site.connections().filter(|c| c.expr.is_none() && c.name != "*");
out.tails.extend(shorthands.map(|c| c.name_span.end));
let last = site.conns.last().map(|e| match e {
ListElem::Ok(c) => c.span,
ListElem::Error(raw) => raw.span,
});
let close = site.instance.span.end.checked_sub(1);
let closed = close.filter(|&at| before.as_bytes().get(at as usize) == Some(&b')'));
if let (true, Some(last), Some(close)) = (site.has_wildcard(), last, closed) {
out.lists.push((last.end, close));
}
}
out
}
/// Whether `edit` — an insertion — lands where its template belongs: a
/// net right after a shorthand's name; a connection between a `.*` list's
/// last element (and the comments after it) and the list's `)`; and the
/// comma-before-`//` pair as a **pair** — a comma right after the last
/// element only with a bare connection written into the same list, and a
/// bare connection only behind such a comma. A lone `,` leaves `(.*,)`,
/// which the tolerant parser does not flag (QA M3.5 finding 3).
fn takes(&self, before: &str, edit: &TextEdit, edits: &[TextEdit], names: [&str; 2]) -> bool {
let at = edit.range.start;
let within = |at: u32, &(end, close): &(u32, u32)| {
let gap = before.get(end as usize..at as usize).unwrap_or(",");
end <= at && at <= close && tokenize(gap).is_ok_and(|tokens| tokens.len() == 1)
};
let comma_at =
|end: u32| edits.iter().any(|e| e.range == TextRange::empty(end) && e.new_text == ",");
let connection_in = |list: &(u32, u32)| {
edits.iter().any(|e| {
e.range.is_empty()
&& template(&e.new_text, names) == Some(Template::Connection)
&& within(e.range.start, list)
})
};
let lists = || self.lists.iter();
match template(&edit.new_text, names) {
Some(Template::Tail) => self.tails.contains(&at),
Some(Template::Comma) => lists().any(|list| list.0 == at && connection_in(list)),
Some(Template::Connection) => lists().any(|list| within(at, list) && comma_at(list.0)),
Some(Template::Appended) => lists().any(|list| within(at, list)),
None => false,
}
}
}
/// Where file `file`'s inserted connection text sits once the edits are
/// applied. The names it spells are the binding print's to account for, not
/// the resolution print's: before the edit they were not written.
pub(super) fn inserted_in(edits: &[(usize, Vec<TextEdit>)], file: usize) -> Vec<TextRange> {
let edits = edits.iter().find(|(f, _)| *f == file);
edits.map(|(_, edits)| inserted_after(edits)).unwrap_or_default()
}
/// Where each insertion's text sits once the edits are applied, so that the
/// resolution print does not compare the names inside it — the binding print
/// is what accounts for them.
fn inserted_after(edits: &[TextEdit]) -> Vec<TextRange> {
let mut out = Vec::new();
let mut delta: i64 = 0;
for edit in edits {
let start = (i64::from(edit.range.start) + delta).max(0) as u32;
if edit.range.is_empty() {
out.push(TextRange::new(start, start + edit.new_text.len() as u32));
}
delta += edit.new_text.len() as i64 - i64::from(edit.range.len());
}
out
}
/// What one half of a connection names.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum Bound {
/// These declarations, as (file, name span).
At(Vec<(PathBuf, u32, u32)>),
/// Nothing lucisv can see.
Nothing,
/// An expression other than a bare name: the resolution print compares
/// what is inside it.
Expression,
/// A name looked up in a scope lucisv cannot name — a hierarchical `bind`
/// target, or the `.*` of a module it cannot read (`probe 0`/`probe 1`).
Opaque(String),
}
/// One binding of one instance: where the instance is named, what the port
/// half names, and what the net half names.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Binding {
at: (u32, u32),
port: Bound,
net: Bound,
}
/// One side of the comparison: a file's tree, its analysis, the index it
/// resolves against, and the shift that maps a before-side span to after.
struct Side<'x> {
tree: &'x SourceFile,
semantics: &'x Semantics,
external: &'x ExternalResolutions,
index: &'x WorkspaceIndex,
path: &'x Path,
shifts: &'x Shifts,
}
/// The state after the edits, as [`super::verify`] already built it: each
/// edited file's new text and analysis, and the after-index.
pub(super) struct After<'x> {
pub(super) edited: &'x [(PathBuf, String)],
pub(super) analyses: &'x [(PathBuf, Semantics)],
pub(super) index: &'x WorkspaceIndex,
}
/// Every watched file's implicit bindings must be the same before and after.
/// A file that could write none of either name is skipped, unless the edits
/// insert into it.
pub(super) fn bindings_match(
scope: &Scope,
watched: &[usize],
edits: &[(usize, Vec<TextEdit>)],
shifts: &Shifts,
after: &After,
names: [&str; 2],
) -> Result<(), String> {
let abandoned = || "lucisv could not verify the rename, so it made no edits.".to_string();
for &i in watched {
let (Some(path), Some(text), Some(analysis)) =
(scope.path(i), scope.text(i), scope.cached(i))
else {
return Err(abandoned());
};
let slot = edits.iter().position(|(f, _)| *f == i);
let inserts = slot
.and_then(|k| edits.get(k))
.is_some_and(|(_, e)| e.iter().any(|e| e.range.is_empty()));
if !inserts && !may_connect_implicitly(text, &names) {
continue;
}
let (tree, _) = parse_source_tolerant(text);
let side = Side {
tree: &tree,
semantics: &analysis.semantics,
external: &analysis.external,
index: scope.index(),
path,
shifts,
};
let before = bindings(&side, names);
let after = match slot.and_then(|k| after.edited.get(k)) {
Some((_, text)) => edited_bindings(path, text, after, names),
None => scope.against(i, after.index).map(|(semantics, external)| {
let identity = Shifts::default();
bindings(
&Side {
tree: &tree,
semantics,
external: &external,
index: after.index,
path,
shifts: &identity,
},
names,
)
}),
};
let Some(after) = after else { return Err(abandoned()) };
if let Some(instance) = first_difference(&before, &after) {
let [old, new] = names;
return Err(format!(
"renaming `{old}` to `{new}` would change what an implicit connection of `{instance}` binds in {}; the rename was abandoned.",
scope.name_of(path)
));
}
}
Ok(())
}
/// An edited file's bindings, read off its new text and the analysis the
/// after-index was built with.
fn edited_bindings(
path: &Path,
text: &str,
after: &After,
names: [&str; 2],
) -> Option<Vec<(Binding, String)>> {
let (tree, _) = parse_source_tolerant(text);
let (_, semantics) = after.analyses.iter().find(|(p, _)| p == path)?;
let external = resolve_external(semantics, after.index);
let identity = Shifts::default();
Some(bindings(
&Side {
tree: &tree,
semantics,
external: &external,
index: after.index,
path,
shifts: &identity,
},
names,
))
}
/// The instance whose bindings differ first, if any do.
fn first_difference(before: &[(Binding, String)], after: &[(Binding, String)]) -> Option<String> {
for n in 0..before.len().max(after.len()) {
match (before.get(n), after.get(n)) {
(Some((a, _)), Some((b, name))) if a != b => return Some(name.clone()),
(Some((_, name)), None) | (None, Some((_, name))) => return Some(name.clone()),
_ => {}
}
}
None
}
/// Every binding in one file whose port or net spells one of `names`, sorted,
/// each with the instance's name for the refusal.
fn bindings(side: &Side, names: [&str; 2]) -> Vec<(Binding, String)> {
let mut out: Vec<(Binding, String)> = Vec::new();
for site in sites(&side.tree.items) {
let at = side.shifts.map(side.path, site.instance.name_span);
let mut push = |port: Bound, net: Bound| {
out.push((Binding { at: (at.start, at.end), port, net }, site.instance.name.clone()))
};
for c in site.connections().filter(|c| c.name != "*") {
if let Some(net) = net_half(side, &site, c, names) {
push(port_half(side, c), net);
}
}
if site.has_wildcard() {
for (port, net) in wildcard(side, &site, names) {
push(port, net);
}
}
}
out.sort();
out
}
/// What a named connection's port half names: the reference the semantic
/// layer recorded for it.
fn port_half(side: &Side, c: &Connection) -> Bound {
reference_at(side, c.name_span)
}
/// What a named connection's net half names, when the connection is one the
/// print covers: `.name`'s implicit net, an explicit bare name, or (for a port
/// spelling one of the names) any other expression.
fn net_half(side: &Side, site: &Site, c: &Connection, names: [&str; 2]) -> Option<Bound> {
let port_named = names.contains(&c.name.as_str());
match c.expr.as_ref().map(|e| (&e.kind, e.span)) {
None => port_named.then(|| implicit(side, site, &c.name)),
Some((ExprKind::Ident(name), span)) if port_named || names.contains(&name.as_str()) => {
Some(reference_at(side, span))
}
Some(_) => port_named.then_some(Bound::Expression),
}
}
/// The bindings a `.*` makes for the ports spelling one of `names` that the
/// list does not connect explicitly — or, when the module cannot be read, a
/// probe of what each name would find there.
fn wildcard(side: &Side, site: &Site, names: [&str; 2]) -> Vec<(Bound, Bound)> {
let module = &site.instantiation.module;
if instantiable(side.index, module) != 1 {
let probe = |(slot, name): (usize, &&str)| {
(Bound::Opaque(format!("probe {slot}")), implicit(side, site, name))
};
return names.iter().enumerate().map(probe).collect();
}
let mut out = Vec::new();
for (port, defs) in side.index.members_of(module) {
let ports: Vec<_> = defs.iter().filter(|d| d.kind == SymbolKind::Port).collect();
if ports.is_empty() || !names.contains(&port) || site.named(port).is_some() {
continue;
}
let at = ports.iter().map(|d| located(side, d.file, d.name_span)).collect();
out.push((at_all(at), implicit(side, site, port)));
}
out
}
/// What `.name` or `.*` binds `name` to at `site`: the nearest declaration
/// where the instance is written, or — for a `bind` into one plain module —
/// that module's own declaration of it.
fn implicit(side: &Side, site: &Site, name: &str) -> Bound {
match site.bind_target() {
Ok(None) => {
// The nearest declaration shadows whatever its kind; one `.*`
// cannot bind (a parameter, a module) is a binding to nothing.
let found = nearest(side.semantics, site.instance.name_span.start, name)
.and_then(|s| side.semantics.symbol(s))
.filter(|s| binds_implicitly(s.kind));
match found {
Some(symbol) => at_all(vec![located_here(side, symbol.name_span)]),
None => Bound::Nothing,
}
}
Ok(Some(target)) if instantiable(side.index, target) == 1 => {
let defs = side.index.member_in(target, name, Surface::Hierarchical);
let defs = defs.iter().filter(|d| binds_implicitly(d.kind));
at_all(defs.map(|d| located(side, d.file, d.name_span)).collect())
}
_ => Bound::Opaque(name.to_string()),
}
}
/// What the reference written exactly at `span` resolves to.
fn reference_at(side: &Side, span: TextRange) -> Bound {
let Some(id) = side.semantics.reference_id_at(span.start) else { return Bound::Nothing };
let Some(reference) = side.semantics.reference(id).filter(|r| r.name_span == span) else {
return Bound::Nothing;
};
let anchor = anchor_of(
side.semantics,
side.external,
side.index,
side.path,
side.shifts,
id.0 as usize,
reference,
);
match anchor {
Anchor::Local(start, end) => at_all(vec![(side.path.to_path_buf(), start, end)]),
Anchor::External(defs) => at_all(defs),
Anchor::Unresolved => Bound::Nothing,
}
}
fn at_all(mut at: Vec<(PathBuf, u32, u32)>) -> Bound {
if at.is_empty() {
return Bound::Nothing;
}
at.sort();
Bound::At(at)
}
fn located_here(side: &Side, span: TextRange) -> (PathBuf, u32, u32) {
let span = side.shifts.map(side.path, span);
(side.path.to_path_buf(), span.start, span.end)
}
fn located(side: &Side, file: vlog_semantic::FileId, span: TextRange) -> (PathBuf, u32, u32) {
let path = side.index.path(file).unwrap_or(Path::new("?")).to_path_buf();
let span = side.shifts.map(&path, span);
(path, span.start, span.end)
}
fn instantiable(index: &WorkspaceIndex, name: &str) -> usize {
index.units(name).iter().filter(|d| d.kind.is_instantiable()).count()
}
/// Masked-corruption attacks (CLAUDE.md invariant 4): each is an edit the
/// rename engine could plausibly produce if it got implicit connections
/// wrong, handed straight to the verifier, and each must be refused. The
/// honest edit is the control.
#[cfg(test)]
mod tests {
use super::super::verify;
use super::*;
use crate::trace::VerifyTrace;
const LEAF: &str = "module leaf (input logic clk, input logic [7:0] d, output logic [7:0] q);\n always_ff @(posedge clk) q <= d;\nendmodule\n";
const TOP: &str = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n";
const TOP2: &str = "module top2 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.clk, .d, .q);\nendmodule\n";
fn files(top: &str) -> Vec<(PathBuf, String)> {
vec![
(PathBuf::from("/rtl/leaf.sv"), LEAF.to_string()),
(PathBuf::from("/rtl/top.sv"), top.to_string()),
(PathBuf::from("/rtl/top2.sv"), TOP2.to_string()),
]
}
/// The edit replacing the whole word `name` found after `prefix`.
fn swap(text: &str, prefix: &str, name: &str, new: &str) -> TextEdit {
let from = text.find(prefix).expect("prefix") + prefix.len();
let start = (from + text[from..].find(name).expect("name")) as u32;
TextEdit { range: TextRange::new(start, start + name.len() as u32), new_text: new.into() }
}
/// The insertion of `new` right after the first `after`.
fn put(text: &str, after: &str, new: &str) -> TextEdit {
let at = (text.find(after).expect("anchor") + after.len()) as u32;
TextEdit { range: TextRange::empty(at), new_text: new.into() }
}
/// Verify a port rename `d` → `din` of `leaf` whose `top.sv` and
/// `top2.sv` edits are the ones given.
fn port_rename(
top: &str,
top_edits: Vec<TextEdit>,
top2_edits: Vec<TextEdit>,
) -> Result<(), String> {
let files = files(top);
let mut scope = Scope::build(&files);
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top_i, top2) =
(index("/rtl/leaf.sv"), index("/rtl/top.sv"), index("/rtl/top2.sv"));
let mut edits =
vec![(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")])];
for (file, list) in [(top_i, top_edits), (top2, top2_edits)] {
if !list.is_empty() {
edits.push((file, list));
}
}
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
}
fn shorthand_edits(tail: &str) -> Vec<TextEdit> {
vec![swap(TOP2, ".clk, .", "d", "din"), put(TOP2, ".clk, .d", tail)]
}
#[test]
fn the_honest_rewrite_verifies() {
let honest = port_rename(TOP, vec![put(TOP, "(.*", ", .din(d)")], shorthand_edits("(d)"));
assert_eq!(honest, Ok(()));
}
#[test]
fn the_rename_that_cut_both_bindings_is_refused() {
// QA finding 1, exactly: `.d` became `.din`, `.*` was left alone.
let cut = port_rename(TOP, Vec::new(), vec![swap(TOP2, ".clk, .", "d", "din")]);
assert!(cut.expect_err("refused").contains("implicit connection of `u_leaf`"));
let wildcard_only = port_rename(TOP, Vec::new(), shorthand_edits("(d)"));
assert!(wildcard_only.is_err(), "the `.*` in top.sv no longer binds `din`");
}
#[test]
fn a_shorthand_written_out_with_the_wrong_net_is_refused() {
// `(din)` spells only the two names, so only the binding print sees it.
let wrong = port_rename(TOP, vec![put(TOP, "(.*", ", .din(d)")], shorthand_edits("(din)"));
assert!(wrong.is_err(), "`.din(din)` binds nothing top2 declares");
}
#[test]
fn a_wildcard_connection_to_the_wrong_net_is_refused() {
let other = port_rename(TOP, vec![put(TOP, "(.*", ", .din(q)")], shorthand_edits("(d)"));
assert!(other.is_err(), "`q` is not one of the two names");
let swapped = port_rename(TOP, vec![put(TOP, "(.*", ", .d(din)")], shorthand_edits("(d)"));
assert!(swapped.is_err(), "`.d(din)` names a port `leaf` no longer has");
}
#[test]
fn an_insertion_that_is_not_connection_text_is_refused() {
for text in [", .din(d) /* c */", "; wire din;", ", .din(d), .din(d)", ", .din(d"] {
let bad = port_rename(TOP, vec![put(TOP, "(.*", text)], shorthand_edits("(d)"));
assert!(bad.is_err(), "{text:?} must be refused");
}
}
#[test]
fn a_connection_added_beside_an_explicit_one_of_the_same_port_is_refused() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*, .d(8'h0));\nendmodule\n";
let honest =
port_rename(top, vec![swap(top, "(.*, .", "d", "din")], shorthand_edits("(d)"));
assert_eq!(honest, Ok(()));
let doubled = port_rename(
top,
vec![swap(top, "(.*, .", "d", "din"), put(top, "(8'h0)", ", .din(d)")],
shorthand_edits("(d)"),
);
assert!(doubled.is_err(), "the port is connected twice");
}
#[test]
fn an_insertion_into_the_wrong_instance_is_refused() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\n leaf u_two (.clk, .d(d), .q());\nendmodule\n";
let wrong = port_rename(
top,
vec![swap(top, "u_two (.clk, .", "d", "din"), put(top, ".q(", ".din(d)")],
shorthand_edits("(d)"),
);
assert!(wrong.is_err());
}
/// Verify a rename `d` → `x` of top's own port, with the given edits.
fn net_rename(top: &str, extra: Vec<TextEdit>) -> Result<(), String> {
let files = files(top);
let mut scope = Scope::build(&files);
let top_i = scope.index_of(Path::new("/rtl/top.sv")).expect("top");
let mut list = vec![swap(top, "[7:0] ", "d", "x")];
list.extend(extra);
list.sort_by_key(|e| e.range.start);
verify(&mut scope, &[(top_i, list)], "d", "x", &mut VerifyTrace::default())
}
#[test]
fn a_net_rename_that_leaves_the_wildcard_alone_is_refused() {
assert_eq!(net_rename(TOP, vec![put(TOP, "(.*", ", .d(x)")]), Ok(()));
assert!(net_rename(TOP, Vec::new()).is_err(), "`.*` loses `d`");
assert!(net_rename(TOP, vec![put(TOP, "(.*", ", .x(d)")]).is_err(), "the halves swapped");
}
#[test]
fn a_wildcard_that_starts_binding_the_new_name_is_refused() {
let child = "module child (input logic a, input logic b);\nendmodule\n";
let top = "module top (input logic a);\n child u_c (.*);\nendmodule\n";
let files = vec![
(PathBuf::from("/rtl/child.sv"), child.to_string()),
(PathBuf::from("/rtl/top.sv"), top.to_string()),
];
let mut scope = Scope::build(&files);
let top_i = scope.index_of(Path::new("/rtl/top.sv")).expect("top");
let edits = vec![(top_i, vec![swap(top, "logic ", "a", "b"), put(top, "(.*", ", .a(b)")])];
let captured = verify(&mut scope, &edits, "a", "b", &mut VerifyTrace::default());
assert!(captured.is_err(), "`.*` now binds `b` to the renamed port");
}
#[test]
fn a_net_rename_behind_an_unreadable_wildcard_is_refused() {
let top = "module top (input logic [7:0] d);\n ghost u_g (.*);\nendmodule\n";
let files = vec![(PathBuf::from("/rtl/top.sv"), top.to_string())];
let mut scope = Scope::build(&files);
let edits = vec![(0usize, vec![swap(top, "[7:0] ", "d", "x")])];
let blind = verify(&mut scope, &edits, "d", "x", &mut VerifyTrace::default());
assert!(blind.is_err(), "the probe of `d` and `x` moved");
}
/// `top2` with every `.` of its shorthand list blanked out: the same
/// bytes at the same offsets, but a **positional** list — so its `d`
/// ends exactly where `top2`'s shorthand `.d` does.
const POSITIONAL: &str = "module top2 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf ( clk, d, q);\nendmodule\n";
/// The position check keys on the file's own sites, not on a byte: `(d)`
/// at the offset that is a shorthand's end in `top2.sv` is still refused
/// in a file where that offset ends a positional element.
#[test]
fn a_shorthand_offset_is_no_licence_in_another_file() {
let end = TOP2.find(".clk, .d").expect("the shorthand") as u32 + 8;
assert_eq!(POSITIONAL.find(" clk, d").map(|at| at as u32 + 8), Some(end));
let files = vec![
(PathBuf::from("/rtl/leaf.sv"), LEAF.to_string()),
(PathBuf::from("/rtl/top.sv"), TOP.to_string()),
(PathBuf::from("/rtl/top2.sv"), TOP2.to_string()),
(PathBuf::from("/rtl/top3.sv"), POSITIONAL.to_string()),
];
let mut scope = Scope::build(&files);
let at = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top, top2, top3) =
(at("/rtl/leaf.sv"), at("/rtl/top.sv"), at("/rtl/top2.sv"), at("/rtl/top3.sv"));
let tail = |text: &str| TextEdit { range: TextRange::empty(end), new_text: text.into() };
let mut edits = vec![
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
(top, vec![put(TOP, "(.*", ", .din(d)")]),
(top2, shorthand_edits("(d)")),
(top3, vec![tail("(d)")]),
];
edits.sort_by_key(|(file, _)| *file);
let outcome = verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default());
let refusal = outcome.expect_err("a positional `d(d)` is not a shorthand");
assert!(refusal.contains("outside a connection list in top3.sv"), "{refusal}");
}
/// The same inside one file: `(d)` after the shorthand `.d` of one
/// instance is the rewrite, `(d)` after the positional `d` of the next is
/// not — and `,` after that positional element is not either.
#[test]
fn a_shorthand_licenses_only_its_own_position() {
let top = "module top2 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.clk, .d, .q);\n leaf u_two (clk, d, q);\nendmodule\n";
let files = vec![
(PathBuf::from("/rtl/leaf.sv"), LEAF.to_string()),
(PathBuf::from("/rtl/top2.sv"), top.to_string()),
];
for extra in ["(d)", ","] {
let mut scope = Scope::build(&files);
let at = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top2) = (at("/rtl/leaf.sv"), at("/rtl/top2.sv"));
let mut list = vec![
swap(top, ".clk, .", "d", "din"),
put(top, ".clk, .d", "(d)"),
put(top, "u_two (clk, d", extra),
];
list.sort_by_key(|e| e.range.start);
let mut edits = vec![
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
(top2, list),
];
edits.sort_by_key(|(file, _)| *file);
let outcome = verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default());
assert!(outcome.is_err(), "{extra:?} after a positional `d` must be refused");
}
}
/// The comma-before-`//` pair must be one pair: a comma closing one
/// `.*` list and a bare connection written into another are each half of
/// nothing, however well each half is placed.
#[test]
fn a_comma_and_its_connection_in_different_lists_are_refused() {
let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_a (\n .* // one\n );\n leaf u_b (\n .* // two\n );\nendmodule\n";
let files = vec![
(PathBuf::from("/rtl/leaf.sv"), LEAF.to_string()),
(PathBuf::from("/rtl/top.sv"), top.to_string()),
];
let verified = |list: Vec<TextEdit>| {
let mut scope = Scope::build(&files);
let at = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top_i) = (at("/rtl/leaf.sv"), at("/rtl/top.sv"));
let mut list = list;
list.sort_by_key(|e| e.range.start);
let mut edits = vec![
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
(top_i, list),
];
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
};
let pair = |list: &str, comment: &str| {
vec![put(top, list, ","), put(top, comment, "\n .din(d)")]
};
let honest: Vec<TextEdit> =
[pair("u_a (\n .*", "// one"), pair("u_b (\n .*", "// two")].concat();
assert_eq!(verified(honest), Ok(()), "each list's own pair");
let crossed: Vec<TextEdit> = [
pair("u_a (\n .*", "// one"),
vec![put(top, "u_b (\n .*", ","), put(top, "// one", "\n .din(d)")],
]
.concat();
let refusal = verified(crossed).expect_err("u_b's comma has no connection of its own");
assert!(refusal.contains("outside a connection list"), "{refusal}");
}
#[test]
fn the_connection_templates_are_exactly_four() {
let names = ["d", "din"];
for ok in ["(d)", " (din )", ",", ".din(d)", ",\n .din(d)", ", .d(din)"] {
assert!(is_connection_text(ok, names), "{ok:?}");
}
for bad in ["(q)", ",,", ".din(d),", "(d)//c", ".din[0](d)", "(d + d)"] {
assert!(!is_connection_text(bad, names), "{bad:?}");
}
}
}