Rename keeps implicit connections bound (TODO-MCP M3.5): .name and .* rewritten explicitly, verified by a binding print; the LSP hands the engine one more hop

vlog_refactor: a rename used to cut a `.name` shorthand or a `.*` wildcard binding — port d → din of leaf left `leaf u (.*)` binding nothing and turned `.d` into `.din` against a parent with no net din; renaming the parent's net cut both — and verified clean, because the semantic layer records the port half of `.name` and nothing of `.*` (M3 QA finding 1; the LSP shared it). rename/{connections,sites,layout}.rs: an AST walk over every named connection list finds the implicit bindings and looks each name up the way the language does (nearest declaration outward; a bind's target module; a bare instance name resolved through the instantiation table with the bind's enclosing module's own instances winning, §23.11); `.p` becomes `.q(p)`, a `.*` that bound the name gains `.q(p)` / `.n(m)` appended in the list's own layout (comma before a trailing // comment, CRLF kept); every rewrite listed in warnings; refused by name: a `.*` into a module lucisv cannot read or finds declared twice, a list split by ifdefs or holding unparsed text, a hierarchical bind target, a `.*` that would start binding the new name, a package variable an import might hand to a `.*`. check/implicit.rs: the verifier learns the shape — a file with insertions passes only if every replacement is the old name becoming the new and every insertion is one of four connection templates at the exact slot the rewrite writes (a shorthand's name end; between a `.*` list's last element and its `)`), the comma and its `.X(Y)` only as a pair in one list, no slot at all in a list holding an error element — and every implicit binding (port half and net half) is printed before and after and must match. lucisv_server: rename_sources_traced hands the engine one more hop — the declaring files of every module a handed-over file instantiates (module_select::instantiated_by, index edges only) — so a `.*` into a module declaring neither name is read, not refused. lucisv_mcp: the rename tool's known-limit sentence replaced; the M3 QA finding-1 test un-ignored.

Three QA rounds (Opus) attacked the widened verifier and found, in order, position-blind insertions, a lone trailing comma, and a slot after an error element — each fixed (the last by the lead) and pinned by 40+ qa_* tests incl. masked-corruption pairs; opentitan copies: prim_count err_o/clr_i, aes_core clk_i, entropy_src clk_i, prim_packer_fifo wready_o rename cleanly with their .* cov binds written out; prim_fifo_sync clr_i refused over the FPV binds that really target fifo instances. Accepted gap: a bind onto an instance that exists only inside a generate block of the enclosing module. Filed to vlog_parser: trailing `,` / `{d,, d}` / `type(x)'(y)` in a connection list parse without a diagnostic. Gates through tools/guard.sh: fmt, clippy, workspace 4 762 passed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5.1 committed 2026-09-23 11:41:46 -07:00
1 parent 14b72f2862
commit 4edada583f
21 files changed
+4226 -20

No files matched your search

+805
View File
@@ -0,0 +1,805 @@
//! 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::{display, 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],
path: &Path,
) -> Result<(), String> {
let refusal =
|what: &str| format!("the rename would {what} in {}; no edits were made.", display(path));
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, path, "the rename")?;
pieces_match(&split, edits, path, "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.",
display(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:?}");
}
}
}
+33 -5
View File
@@ -18,7 +18,10 @@
//! contract, kept separately, so the formatter's safety net does not widen.
mod after;
mod implicit;
mod ledger;
#[cfg(test)]
mod qa_implicit;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -58,10 +61,7 @@ pub(crate) fn verify(
let shifts = Shifts::new(scope, edits, new_name);
// 1. The token stream of every touched file, before and after.
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
let Some(before) = scope.text(*i) else { return Err(ABANDONED.to_string()) };
trace.tokens.measure(|| tokens_match(before, text, &Shift::new(edits), new_name, path))?;
}
tokens_verified(scope, edits, &edited, [old_name, new_name], &mut trace.tokens)?;
// 2. What every name resolves to, before and after — in every file the
// rename could possibly have moved, not only the ones it edited. A file
@@ -98,9 +98,10 @@ pub(crate) fn verify(
let (after_index, edited_analyses) = trace.rebuild.measure(|| after_index(scope, &edited));
for (n, &i) in watched.iter().enumerate() {
let Some(path) = scope.path(i) else { return Err(ABANDONED.to_string()) };
let inserted = implicit::inserted_in(edits, i);
let after = trace
.after
.measure(|| after_print(scope, i, path, &after_index, &edited_analyses, &[]));
.measure(|| after_print(scope, i, path, &after_index, &edited_analyses, &inserted));
let (Some(after), Some(before)) = (after, before.get(n)) else {
return Err(ABANDONED.to_string());
};
@@ -111,6 +112,33 @@ pub(crate) fn verify(
));
}
}
// 3. What every implicit connection (`.name`, `.*`) binds, before and
// after — the bindings no reference records.
let after =
implicit::After { edited: &edited, analyses: &edited_analyses, index: &after_index };
let names = [old_name, new_name];
trace.after.measure(|| implicit::bindings_match(scope, &watched, edits, &shifts, &after, names))
}
/// Step 1 of [`verify`]: every touched file's token stream, before and after.
/// A file the rename also rewrites an implicit connection in may insert —
/// only connection text, where a connection list takes it, checked piece by
/// piece (`implicit`); every other file keeps the strict token identity.
fn tokens_verified(
scope: &Scope,
edits: &[(usize, Vec<TextEdit>)],
edited: &[(PathBuf, String)],
names: [&str; 2],
stage: &mut crate::trace::Stage,
) -> Result<(), String> {
for ((i, edits), (path, text)) in edits.iter().zip(edited) {
let Some(before) = scope.text(*i) else { return Err(ABANDONED.to_string()) };
stage.measure(|| match edits.iter().any(|e| e.range.is_empty()) {
true => implicit::insertions_match(before, text, edits, names, path),
false => tokens_match(before, text, &Shift::new(edits), names[1], path),
})?;
}
Ok(())
}
@@ -0,0 +1,498 @@
//! QA M3.5 (2026-09-23): masked-corruption attacks on the rename verifier's
//! implicit-connection widening (`check::implicit`), CLAUDE.md invariant 4.
//!
//! Each attack hands `verify` the honest edits of a port rename `d` → `din`
//! of `leaf` *plus* one corrupting insertion that spells one of the four
//! connection templates `insertions_match` admits, placed somewhere a rename
//! never writes. The template check looks at an insertion's text, not at
//! where it goes, and the resolution print skips inserted ranges — so an
//! insertion outside a named connection list is seen by nothing.
//!
//! Crate-internal because `verify` is: the dev exposed no public hook.
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use super::verify;
use crate::rename::Scope;
use crate::trace::VerifyTrace;
use crate::TextEdit;
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";
/// The attacked file: a positional instance with a parameter override, a
/// function call, a task call, a concatenation, a string and a comment.
const T3: &str = "module top3 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf #(.W(8)) u_p (clk, d, q);\n initial $display(\"see .d here\");\n // comment .d here\n function automatic logic [7:0] f(input logic [7:0] a, input logic [7:0] b = 0); return a; endfunction\n logic [7:0] r;\n logic [15:0] c;\n assign r = f(d, d);\n assign c = {d, d};\n (* keep *) wire [7:0] w;\n task automatic t(); endtask\n initial t;\n leaf u_n (.clk(clk), .q({q, q}), .*);\nendmodule\n";
/// 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 the honest port rename `d` → `din` over leaf/top/top2/top3, with
/// `extra` edits added to top3 beside its own honest one (`u_n`'s `.*`).
fn attack(extra: Vec<TextEdit>) -> Result<(), String> {
let files: Vec<(PathBuf, String)> = [
("/rtl/leaf.sv", LEAF),
("/rtl/top.sv", TOP),
("/rtl/top2.sv", TOP2),
("/rtl/top3.sv", T3),
]
.iter()
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
.collect();
let mut scope = Scope::build(&files);
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top, top2, top3) =
(index("/rtl/leaf.sv"), index("/rtl/top.sv"), index("/rtl/top2.sv"), index("/rtl/top3.sv"));
let mut t3 = vec![put(T3, "u_n (.clk(clk), .q({q, q}), .*", ", .din(d)")];
t3.extend(extra);
t3.sort_by_key(|e| (e.range.start, e.range.end));
let mut edits = vec![
(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")]),
(top, vec![put(TOP, "(.*", ", .din(d)")]),
(top2, vec![swap(TOP2, ".clk, .", "d", "din"), put(TOP2, ".clk, .d", "(d)")]),
(top3, t3),
];
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
}
#[test]
fn qa_the_honest_edits_verify() {
assert_eq!(attack(Vec::new()), Ok(()));
}
#[test]
fn qa_insertions_the_verifier_already_refuses() {
// Inside a string, a comment, an attribute; an empty named element;
// `(d)` after a `.*` or after an explicit connection; a connection
// before the first element with no comma; a second `.din(d)`.
for (anchor, text) in [
("see .d", "(d)"),
("comment .d", "(d)"),
("(* keep", "(d)"),
("u_n (.clk(clk),", ","),
("u_n (.clk(clk), .q({q, q}), .*", "(d)"),
("u_n (.clk(clk)", "(d)"),
("u_n (", ".din(d)"),
("u_n (.clk(clk), .q({q, q}), .*", ", .din(d)"),
] {
let outcome = attack(vec![put(T3, anchor, text)]);
assert!(outcome.is_err(), "{text:?} after {anchor:?} must be refused");
}
}
/// QA finding 1: an insertion is checked for its text, never for its place.
/// A lone `,` in a positional list shifts every later connection one port
/// down — `leaf u_p (clk,, d, q)` connects `d` to `q`'s port.
#[test]
fn qa_a_comma_inserted_into_a_positional_list_is_refused() {
let outcome = attack(vec![put(T3, "u_p (clk,", ",")]);
assert!(outcome.is_err(), "`u_p (clk,, d, q)` rewires the instance");
}
/// QA finding 1: a connection template inserted outside any connection list.
#[test]
fn qa_connection_text_outside_a_connection_list_is_refused() {
for (anchor, text) in [
("#(.W(8)", ", .din(d)"), // a parameter override
("assign r = f(d, d", "(d)"), // `d(d)`: a call on a net
("assign r = f(d,", ","), // an empty (defaulted) argument
("assign r = f(d, d", ", .din(d)"), // a named argument
("initial t", "(d)"), // a task call gains an argument
("assign c = {d,", ","), // an empty concatenation element
] {
let outcome = attack(vec![put(T3, anchor, text)]);
assert!(outcome.is_err(), "{text:?} after {anchor:?} must be refused: {outcome:?}");
}
}
/// QA finding 1, inside a named list: the template lands inside an explicit
/// connection's expression, which the binding print does not look into
/// (`Bound::Expression` is printed only for a port spelling one of the
/// names) and the resolution print skips.
#[test]
fn qa_connection_text_inside_an_explicit_connection_is_refused() {
for (anchor, text) in [
("u_n (.clk(clk", "(d)"), // `.clk(clk(d))`
("u_n (.clk(clk), .q({q", "(d)"), // `.q({q(d), q})`
("u_n (.clk(clk), .q({q,", ","), // `.q({q,, q})`
] {
let outcome = attack(vec![put(T3, anchor, text)]);
assert!(outcome.is_err(), "{text:?} after {anchor:?} must be refused: {outcome:?}");
}
}
// ----------------------------------------------------------------------
// M3.5 re-check (2026-09-23): attacks on the position rule (`Slots`)
// ----------------------------------------------------------------------
/// Verify a port rename `d` → `new` of `leaf` (whose two occurrences are
/// renamed honestly) with `top3`'s edits exactly as given — nothing honest
/// added there.
fn port_rename_with(new: &str, top3: &str, edits3: Vec<TextEdit>) -> Result<(), String> {
let files: Vec<(PathBuf, String)> = [("/rtl/leaf.sv", LEAF), ("/rtl/top3.sv", top3)]
.iter()
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
.collect();
let mut scope = Scope::build(&files);
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top) = (index("/rtl/leaf.sv"), index("/rtl/top3.sv"));
let mut edits3 = edits3;
edits3.sort_by_key(|e| (e.range.start, e.range.end));
let mut edits =
vec![(leaf, vec![swap(LEAF, "[7:0] ", "d", new), swap(LEAF, "q <= ", "d", new)])];
if !edits3.is_empty() {
edits.push((top, edits3));
}
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", new, &mut VerifyTrace::default())
}
fn outside(outcome: &Result<(), String>) -> bool {
outcome.as_ref().is_err_and(|refusal| refusal.contains("outside a connection list"))
}
const HEAD: &str = "module top3 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n";
#[test]
fn qa_r_an_append_to_a_named_list_without_a_wildcard_is_outside() {
let top = format!("{HEAD} leaf u_c (.clk(clk), .q(q));\nendmodule\n");
let appended = port_rename_with("din", &top, vec![put(&top, ".q(q)", ", .din(d)")]);
assert!(outside(&appended), "no `.*`, no append: {appended:?}");
}
#[test]
fn qa_r_a_tail_after_an_explicit_connections_name_is_outside() {
let top = format!("{HEAD} leaf u_c (.clk(clk), .d(d), .q(q));\nendmodule\n");
let honest = vec![swap(&top, "(clk), .", "d", "din")];
assert_eq!(port_rename_with("din", &top, honest.clone()), Ok(()));
for anchor in ["u_c (.clk", "(clk), .d"] {
let mut edits = honest.clone();
edits.push(put(&top, anchor, "(d)"));
let outcome = port_rename_with("din", &top, edits);
assert!(outside(&outcome), "`(d)` after {anchor:?}: {outcome:?}");
}
}
#[test]
fn qa_r_an_insertion_between_two_elements_of_a_wildcard_list_is_outside() {
let top = format!("{HEAD} leaf u_n (.*, .clk(clk));\nendmodule\n");
let honest = port_rename_with("din", &top, vec![put(&top, ".clk(clk)", ", .din(d)")]);
assert_eq!(honest, Ok(()), "the append after the last element is the rewrite");
let early = port_rename_with("din", &top, vec![put(&top, "u_n (.*", ", .din(d)")]);
assert!(outside(&early), "between `.*` and `.clk(clk)`: {early:?}");
}
#[test]
fn qa_r_an_insertion_after_the_closing_paren_is_outside() {
let top = format!("{HEAD} leaf u_n (.*);\nendmodule\n");
for text in [", .din(d)", "(d)", ","] {
let outcome = port_rename_with("din", &top, vec![put(&top, "u_n (.*)", text)]);
assert!(outside(&outcome), "{text:?} after `)`: {outcome:?}");
}
}
#[test]
fn qa_r_a_wildcard_list_inside_a_generate_block() {
let top = format!(
"{HEAD} for (genvar i = 0; i < 2; i++) begin : g\n leaf u_g (.*);\n end\nendmodule\n"
);
let honest = port_rename_with("din", &top, vec![put(&top, "u_g (.*", ", .din(d)")]);
assert_eq!(honest, Ok(()), "the generate-scoped `.*` is a slot like any other");
// A bare `.din(d)` needs the `,` written before it.
let bare = port_rename_with("din", &top, vec![put(&top, "u_g (.*", ".din(d)")]);
assert!(outside(&bare), "{bare:?}");
// The same `.*` with nothing added cuts the binding.
assert!(port_rename_with("din", &top, Vec::new()).is_err());
}
#[test]
fn qa_r_a_lone_trailing_comma_is_refused() {
// `,` at a `.*` list's end is a slot (the comma before a `//` comment),
// but written alone it leaves `(.*,)`, which is not a connection list.
let top = format!("{HEAD} leaf u_n (.*);\n leaf u_m (.clk, .d, .q);\nendmodule\n");
let edits = vec![
swap(&top, "u_m (.clk, .", "d", "din"),
put(&top, "u_m (.clk, .d", "(d)"),
put(&top, "u_n (.*", ", .din(d)"),
];
assert_eq!(port_rename_with("din", &top, edits.clone()), Ok(()));
let mut trailing = edits.clone();
trailing.push(put(&top, "u_n (.*", ","));
trailing.retain(|e| e.new_text != ", .din(d)");
let outcome = port_rename_with("din", &top, trailing);
assert!(outcome.is_err(), "`(.*,)`: {outcome:?}");
}
#[test]
fn qa_r_positions_are_before_coordinates_whatever_an_earlier_edit_shifts() {
// `d` → `dnw` grows the line by 2... and `dnew` by 3, which is exactly the
// distance from `.d`'s end to `.q`'s end in `.d,.q`. A tail computed in
// after-coordinates lands on `.q`'s shorthand slot in before-coordinates.
let top = format!("{HEAD} leaf u_s (.clk,.d,.q);\nendmodule\n");
let rename = swap(&top, "u_s (.clk,.", "d", "dnew");
let d_end = top.find("u_s (.clk,.d").expect("d") as u32 + 12;
let q_end = top.find("u_s (.clk,.d,.q").expect("q") as u32 + 15;
assert_eq!(q_end, d_end + 3, "premise: the shift equals the gap");
let tail = |at: u32| TextEdit { range: TextRange::empty(at), new_text: "(d)".into() };
assert_eq!(port_rename_with("dnew", &top, vec![rename.clone(), tail(d_end)]), Ok(()));
let shifted = port_rename_with("dnew", &top, vec![rename, tail(q_end)]);
assert!(shifted.is_err(), "`.dnew,.q(d)` must be refused: {shifted:?}");
}
#[test]
fn qa_r_an_append_inside_the_trailing_comment_is_refused() {
// The gap from `.*` to the insertion is only trivia, so the slot rule
// lets it through; the piece ledger must see the comment change.
let top = format!("{HEAD} leaf u_n (\n .* // the rest\n );\nendmodule\n");
for anchor in ["// the", "// the rest"] {
let outcome = port_rename_with("din", &top, vec![put(&top, anchor, ", .din(d)")]);
assert!(outcome.is_err(), "inside/at the end of the comment ({anchor:?}): {outcome:?}");
}
// The rewrite `layout.rs` writes: `,` before the comment, the connection
// on its own line after it.
let honest = vec![put(&top, " .*", ","), put(&top, "// the rest", "\n .din(d)")];
assert_eq!(port_rename_with("din", &top, honest), Ok(()));
// The bare connection without its comma, and the pair with the
// connection written inside the comment.
let bare = port_rename_with("din", &top, vec![put(&top, "// the rest", "\n .din(d)")]);
assert!(outside(&bare), "{bare:?}");
let inside = vec![put(&top, " .*", ","), put(&top, "// the", "\n .din(d)")];
assert!(port_rename_with("din", &top, inside).is_err(), "the comment is split");
}
/// Verify a net rename `d` → `x` of top's port, the bind file's edits given.
fn bind_net_rename(bind_edits: Vec<TextEdit>, bind: &str) -> Result<(), String> {
let top =
"module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\nendmodule\n";
let files: Vec<(PathBuf, String)> =
[("/rtl/leaf.sv", LEAF), ("/rtl/top.sv", top), ("/rtl/binds.sv", bind)]
.iter()
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
.collect();
let mut scope = Scope::build(&files);
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (top_i, binds) = (index("/rtl/top.sv"), index("/rtl/binds.sv"));
let mut edits = vec![(top_i, vec![swap(top, "[7:0] ", "d", "x")])];
let mut bind_edits = bind_edits;
bind_edits.sort_by_key(|e| e.range.start);
if !bind_edits.is_empty() {
edits.push((binds, bind_edits));
}
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", "x", &mut VerifyTrace::default())
}
#[test]
fn qa_r_a_shorthand_in_a_bind() {
let bind = "module binds;\n bind top leaf u_b (.clk, .d, .q);\nendmodule\n";
assert_eq!(bind_net_rename(vec![put(bind, ".clk, .d", "(x)")], bind), Ok(()));
assert!(bind_net_rename(Vec::new(), bind).is_err(), "`.d` left dangling");
// `.clk` is a shorthand slot too: the binding print is what refuses it.
let wrong = bind_net_rename(vec![put(bind, ".clk", "(x)")], bind);
assert!(wrong.is_err_and(|r| r.contains("implicit connection of `u_b`")));
let stale = bind_net_rename(vec![put(bind, ".clk, .d", "(d)")], bind);
assert!(stale.is_err(), "`.d(d)` names nothing in top any more");
}
/// QA finding 3 (re-check): `Slots::takes` admits a lone `,` at the end of
/// *any* `.*` list — the comma half of the comma-before-`//` pair — without
/// its `.X(Y)` half. Where the list binds one of the names the binding print
/// refuses it (`qa_r_a_lone_trailing_comma_is_refused`); here `other`
/// declares neither name, the binding print has nothing to compare, and the
/// tolerant parser reports no diagnostic for `(.*,)`, so it verifies.
#[test]
fn qa_r_a_lone_trailing_comma_on_a_wildcard_binding_neither_name() {
let other = "module other (input logic clk);\nendmodule\n";
let top = format!("{HEAD} other u_o (.*);\n leaf u_m (.clk, .d, .q);\nendmodule\n");
let files: Vec<(PathBuf, String)> =
[("/rtl/leaf.sv", LEAF), ("/rtl/other.sv", other), ("/rtl/top3.sv", top.as_str())]
.iter()
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
.collect();
let edits_with = |extra: Option<TextEdit>| {
let mut scope = Scope::build(&files);
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top3) = (index("/rtl/leaf.sv"), index("/rtl/top3.sv"));
let mut list =
vec![swap(&top, "u_m (.clk, .", "d", "din"), put(&top, "u_m (.clk, .d", "(d)")];
list.extend(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")]),
(top3, list),
];
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
};
assert_eq!(edits_with(None), Ok(()));
let trailing = edits_with(Some(put(&top, "u_o (.*", ",")));
assert!(trailing.is_err(), "`other u_o (.*,)` does not compile: {trailing:?}");
}
// ----------------------------------------------------------------------
// M3.5 final re-check (2026-09-23): attacks on the comma/connection pair
// ----------------------------------------------------------------------
/// A `.*` list one per line with a `//` comment on its last element.
fn commented(name: &str) -> String {
format!("{HEAD} leaf {name} (\n .* // the rest\n );\nendmodule\n")
}
/// Verify the port rename `d` → `din` with the two files' edits as given.
fn two_files(top3: &str, e3: Vec<TextEdit>, top4: &str, e4: Vec<TextEdit>) -> Result<(), String> {
let files: Vec<(PathBuf, String)> =
[("/rtl/leaf.sv", LEAF), ("/rtl/top3.sv", top3), ("/rtl/top4.sv", top4)]
.iter()
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
.collect();
let mut scope = Scope::build(&files);
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, t3, t4) = (index("/rtl/leaf.sv"), index("/rtl/top3.sv"), index("/rtl/top4.sv"));
let mut edits =
vec![(leaf, vec![swap(LEAF, "[7:0] ", "d", "din"), swap(LEAF, "q <= ", "d", "din")])];
for (file, list) in [(t3, e3), (t4, e4)] {
if !list.is_empty() {
edits.push((file, list));
}
}
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
}
#[test]
fn qa_p_a_comma_in_one_file_and_its_connection_in_another_are_refused() {
let (a, b) = (commented("u_a"), commented("u_b"));
let comma = |t: &str| put(t, " .*", ",");
let conn = |t: &str| put(t, "// the rest", "\n .din(d)");
let honest = two_files(&a, vec![comma(&a), conn(&a)], &b, vec![comma(&b), conn(&b)]);
assert_eq!(honest, Ok(()));
let split = two_files(&a, vec![comma(&a)], &b, vec![conn(&b)]);
assert!(outside(&split), "each file holds half a pair: {split:?}");
let split = two_files(&a, vec![conn(&a)], &b, vec![comma(&b)]);
assert!(outside(&split), "the other way round: {split:?}");
}
#[test]
fn qa_p_two_commas_and_one_connection_in_one_list_are_refused() {
let top = commented("u_n");
let comma = || put(&top, " .*", ",");
let conn = || put(&top, "// the rest", "\n .din(d)");
assert_eq!(port_rename_with("din", &top, vec![comma(), conn()]), Ok(()));
let doubled = port_rename_with("din", &top, vec![comma(), comma(), conn()]);
assert!(doubled.is_err(), "`.*,, // the rest` must be refused: {doubled:?}");
let twice = port_rename_with("din", &top, vec![comma(), conn(), conn()]);
assert!(twice.is_err(), "one comma, two connections: {twice:?}");
}
#[test]
fn qa_p_a_connection_before_its_comma_in_offset_order_is_refused() {
let top = commented("u_n");
let comma = || put(&top, " .*", ",");
// Both at the `.*`'s end, the connection first: `.*\n .din(d), //…`.
let early = put(&top, " .*", "\n .din(d)");
let reversed = port_rename_with("din", &top, vec![early.clone(), comma()]);
assert!(reversed.is_err(), "{reversed:?}");
let glued = port_rename_with("din", &top, vec![put(&top, " .*", ".din(d)"), comma()]);
assert!(glued.is_err(), "`.*.din(d),`: {glued:?}");
// In source order the same two pieces are a legal list whose comment
// now ends the new line: `.*,\n .din(d) // the rest` — accepted, and
// harmless (same bindings, the comment kept).
assert_eq!(port_rename_with("din", &top, vec![comma(), early]), Ok(()));
}
/// `.d(type(q)'(q))` is valid SV (a cast through the type operator) that the
/// tolerant parser reads as an error element `.d(type(q)'(q)` — one byte short
/// of the connection's `)`.
fn cast_list() -> String {
format!("{HEAD} leaf u_e (.*, .d(type(q)'(q)));\nendmodule\n")
}
#[test]
fn qa_p_a_pair_after_an_error_element() {
// After the connection's `)`: the gap to the error element's end is not
// trivia, so no slot.
let cast = cast_list();
let rename = swap(&cast, "u_e (.*, .", "d", "din");
let after_conn = put(&cast, "(q)'(q))", ", .din(d)");
let outcome = port_rename_with("din", &cast, vec![rename, after_conn]);
assert!(outside(&outcome), "{outcome:?}");
// Text that is not SV at all (`+.din(x)`): the verifier used to admit
// the pair after it (the error element is invisible to the binding
// print). Since finding 4 a list holding an error element has no slot at
// all, so the pair is refused — the engine refuses such a list too
// (`unreadable_elements`). Pinned so a change is noticed.
let junk = format!("{HEAD} leaf u_e (\n .*, +.din(x) // the rest\n );\nendmodule\n");
let pair = vec![put(&junk, "+.din(x)", ","), put(&junk, "// the rest", "\n .din(d)")];
let outcome = port_rename_with("din", &junk, pair);
assert!(outside(&outcome), "{outcome:?}");
assert!(port_rename_with("din", &junk, Vec::new()).is_err(), "the cut is still seen");
}
/// QA finding 4 (final re-check): a list holding an error element still
/// registers a slot at the element's end. For valid SV the parser misreads
/// (`.d(type(q)'(q))`, element ending before the connection's own `)`), an
/// append there lands *inside* that connection:
/// `.din(type(q)'(q), .din(d)))` — valid input, output that does not compile,
/// and it verifies: the diagnostic count is compared, not the diagnostics, and
/// the binding print cannot see into an error element. The engine never
/// writes it (`unreadable_elements` refuses a list whose error element spells
/// either name). Loud, not silent — but accepted.
#[test]
fn qa_p_an_append_at_an_error_elements_end_is_refused() {
let cast = cast_list();
let rename = swap(&cast, "u_e (.*, .", "d", "din");
let at_error = put(&cast, "(q)'(q)", ", .din(d)");
let outcome = port_rename_with("din", &cast, vec![rename, at_error]);
assert!(outcome.is_err(), "`.din(type(q)'(q), .din(d)))` must be refused: {outcome:?}");
}
#[test]
fn qa_p_a_clean_list_beside_an_error_element_list_still_verifies() {
// Finding 4's fix drops the slots of the list holding the error element
// only: an honest rewrite of a clean list in the same file still
// verifies, and the same append into the unreadable list is refused.
let other = "module other (input logic clk);\nendmodule\n";
let top = format!(
"{HEAD} other u_x (.*, .clk(type(clk)'(clk)));\n leaf u_n (.*);\n leaf u_m (.clk, .d, .q);\nendmodule\n"
);
let files: Vec<(PathBuf, String)> =
[("/rtl/leaf.sv", LEAF), ("/rtl/other.sv", other), ("/rtl/top3.sv", top.as_str())]
.iter()
.map(|(p, t)| (PathBuf::from(p), t.to_string()))
.collect();
let run = |extra: Option<TextEdit>| {
let mut scope = Scope::build(&files);
let index = |name: &str| scope.index_of(Path::new(name)).expect(name);
let (leaf, top3) = (index("/rtl/leaf.sv"), index("/rtl/top3.sv"));
let mut list = vec![
put(&top, "u_n (.*", ", .din(d)"),
swap(&top, "u_m (.clk, .", "d", "din"),
put(&top, "u_m (.clk, .d", "(d)"),
];
list.extend(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")]),
(top3, list),
];
edits.sort_by_key(|(file, _)| *file);
verify(&mut scope, &edits, "d", "din", &mut VerifyTrace::default())
};
assert_eq!(run(None), Ok(()), "the error element sits in another instance's list");
let into_error = run(Some(put(&top, "(clk)'(clk)", ", .din(d)")));
assert!(outside(&into_error), "{into_error:?}");
}
@@ -0,0 +1,609 @@
//! A rename versus the connections that name it **implicitly**: the `.name`
//! shorthand and the `.*` wildcard (IEEE 1800 §23.3.2.3–4).
//!
//! Both bind by *equal names*, so renaming either side cuts the binding
//! without a single reference moving — the semantic layer records the port
//! half of `.name` and nothing else of either. Two directions:
//!
//! * **A port `p` → `q` of module `M`.** In every instance of `M`, the
//! shorthand `.p` (whose port half the rename already edits to `.q`) gets
//! its net written out: `.q(p)`. A `.*` that bound `p` gets an explicit
//! `.q(p)` added beside it, which is legal and wins over the wildcard.
//! * **A net, variable or port `n` → `m` seen by an instance.** The shorthand
//! `.n` becomes `.n(m)`; a `.*` whose module declares a port `n` gets
//! `.n(m)` added. That covers the instances written where `n` is visible,
//! and the `bind` directives whose target is the module declaring it.
//!
//! Every rewrite is an **insertion** (the port half of `.p` is the rename's
//! own edit), every one is listed in the warnings, and anything lucisv cannot
//! read is refused rather than guessed: an unreadable `.*` module, a module
//! declared twice, a list split by compiler directives or holding text that
//! did not parse, a hierarchical `bind` target, and a `.*` that would start
//! binding the new name. `check::implicit` then re-derives every implicit
//! binding before and after, so an edit here that got it wrong is refused.
use std::collections::HashMap;
use vlog_parser::ast::PortList;
use vlog_parser::{parse_source_tolerant, LineIndex};
use vlog_semantic::{ScopeKind, Surface, SymbolId, SymbolKind};
use super::layout::{append, connection, shorthand_tail};
use super::sites::{binds_implicitly, may_connect_implicitly, nearest, sites, Site};
use super::{contains_word, display, Scope, Target};
use crate::TextEdit;
/// The insertions a rename's implicit connections need, and the sentences
/// that tell the user about each one.
#[derive(Default)]
pub(super) struct Implicit {
pub(super) edits: Vec<(usize, Vec<TextEdit>)>,
pub(super) warnings: Vec<String>,
}
/// Where the renamed declaration lives, as far as an implicit binding cares.
enum Home {
/// Inside module `name`; `top` when directly in the module's own scope,
/// which is the only scope a `bind` into that module reaches.
Module { name: String, top: bool },
/// Inside package `name`: visible wherever it is imported.
Package(String),
/// Anywhere else (a function, a class, the compilation unit).
Elsewhere,
}
/// The rename, as the walk needs it.
struct Renamed {
old: String,
new: String,
file: usize,
symbol: SymbolId,
kind: SymbolKind,
home: Home,
}
/// What a `bind` directive's connections can see of the renamed module.
enum Reach {
/// Its own top-level scope: the bind targets the module by name.
Module,
/// Possibly it: a target lucisv cannot tie to one module.
Maybe,
/// Not it: the target is another module, or instances of other modules.
Elsewhere,
}
/// A module's declared port names, or why lucisv cannot read them.
type Ports = Result<Vec<String>, &'static str>;
/// One pass over the in-scope files.
struct Walk<'r> {
renamed: &'r Renamed,
/// The rename's own edits: a shorthand is rewritten only where its port
/// half is one of them.
occurrences: &'r [(usize, Vec<TextEdit>)],
out: Implicit,
ports: HashMap<String, Ports>,
}
impl<'a> Scope<'a> {
/// The implicit connections renaming `target` to `new_name` must rewrite.
/// `occurrences` are the rename's own edits.
pub(super) fn implicit_connections(
&mut self,
target: &Target,
new_name: &str,
occurrences: &[(usize, Vec<TextEdit>)],
) -> Result<Implicit, String> {
let Some(renamed) = self.renamed(target, new_name) else { return Ok(Implicit::default()) };
let mut walk = Walk {
renamed: &renamed,
occurrences,
out: Implicit::default(),
ports: HashMap::new(),
};
if let (SymbolKind::Port, Home::Module { name, top: true }) = (renamed.kind, &renamed.home)
{
self.port_users(&mut walk, name)?;
}
self.signal_users(&mut walk)?;
let mut out = walk.out;
for (_, edits) in &mut out.edits {
edits.sort_by_key(|e| (e.range.start, e.range.end));
}
Ok(out)
}
/// What the target is and where it lives, read off its own analysis.
fn renamed(&mut self, target: &Target, new_name: &str) -> Option<Renamed> {
let semantics = &self.analysis(target.file)?.semantics;
let symbol = semantics.symbol(target.symbol)?;
let mut scope = semantics.scope(symbol.scope);
let mut top = true;
let home = loop {
let Some(here) = scope else { break Home::Elsewhere };
let owner = here.owner.and_then(|o| semantics.symbol(o)).map(|o| o.name.clone());
match (here.kind, owner) {
(ScopeKind::Module, Some(name)) => break Home::Module { name, top },
(ScopeKind::Package, Some(name)) => break Home::Package(name),
(ScopeKind::Generate | ScopeKind::Block, _) => {}
_ => break Home::Elsewhere,
}
top = false;
scope = here.parent.and_then(|p| semantics.scope(p));
};
Some(Renamed {
old: target.name.clone(),
new: new_name.to_string(),
file: target.file,
symbol: target.symbol,
kind: symbol.kind,
home,
})
}
/// Direction one: every instance of the module whose port is renamed.
fn port_users(&mut self, walk: &mut Walk, module: &str) -> Result<(), String> {
let ours = self.unique_module(module).is_some_and(|file| file == walk.renamed.file);
let old = [walk.renamed.old.as_str()];
for i in 0..self.len() {
let wanted =
|text: &&str| contains_word(text, module) && may_connect_implicitly(text, &old);
let Some(text) = self.text(i).filter(wanted) else { continue };
let (tree, _) = parse_source_tolerant(text);
for site in sites(&tree.items).iter().filter(|s| s.instantiation.module == module) {
self.port_site(walk, i, text, site, ours)?;
}
}
Ok(())
}
/// One instance of the module whose port `p` becomes `q`.
fn port_site(
&mut self,
walk: &mut Walk,
file: usize,
text: &str,
site: &Site,
ours: bool,
) -> Result<(), String> {
let (old, new) = (walk.renamed.old.as_str(), walk.renamed.new.as_str());
let here = self.describe(file, text, site);
unreadable_elements(site, old, new, &here)?;
if let Some(c) = site.named(old) {
let edited = walk
.occurrences
.iter()
.any(|(f, edits)| *f == file && edits.iter().any(|e| e.range == c.name_span));
if c.expr.is_some() || !edited {
return Ok(());
}
if site.bind_target().is_err() {
return Err(hierarchical_bind(&here, old));
}
let written = connection(new, old);
walk.push(file, vec![shorthand_tail(c.name_span.end, new, old)]);
walk.out.warnings.push(format!(
"{here} connected `{old}` by the shorthand `.{old}`; wrote `{written}` so it still binds the same net."
));
return Ok(());
}
if !site.has_wildcard() {
return Ok(());
}
directives(site, &here)?;
if !ours {
return Err(wildcard_unreadable(&here, &site.instantiation.module, old));
}
match self.wildcard_sees(file, site, old, new, &here)? {
(true, _) => walk.append(file, text, site, &connection(new, old), &here, old),
(false, true) => Err(captured(&here, new)),
(false, false) => Ok(()),
}
}
/// Whether a `.*` at `site` binds something named `old`, and whether it
/// would bind something named `new` — what decides between adding
/// `.new(old)`, refusing, and leaving the wildcard alone.
fn wildcard_sees(
&mut self,
file: usize,
site: &Site,
old: &str,
new: &str,
here: &str,
) -> Result<(bool, bool), String> {
match site.bind_target() {
Ok(None) => {
let Some(analysis) = self.analysis(file) else { return Ok((false, false)) };
let semantics = &analysis.semantics;
let offset = site.instance.name_span.start;
let binds = |name| {
let found = nearest(semantics, offset, name).and_then(|s| semantics.symbol(s));
found.is_some_and(|s| binds_implicitly(s.kind))
};
Ok((binds(old), binds(new)))
}
Ok(Some(target)) => {
if self.unique_module(target).is_none() {
return Err(bind_unreadable(here, target));
}
let binds = |name| {
let defs = self.index.member_in(target, name, Surface::Hierarchical);
defs.iter().any(|d| binds_implicitly(d.kind))
};
Ok((binds(old), binds(new)))
}
Err(()) => Err(hierarchical_bind(here, old)),
}
}
/// Direction two: every instance whose implicit connections can see the
/// renamed declaration under its old name.
fn signal_users(&mut self, walk: &mut Walk) -> Result<(), String> {
let renamed = walk.renamed;
if !binds_implicitly(renamed.kind) {
return Ok(());
}
let (file, symbol, old) = (renamed.file, renamed.symbol, renamed.old.as_str());
let rewrite = !matches!(renamed.home, Home::Package(_));
if let Some(text) = self.text(file).filter(|text| may_connect_implicitly(text, &[old])) {
let (tree, _) = parse_source_tolerant(text);
for site in sites(&tree.items).iter().filter(|s| s.bind.is_none()) {
if self.nearest_at(file, site, old) == Some(symbol) {
self.signal_site(walk, file, text, site, rewrite)?;
}
}
}
match &renamed.home {
Home::Module { name, top: true } => self.binds_into(walk, name, rewrite),
Home::Package(name) => self.importers(walk, name),
_ => Ok(()),
}
}
/// The nearest declaration of `name` where `site`'s implicit connections
/// bind, for an ordinary instantiation in `file`.
fn nearest_at(&mut self, file: usize, site: &Site, name: &str) -> Option<SymbolId> {
let analysis = self.analysis(file)?;
nearest(&analysis.semantics, site.instance.name_span.start, name)
}
/// The `bind` directives that bind into module `module`, whose connections
/// see its own top-level declarations — and the ones whose target lucisv
/// cannot name, which might.
fn binds_into(&mut self, walk: &mut Walk, module: &str, rewrite: bool) -> Result<(), String> {
let old = [walk.renamed.old.as_str()];
for i in 0..self.len() {
let wanted =
|text: &&str| contains_word(text, "bind") && may_connect_implicitly(text, &old);
let Some(text) = self.text(i).filter(wanted) else { continue };
let (tree, _) = parse_source_tolerant(text);
for site in sites(&tree.items).iter().filter(|s| s.bind.is_some()) {
match self.bind_reaches(i, site, module) {
Reach::Module => self.signal_site(walk, i, text, site, rewrite)?,
Reach::Maybe => self.signal_site(walk, i, text, site, false)?,
Reach::Elsewhere => {}
}
}
}
Ok(())
}
/// Whether a `bind`'s connections see `module`'s own scope.
///
/// A lone target is a module name or an **instance** name (IEEE 1800
/// §23.11). A module lucisv indexes is that module; otherwise the index's
/// instantiation edges say which modules own an instance of that name
/// (QA M3.5 finding 2: `bind i_nopass1 … (.clk_i, …)` into a
/// `prim_fifo_sync` refused `clk_i` renames of every other module). Owned
/// by other modules only — elsewhere; owned by nobody lucisv indexes, or by
/// `module` itself — maybe, which refuses what it would bind: the verifier
/// cannot name an instance's scope, so a rewrite there would be refused
/// anyway, and saying so up front is the clearer sentence.
fn bind_reaches(&self, file: usize, site: &Site, module: &str) -> Reach {
let target = match site.bind_target() {
Ok(Some(target)) => target,
Ok(None) => return Reach::Elsewhere,
Err(()) => return Reach::Maybe,
};
if target == module {
return Reach::Module;
}
if !self.index.units(target).is_empty() {
return Reach::Elsewhere;
}
let owners = self.instance_owners(file, site, target);
match owners.is_empty() || owners.contains(&module) {
true => Reach::Maybe,
false => Reach::Elsewhere,
}
}
/// The modules an instance named `target` instantiates, as a `bind`
/// written at `site` sees them. A bare instance name is found by upward
/// name resolution from the bind's own scope (§23.11), so the instances
/// the **enclosing module** declares answer first — `bind dut … (.*)` in
/// sram_ctrl's bench means that bench's `dut`, not entropy_src's — and
/// only when it declares none does every instance of that name count.
fn instance_owners(&self, file: usize, site: &Site, target: &str) -> Vec<&str> {
let here = self.file_id(file);
let at = site.instance.span.start;
let named = |edge: &vlog_semantic::InstantiationEdge| {
edge.instances.iter().any(|instance| instance.name == target)
};
let enclosing = |edge: &vlog_semantic::InstantiationEdge| {
Some(edge.file) == here && edge.owner.span.contains(at)
};
// Keyed by the module *instantiated*, which is what the bind reaches.
let mut local: Vec<&str> = Vec::new();
let mut anywhere: Vec<&str> = Vec::new();
for (instantiated, edges) in self.index.instantiations() {
if edges.iter().any(|edge| named(edge) && enclosing(edge)) {
local.push(instantiated);
}
if edges.iter().any(named) {
anywhere.push(instantiated);
}
}
if local.is_empty() {
anywhere
} else {
local
}
}
/// The instances that may see a package's declaration through an import:
/// any instance, in a file naming the package, that declares nothing of
/// that name itself. lucisv does not follow imports into `.*`, so these are
/// refused rather than rewritten.
fn importers(&mut self, walk: &mut Walk, package: &str) -> Result<(), String> {
let old = walk.renamed.old.as_str();
for i in 0..self.len() {
let wanted =
|text: &&str| contains_word(text, package) && may_connect_implicitly(text, &[old]);
let Some(text) = self.text(i).filter(wanted) else { continue };
let (tree, _) = parse_source_tolerant(text);
for site in sites(&tree.items).iter() {
if site.bind.is_some() || self.nearest_at(i, site, old).is_none() {
self.signal_site(walk, i, text, site, false)?;
}
}
}
Ok(())
}
/// One instance whose implicit connections see the renamed declaration.
/// `rewrite` is false where lucisv can only refuse what it finds.
fn signal_site(
&mut self,
walk: &mut Walk,
file: usize,
text: &str,
site: &Site,
rewrite: bool,
) -> Result<(), String> {
let renamed = walk.renamed;
let (old, new) = (renamed.old.as_str(), renamed.new.as_str());
let here = self.describe(file, text, site);
unreadable_elements(site, old, new, &here)?;
if let Some(c) = site.named(old).filter(|c| c.expr.is_none()) {
if !rewrite {
return Err(cannot_rewrite(&here, old, &format!(".{old}")));
}
let written = connection(old, new);
walk.push(file, vec![shorthand_tail(c.name_span.end, old, new)]);
walk.out.warnings.push(format!(
"{here} connected `{old}` by the shorthand `.{old}`; wrote `{written}`."
));
}
if !site.has_wildcard() {
return Ok(());
}
directives(site, &here)?;
let module = site.instantiation.module.clone();
let ports = match walk.ports_of(self, &module) {
Ok(ports) => ports,
Err(why) => return Err(wildcard_problem(&here, &module, old, why)),
};
let declares = |name: &str| ports.iter().any(|port| port == name);
if declares(new) && site.named(new).is_none() {
return Err(captured(&here, new));
}
if !declares(old) || site.named(old).is_some() {
return Ok(());
}
if !rewrite {
return Err(cannot_rewrite(&here, old, ".*"));
}
walk.append(file, text, site, &connection(old, new), &here, old)
}
/// The one in-scope file declaring module `name`, if exactly one does.
fn unique_module(&self, name: &str) -> Option<usize> {
let defs: Vec<_> =
self.index.units(name).iter().filter(|def| def.kind.is_instantiable()).collect();
let [def] = defs.as_slice() else { return None };
self.index.path(def.file).and_then(|path| self.index_of(path))
}
/// The declared ports of module `name`, read from its declaring file.
fn read_ports(&self, name: &str) -> Ports {
let count = self.index.units(name).iter().filter(|d| d.kind.is_instantiable()).count();
if count > 1 {
return Err(TWICE);
}
let file = self.unique_module(name).ok_or(UNREADABLE)?;
let text = self.text(file).ok_or(UNREADABLE)?;
let (tree, _) = parse_source_tolerant(text);
let (module, _) = crate::ports::find_module(&tree, name).ok_or(UNREADABLE)?;
if !module.port_directives.is_empty() {
return Err(DIRECTIVES);
}
let names = match &module.ports {
PortList::Ansi(ports) => ports.iter().map(|p| p.ok().map(|p| p.name.clone())).collect(),
PortList::NonAnsi(ports) => {
ports.iter().map(|p| p.ok().map(|p| p.name.clone())).collect()
}
PortList::Empty | PortList::None => Some(Vec::new()),
};
names.ok_or(UNREADABLE)
}
/// "`u_leaf` at top.sv:12", the way every sentence here names an instance.
fn describe(&self, file: usize, text: &str, site: &Site) -> String {
let path = self.path(file).map(display).unwrap_or_default();
let line = LineIndex::new(text).line_col(site.instance.name_span.start).0;
format!("`{}` at {path}:{line}", site.instance.name)
}
}
impl Walk<'_> {
/// Record insertions into one file.
fn push(&mut self, file: usize, edits: Vec<TextEdit>) {
match self.out.edits.iter_mut().find(|(f, _)| *f == file) {
Some((_, existing)) => existing.extend(edits),
None => self.out.edits.push((file, edits)),
}
}
/// Append `element` to `site`'s connection list, and say so.
fn append(
&mut self,
file: usize,
text: &str,
site: &Site,
element: &str,
here: &str,
old: &str,
) -> Result<(), String> {
let Some(edits) = append(text, site.conns, element) else {
return Err(format!(
"lucisv cannot find where {here}'s connection list ends; it made no edits."
));
};
self.push(file, edits);
self.out.warnings.push(format!("{here} bound `{old}` through `.*`; added `{element}`."));
Ok(())
}
/// A module's ports, read once per walk.
fn ports_of(&mut self, scope: &Scope, module: &str) -> Ports {
self.ports.entry(module.to_string()).or_insert_with(|| scope.read_ports(module)).clone()
}
}
/// The rename's own edits and the implicit-connection insertions, as one
/// sorted edit list per file. Two insertions at one offset would be two
/// rewrites of one place, which no correct plan makes, so that is a refusal.
pub(super) fn combine(
mut renamed: Vec<(usize, Vec<TextEdit>)>,
inserted: Vec<(usize, Vec<TextEdit>)>,
) -> Result<Vec<(usize, Vec<TextEdit>)>, String> {
for (file, edits) in inserted {
match renamed.iter_mut().find(|(f, _)| *f == file) {
Some((_, existing)) => existing.extend(edits),
None => renamed.push((file, edits)),
}
}
renamed.sort_by_key(|(file, _)| *file);
for (_, edits) in &mut renamed {
edits.sort_by_key(|e| (e.range.start, e.range.end));
let clash = edits.windows(2).any(|pair| match pair {
[a, b] => b.range.start < a.range.end || (a.range.is_empty() && a.range == b.range),
_ => false,
});
if clash {
return Err("two rewrites of one connection overlap; the rename was abandoned.".into());
}
}
Ok(renamed)
}
/// The verified edits as the caller receives them: an insertion written right
/// where a replacement ends becomes part of it, so `.p` → `.q` plus `(p)` is
/// the one edit `.q(p)`. The applied text is the same either way.
pub(super) fn fuse(edits: Vec<TextEdit>) -> Vec<TextEdit> {
let mut out: Vec<TextEdit> = Vec::with_capacity(edits.len());
for edit in edits {
match out.last_mut() {
Some(last)
if edit.range.is_empty()
&& !last.range.is_empty()
&& last.range.end == edit.range.start =>
{
last.new_text.push_str(&edit.new_text)
}
_ => out.push(edit),
}
}
out
}
/// Refuse a list holding text a tolerant parse could not read, when that text
/// could be an implicit connection of either name.
fn unreadable_elements(site: &Site, old: &str, new: &str, here: &str) -> Result<(), String> {
let hides = |raw: &str| contains_word(raw, old) || contains_word(raw, new) || raw.contains('*');
match site.unreadable().any(hides) {
true => Err(format!(
"{here}'s connection list holds text lucisv could not parse, so it cannot tell whether it binds `{old}` implicitly; the rename was abandoned."
)),
false => Ok(()),
}
}
/// Refuse a `.*` list split by compiler directives: which ports it binds
/// depends on the configuration.
fn directives(site: &Site, here: &str) -> Result<(), String> {
match site.instance.conn_directives.is_empty() {
true => Ok(()),
false => Err(format!(
"{here}'s connection list is split by compiler directives, so which ports its `.*` binds depends on the configuration; lucisv does not preprocess, so the rename was abandoned."
)),
}
}
const UNREADABLE: &str = "unreadable";
const TWICE: &str = "twice";
const DIRECTIVES: &str = "directives";
fn wildcard_problem(here: &str, module: &str, old: &str, why: &str) -> String {
match why {
TWICE => format!(
"{here} connects with `.*` to `{module}`, which is declared in more than one indexed file, so lucisv cannot tell whether `{old}` is bound implicitly; the rename was abandoned."
),
DIRECTIVES => format!(
"{here} connects with `.*` to `{module}`, whose port list carries compiler directives, so whether `{old}` is bound implicitly depends on the configuration; the rename was abandoned."
),
_ => wildcard_unreadable(here, module, old),
}
}
fn wildcard_unreadable(here: &str, module: &str, old: &str) -> String {
format!(
"{here} connects with `.*` to `{module}`, which lucisv cannot read, so it cannot tell whether `{old}` is bound implicitly; the rename was abandoned."
)
}
fn bind_unreadable(here: &str, target: &str) -> String {
format!(
"{here} is bound into `{target}`, which lucisv cannot read, so it cannot tell what its `.*` binds; the rename was abandoned."
)
}
fn hierarchical_bind(here: &str, old: &str) -> String {
format!(
"{here} is bound into a hierarchical `bind` target, whose scope lucisv cannot name, so it cannot tell what `{old}` binds there implicitly; the rename was abandoned."
)
}
fn captured(here: &str, new: &str) -> String {
format!(
"{here} connects with `.*`, which would start binding `{new}` to the renamed declaration; the rename was abandoned."
)
}
fn cannot_rewrite(here: &str, old: &str, how: &str) -> String {
format!(
"{here} may bind `{old}` implicitly through `{how}`, from a scope lucisv cannot tie to the renamed declaration (a package import, or a `bind` target it cannot name); the rename was abandoned."
)
}
+184
View File
@@ -0,0 +1,184 @@
//! The text a rewritten implicit connection is spelled with, and where it is
//! written: a `(net)` after a `.name` shorthand, or a whole `.port(net)`
//! appended to a connection list that uses `.*`.
//!
//! Text-level, and only ever an **insertion** — nothing the source wrote is
//! replaced, so no comment can be lost and the verifier's piece check sees
//! exactly the tokens written here and nothing else move.
//!
//! The appending rule is `ports::list::append_to_list`'s, restated here
//! because that one is private to the port refactorings (see the feature
//! README's Handshakes): the list's own layout is kept — one element per line
//! stays one per line at the last element's indentation, an inline list stays
//! inline — and when the last element carries a `//` comment the comma goes
//! before the comment and the new element on the next line, because a `,`
//! written after `//` is a `,` inside a comment. The newline is the list's
//! own, so a CRLF file stays CRLF.
use vlog_parser::ast::{Connection, ListElem};
use vlog_parser::span::TextRange;
use crate::TextEdit;
/// `name`, followed by the blank an escaped identifier needs to end: an
/// escaped identifier runs to the next whitespace, so `\a-b(x)` would be one
/// token swallowing the parenthesis (IEEE 1800 §5.6.1).
fn spelled(name: &str) -> String {
match name.starts_with('\\') {
true => format!("{name} "),
false => name.to_string(),
}
}
/// `.port(net)`, as a connection lucisv writes it.
pub(super) fn connection(port: &str, net: &str) -> String {
format!(".{}({})", spelled(port), spelled(net))
}
/// The insertion that turns the shorthand `.written` into `.written(net)`,
/// where `written` is what the port name will spell once the rename's own
/// edits are applied (it decides whether a blank must separate the two).
pub(super) fn shorthand_tail(name_end: u32, written: &str, net: &str) -> TextEdit {
let gap = if written.starts_with('\\') { " " } else { "" };
insert(name_end, format!("{gap}({})", spelled(net)))
}
/// The insertions that append `element` after the last element of a
/// connection list, or `None` when the list has no element to append after.
pub(super) fn append(
text: &str,
conns: &[ListElem<Connection>],
element: &str,
) -> Option<Vec<TextEdit>> {
let spans: Vec<TextRange> = conns
.iter()
.map(|e| match e {
ListElem::Ok(c) => c.span,
ListElem::Error(raw) => raw.span,
})
.collect();
let last = *spans.last()?;
let first = *spans.first()?;
let gap_from = match spans.len() {
1 => text.get(..first.start as usize)?.rfind('(')? as u32,
n => spans.get(n - 2)?.end,
};
let gap = text.get(gap_from as usize..last.start as usize)?;
let newline = if gap.contains("\r\n") { "\r\n" } else { "\n" };
let indent = line_indent(text, last.start);
let (at, line_comment) = after_same_line_comments(text, last.end);
Some(match (line_comment, gap.contains('\n')) {
(true, _) => vec![
insert(last.end, ",".to_string()),
insert(at, format!("{newline}{indent}{element}")),
],
(false, true) => vec![insert(at, format!(",{newline}{indent}{element}"))],
(false, false) => vec![insert(at, format!(", {element}"))],
})
}
fn insert(at: u32, text: String) -> TextEdit {
TextEdit { range: TextRange::empty(at), new_text: text }
}
/// Where an append writes once the comments written after the last element
/// on its own line are stepped over, and whether the last of them is a `//`
/// comment (whose end is the line break, before a CRLF's `\r`).
fn after_same_line_comments(text: &str, end: u32) -> (u32, bool) {
let mut at = end as usize;
loop {
let Some(rest) = text.get(at..) else { return (at as u32, false) };
let blanks = rest.len() - rest.trim_start_matches([' ', '\t']).len();
let rest = &rest[blanks..];
if rest.starts_with("//") {
let line = rest.find('\n').unwrap_or(rest.len());
let line = match rest[..line].ends_with('\r') {
true => line - 1,
false => line,
};
return ((at + blanks + line) as u32, true);
}
if !rest.starts_with("/*") {
return (at as u32, false);
}
match rest.find("*/") {
Some(close) if !rest[..close].contains('\n') => at += blanks + close + 2,
_ => return (at as u32, false),
}
}
}
/// The blanks the line holding `offset` starts with, or nothing when
/// `offset` is not the first thing written on its line.
fn line_indent(text: &str, offset: u32) -> String {
let offset = offset as usize;
let start = text.get(..offset).map_or(0, |before| before.rfind('\n').map_or(0, |n| n + 1));
let Some(head) = text.get(start..offset) else { return String::new() };
match head.chars().all(|c| c == ' ' || c == '\t') {
true => head.to_string(),
false => String::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::ast::{Connections, ItemKind};
use vlog_parser::parse_source_tolerant;
/// The one instance in `module m; … endmodule`, appended to.
fn appended(body: &str, element: &str) -> String {
let text = format!("module m;\n{body}\nendmodule\n");
let (tree, _) = parse_source_tolerant(&text);
let Some(ItemKind::Module(module)) = tree.items.first().map(|i| &i.kind) else {
panic!("a module")
};
let conns = module
.items
.iter()
.find_map(|item| match &item.kind {
ItemKind::Instantiation(inst) => match &inst.instances[0].conns {
Connections::Named(conns) => Some(conns),
Connections::Ordered(_) => None,
},
_ => None,
})
.expect("a named list");
let edits = append(&text, conns, element).expect("an append");
crate::apply(&text, &edits)
}
#[test]
fn an_inline_list_stays_inline() {
assert!(appended(" c u (.*);", ".d(x)").contains(" c u (.*, .d(x));"));
assert!(appended(" c u (.a(b), .* /* all */);", ".d(x)")
.contains("(.a(b), .* /* all */, .d(x));"));
}
#[test]
fn a_list_one_per_line_gets_its_own_line_at_the_same_indent() {
let out = appended(" c u (\n .a(b),\n .*\n );", ".d(x)");
assert!(out.contains(" .*,\n .d(x)\n );"), "{out}");
let lone = appended(" c u (\n .*\n );", ".d(x)");
assert!(lone.contains(" .*,\n .d(x)\n );"), "{lone}");
}
#[test]
fn a_line_comment_after_the_last_element_keeps_the_comma_out_of_it() {
let out = appended(" c u (\n .* // everything\n );", ".d(x)");
assert!(out.contains(" .*, // everything\n .d(x)\n );"), "{out}");
}
#[test]
fn a_crlf_list_stays_crlf() {
let out = appended(" c u (\r\n .* // all\r\n );", ".d(x)");
assert!(out.contains(" .*, // all\r\n .d(x)\r\n );"), "{out:?}");
}
#[test]
fn an_escaped_name_is_terminated() {
assert_eq!(connection("\\a-b", "c"), ".\\a-b (c)");
assert_eq!(shorthand_tail(5, "\\q", "\\p").new_text, " (\\p )");
assert_eq!(shorthand_tail(5, "q", "p").new_text, "(p)");
}
}
+17 -5
View File
@@ -9,10 +9,16 @@
//! This file is the rename itself: the entry points, the new-name check, the
//! walk from a cursor to the declaration it means, the occurrences of that
//! declaration, and the refusal sentences. `crate::scope` is the in-scope
//! workspace every refactoring in this crate reads through, and `warnings` is
//! what a finished rename says about the occurrences it could not edit.
//! workspace every refactoring in this crate reads through, `warnings` is
//! what a finished rename says about the occurrences it could not edit, and
//! `connections` (with `sites` and `layout`) rewrites the `.name` and `.*`
//! connections that bind the renamed name implicitly.
mod connections;
use connections::{combine, fuse};
mod layout;
mod preflight;
pub(crate) mod sites;
#[cfg(test)]
mod tests;
mod warnings;
@@ -245,7 +251,12 @@ fn renaming(
if target.name == new_name {
return Err(already_named(new_name));
}
let edits = trace.edits.measure(|| scope.collect_edits(&target, new_name))?;
let edits = trace.edits.measure(|| {
let renamed = scope.collect_edits(&target, new_name)?;
let implicit = scope.implicit_connections(&target, new_name, &renamed)?;
Ok::<_, String>((combine(renamed, implicit.edits)?, implicit.warnings))
});
let (edits, rewrites) = edits?;
trace.edited = edits.len();
// Two disjoint fields of one trace: `verify` times the whole pass while
// `checks` is filled by its stages, so they are borrowed apart.
@@ -253,10 +264,11 @@ fn renaming(
verify.measure(|| check::verify(&mut scope, &edits, &target.name, new_name, checks))?;
let RenameTrace { warnings: stage, warning_scans, .. } = &mut *trace;
let warnings = stage.measure(|| scope.warnings(&target, &edits, warning_scans));
let mut warnings = stage.measure(|| scope.warnings(&target, &edits, warning_scans));
warnings.extend(rewrites);
let mut out: Vec<(PathBuf, Vec<TextEdit>)> = edits
.into_iter()
.filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), edits)))
.filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), fuse(edits))))
.collect();
out.sort_by(|a, b| a.0.cmp(&b.0));
Ok(RefactorEdit { edits: out, warnings, created: Vec::new() })
+253
View File
@@ -0,0 +1,253 @@
//! Where an implicit connection is written, and where its name binds.
//!
//! `.name` and `.*` (IEEE 1800 §23.3.2.3–4) connect a port to the same-named
//! declaration visible where the instance is written — or, for a `bind`, in
//! the target's scope (§23.11). The semantic layer records a reference for
//! the `.port` half of `.name` and nothing at all for the net half or for
//! `.*`, so nothing a reference walk sees says that renaming the net (or the
//! port) cuts the binding. This file is the AST walk both halves of the rename
//! read that from: the engine (`connections.rs`) to decide the rewrite, the
//! verifier (`check::implicit`) to print what every implicit binding names
//! before and after it.
use vlog_parser::ast::{
BindDirective, Connection, Connections, GenBlock, GenElse, Instance, Instantiation, Item,
ItemKind, ListElem,
};
use vlog_semantic::{Semantics, SymbolId, SymbolKind};
/// One instance with a **named** connection list, and the `bind` directive
/// it is written in, if it is one. A positional list has no implicit
/// connection, so it is not visited.
pub(crate) struct Site<'t> {
pub(crate) instantiation: &'t Instantiation,
pub(crate) instance: &'t Instance,
pub(crate) conns: &'t [ListElem<Connection>],
pub(crate) bind: Option<&'t BindDirective>,
}
impl<'t> Site<'t> {
/// The well-formed connections.
pub(crate) fn connections(&self) -> impl Iterator<Item = &'t Connection> {
self.conns.iter().filter_map(ListElem::ok)
}
/// True when the list writes `.*`.
pub(crate) fn has_wildcard(&self) -> bool {
self.connections().any(|c| c.name == "*")
}
/// The connection naming port `name` explicitly (`.name` or `.name(…)`).
pub(crate) fn named(&self, name: &str) -> Option<&'t Connection> {
self.connections().find(|c| c.name == name)
}
/// The raw text of every element a tolerant parse could not read.
pub(crate) fn unreadable(&self) -> impl Iterator<Item = &'t str> {
self.conns.iter().filter_map(|e| match e {
ListElem::Error(raw) => Some(raw.text.as_str()),
ListElem::Ok(_) => None,
})
}
/// The module a `bind` binds into, when the target is one plain name —
/// the only target whose scope lucisv can name without elaborating.
/// `Err(())` for a hierarchical or indexed target; `Ok(None)` for an
/// ordinary instantiation.
pub(crate) fn bind_target(&self) -> Result<Option<&'t str>, ()> {
match self.bind.map(|b| b.target.as_slice()) {
None => Ok(None),
Some([only]) if only.index.is_none() => Ok(Some(only.name.as_str())),
Some(_) => Err(()),
}
}
}
/// Every instance with a named connection list in `items`: modules,
/// packages, generate regions and blocks, and `bind` directives.
pub(crate) fn sites(items: &[Item]) -> Vec<Site<'_>> {
let mut out = Vec::new();
walk(items, &mut out);
out
}
fn walk<'t>(items: &'t [Item], out: &mut Vec<Site<'t>>) {
for item in items {
match &item.kind {
ItemKind::Instantiation(inst) => push(inst, None, out),
ItemKind::Bind(bind) => push(&bind.inst, Some(bind), out),
ItemKind::Module(module) => walk(&module.items, out),
ItemKind::Package { items, .. } => walk(items, out),
ItemKind::GenerateRegion { items, .. } => walk(items, out),
ItemKind::GenBlock(block) => walk(&block.items, out),
ItemKind::GenIf(gen) => {
walk_block(&gen.then, out);
let mut els = gen.els.as_deref();
while let Some(next) = els {
match next {
GenElse::If(_, gen) => {
walk_block(&gen.then, out);
els = gen.els.as_deref();
}
GenElse::Block(block) => {
walk_block(block, out);
els = None;
}
}
}
}
ItemKind::GenFor(gen) => walk_block(&gen.body, out),
ItemKind::GenCase(gen) => gen.items.iter().for_each(|arm| walk_block(&arm.body, out)),
_ => {}
}
}
}
fn walk_block<'t>(block: &'t GenBlock, out: &mut Vec<Site<'t>>) {
walk(&block.items, out);
}
fn push<'t>(inst: &'t Instantiation, bind: Option<&'t BindDirective>, out: &mut Vec<Site<'t>>) {
for instance in &inst.instances {
if let Connections::Named(conns) = &instance.conns {
out.push(Site { instantiation: inst, instance, conns, bind });
}
}
}
/// Whether `.name` or `.*` can bind a declaration of this kind: a net, a
/// variable, a port of the enclosing module (the reading `ports/expand.rs`
/// uses), and an instance — an interface instance is what a `.*` binds an
/// interface port to, and writing a module instance's connection out
/// explicitly is exactly as wrong as the implicit one was. Anything else (a
/// parameter, a type, a module) is never bound, whatever its name.
pub(crate) fn binds_implicitly(kind: SymbolKind) -> bool {
matches!(kind, SymbolKind::Net | SymbolKind::Var | SymbolKind::Port | SymbolKind::Instance)
}
/// The declaration a lookup of `name` finds from the innermost scope covering
/// `offset`, walking outwards — what `.name` and `.*` bind to at an instance
/// written there. The nearest declaration wins whatever its kind; the caller
/// judges the kind.
///
/// Local scopes only: a name a `.*` could only reach through a package import
/// is not seen (the README's Assumptions say what that costs).
pub(crate) fn nearest(semantics: &Semantics, offset: u32, name: &str) -> Option<SymbolId> {
let scopes = semantics.scopes();
let mut best: Option<usize> = None;
for (i, scope) in scopes.iter().enumerate() {
if !scope.span.contains(offset) {
continue;
}
let better = best.is_none_or(|b| {
scopes.get(b).is_some_and(|current| scope.span.len() <= current.span.len())
});
if better {
best = Some(i);
}
}
let mut at = best;
while let Some(i) = at {
let current = scopes.get(i)?;
if let Some(symbol) = current.lookup_local(name) {
return Some(symbol);
}
at = current.parent.map(|p| p.0 as usize);
}
None
}
/// Whether `text` could write an implicit connection naming one of `names`:
/// a `.` that starts a list element (see [`opens_an_element`]) followed —
/// past blanks and comments — by `*` or by one of the names as a whole word.
/// A cheap superset of the parse that answers it exactly, so the engine and
/// the verifier parse only the files that pass; a hierarchical `u_x.d` is
/// not a connection and does not pass.
pub(crate) fn may_connect_implicitly(text: &str, names: &[&str]) -> bool {
let bytes = text.as_bytes();
let mut from = 0usize;
while let Some(hit) = text.get(from..).and_then(|rest| rest.find('.')) {
let dot = from + hit;
from = dot + 1;
if !opens_an_element(text, dot) {
continue;
}
let after = skip_trivia(text, dot + 1);
let rest = text.get(after..).unwrap_or("");
if rest.starts_with('*') {
return true;
}
let names_it = |name: &&str| {
let end = after + name.len();
let whole = !bytes.get(end).is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
!name.is_empty() && rest.starts_with(*name) && whole
};
if names.iter().any(names_it) {
return true;
}
}
false
}
/// Whether the `.` at `dot` may begin an element of a connection list: the
/// last thing before it, past blanks and block comments, is `(`, `,` or the
/// `*)` of an attribute — or a line lucisv does not read backwards (one
/// holding a `//` comment, or a compiler directive), which is let through,
/// because a superset is what the prefilter promises.
fn opens_an_element(text: &str, dot: usize) -> bool {
let mut end = dot;
loop {
let Some(before) = text.get(..end) else { return true };
let trimmed = before.trim_end();
if trimmed.ends_with("*/") {
match trimmed.rfind("/*") {
Some(open) => end = open,
None => return true,
}
continue;
}
let line_start = trimmed.rfind('\n').map_or(0, |n| n + 1);
let line = &trimmed[line_start..];
let crossed_a_line = before.get(trimmed.len()..).is_some_and(|gap| gap.contains('\n'));
if crossed_a_line && (line.contains("//") || line.trim_start().starts_with('`')) {
return true;
}
return trimmed.ends_with('(') || trimmed.ends_with(',') || trimmed.ends_with("*)");
}
}
/// The offset of the first byte at or after `at` that is neither blank nor
/// inside a comment.
fn skip_trivia(text: &str, mut at: usize) -> usize {
loop {
let Some(rest) = text.get(at..) else { return at };
let trimmed = rest.trim_start();
at += rest.len() - trimmed.len();
if trimmed.starts_with("//") {
at += trimmed.find('\n').unwrap_or(trimmed.len());
} else if trimmed.starts_with("/*") {
at += trimmed.find("*/").map_or(trimmed.len(), |end| end + 2);
} else {
return at;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_prefilter_sees_a_wildcard_and_a_shorthand_past_comments() {
assert!(may_connect_implicitly("u (. /* c */ *);", &["d"]));
assert!(may_connect_implicitly("u (.clk, .d);", &["d"]));
assert!(may_connect_implicitly("u (.\n // why\n d);", &["d"]));
assert!(may_connect_implicitly("u (.a(b), /* c */ .d);", &["d"]));
assert!(may_connect_implicitly("u (.a(b), // c\n .d);", &["d"]));
assert!(may_connect_implicitly("u (\n`ifdef A\n .*\n`endif\n);", &["d"]));
assert!(may_connect_implicitly("u ((* keep *) .d);", &["d"]));
assert!(!may_connect_implicitly("u (.dd(x), .e(d));", &["d"]));
assert!(!may_connect_implicitly("assign a = b.c;", &["d"]));
assert!(!may_connect_implicitly("assign w = u_sub.d;", &["d"]));
}
}