- L-1: an unowned block's closing label is a use of a same-named block only for block constructs and only when it spells the construct's own opening label (use_block_end_label); a mismatched `end : a` or an `endfunction : g` beside block `g` records nothing. - L-2: duplicate-declaration stays silent for two block labels only when both may be arms of one generate if/case; sibling `for` blocks and a procedural block beside a generate one are reported in either order. OpenTitan check: 1 158 findings, identical to 0.60.0. - L-3: a block comment between `.` and the name is still dotted. - L-4: a bind file that does not lex counts as binding (K2); a pasted fragment that does not lex is said, not skipped. - L-12: no unchecked slice in rename/arms.rs. - L-13: expand/ansi/inline/extract messages name files by Scope::name_of. 7 tests (L-3/L-4's fail with the fixes disabled). Per-crate suites under the guard: 80 suites, 5 085 passed, 0 failed, 51 ignored (one combined run was cut at 1 800 s in vlog_refactor/tests/corpus.rs with syspolicyd at 95 % — the §65.3 stall). Co-Authored-By: Claude Opus 5.5 <[email protected]>
406 lines
17 KiB
Rust
406 lines
17 KiB
Rust
//! Which of the rename's *text* warnings are about the renamed declaration
|
||
//! (TODO §65.1: the lead's inspection, QA's final pass H1–H4, rework 4's
|
||
//! K1–K3/N1–N3 and the corrected rulings, 2026-09-30).
|
||
//!
|
||
//! **The governing principle: scoping may drop a warning only when the
|
||
//! engine can show the spelling cannot reach the renamed declaration; any
|
||
//! doubt falls back to the unscoped behaviour — every spelling warned, as
|
||
//! before scoping existed.**
|
||
//!
|
||
//! Scoping applies only to a declaration that is a **member of a module or
|
||
//! interface** (a net, variable, parameter, port, instance, block, a
|
||
//! function- or task-local, an enum value written in a module) whose **home
|
||
//! set** (`home.rs`) is known. A declaration with no enclosing unit (a
|
||
//! fragment's or `$unit`'s own declaration — K1) and one whose home set holds
|
||
//! an include the engine cannot resolve (K3) are warned about unscoped.
|
||
//! When it applies:
|
||
//!
|
||
//! * a **bare** spelling (no `.` before it) in a macro argument or an
|
||
//! unstructured assertion is news in the declaring file and in a file the
|
||
//! rename edits when the scope lookup there (`sites::nearest`) finds the
|
||
//! declaration (N1 — another module's own `clk_i` is not); in a file pasted
|
||
//! into or around the declaring file always (no scope to look in — H1);
|
||
//! inside a `bind` into the declaring unit wherever it is written (H3);
|
||
//! in an argument the macro carries after a `.`, into a `bind` into the
|
||
//! unit or into a macro the set does not define, wherever it is written
|
||
//! (`carry.rs`, review H-1/H-2); elsewhere never;
|
||
//! * a **dotted** spelling (`… .state_q`) may be a hierarchical path and is
|
||
//! always news;
|
||
//! * a `` `define`` body is news when it is written in the home set, when its
|
||
//! macro is invoked from the home set — a file with a `bind` into the unit,
|
||
//! or invoking a macro that expands to one, counts (K2) — through other
|
||
//! bodies too (H2), when the macro itself expands to such a `bind`, or when
|
||
//! it spells the name dotted; a macro with a **parameter** named like the
|
||
//! declaration never is (N2: the body's spellings are the parameter);
|
||
//! * a bare use in the plain code of a pasted file is a use the engine
|
||
//! cannot edit, and is said (H4, `Scope::fragment_use_warnings`) — for
|
||
//! every renamed declaration, scoped or not.
|
||
//!
|
||
//! Anything else — a module, interface, package or class, a package's or
|
||
//! class's member — can be named bare from any file (an import, a `pkg::`, a
|
||
//! handle), and every spelling is reported as before.
|
||
|
||
use std::collections::HashSet;
|
||
|
||
use vlog_parser::span::TextRange;
|
||
use vlog_parser::token::{Token, TokenKind};
|
||
use vlog_semantic::{ScopeId, Semantics, SymbolId};
|
||
|
||
use super::carry::{Carriers, Defs, MacroDef};
|
||
use super::home::{home_of, invoked_from, macro_names, Home};
|
||
use super::sites::nearest;
|
||
use super::Target;
|
||
use crate::scope::Scope;
|
||
use crate::TextEdit;
|
||
|
||
/// What the text scans need to know about the renamed declaration.
|
||
pub(super) struct Scoping {
|
||
/// The module or interface the declaration is a member of.
|
||
unit: Option<String>,
|
||
/// Whether spellings may be dropped at all: a member (`unit`) whose home
|
||
/// set is known. `false` is the unscoped behaviour.
|
||
scoped: bool,
|
||
declaring: usize,
|
||
symbol: SymbolId,
|
||
name: String,
|
||
/// The home set (`home.rs`), plus the files holding a `bind` into the
|
||
/// unit (K2).
|
||
home: Home,
|
||
/// Every macro a home-set file invokes, through define bodies.
|
||
invoked: HashSet<String>,
|
||
/// The macros whose arguments reach the unit from any file, and those
|
||
/// expanding to a `bind` into it (`carry.rs`).
|
||
carriers: Carriers,
|
||
}
|
||
|
||
impl Scoping {
|
||
/// The rule for `target`, renamed by edits to `edited`.
|
||
pub(super) fn new(scope: &mut Scope, target: &Target, edited: Vec<usize>) -> Scoping {
|
||
let unit = scope
|
||
.analysis(target.file)
|
||
.and_then(|a| a.semantics.symbol(target.symbol).map(|s| (s.scope, &a.semantics)))
|
||
.and_then(|(declared_in, sem)| enclosing_unit(sem, declared_in));
|
||
let sources: Vec<_> =
|
||
(0..scope.len()).filter_map(|i| Some((scope.path(i)?, scope.text(i)?))).collect();
|
||
let mut home = home_of(&sources, target.file, &edited);
|
||
let scoped = unit.is_some() && !home.unknown;
|
||
let mut invoked = HashSet::new();
|
||
let mut carriers = Carriers::default();
|
||
if let (Some(unit), true) = (&unit, scoped) {
|
||
let defs = define_defs(scope);
|
||
carriers = Carriers::of(&defs, unit);
|
||
home.all.extend(files_binding_into(scope, unit, &carriers));
|
||
let texts: Vec<&str> = home.all.iter().filter_map(|&i| scope.text(i)).collect();
|
||
invoked = invoked_from(&texts, &defs);
|
||
}
|
||
Scoping {
|
||
unit,
|
||
scoped,
|
||
declaring: target.file,
|
||
symbol: target.symbol,
|
||
name: target.name.clone(),
|
||
home,
|
||
invoked,
|
||
carriers,
|
||
}
|
||
}
|
||
|
||
/// The module or interface the declaration is a member of, when spellings
|
||
/// are scoped to it.
|
||
pub(super) fn unit(&self) -> Option<&str> {
|
||
self.unit.as_deref().filter(|_| self.scoped)
|
||
}
|
||
|
||
/// The files the preprocessor pastes into or around the declaring file
|
||
/// (H4's fragments), each with whether the declaring file includes it
|
||
/// (`true`) or it is on the including side (`false`).
|
||
pub(super) fn pasted(&self) -> Vec<(usize, bool)> {
|
||
let included = self.home.included.iter().map(|&i| (i, true));
|
||
included.chain(self.home.around.iter().map(|&i| (i, false))).collect()
|
||
}
|
||
|
||
/// The declaring file's source index.
|
||
pub(super) fn declaring(&self) -> usize {
|
||
self.declaring
|
||
}
|
||
|
||
/// Whether a `` `define`` of macro `macro_name` in `file`, whose body
|
||
/// spells the name (`params`: its formal arguments), is news.
|
||
///
|
||
/// The unscoped fallback and a dotted spelling are news first; only then
|
||
/// may a parameter named like the declaration silence the body's bare
|
||
/// spellings (they are the parameter) — never a bare spelling in a
|
||
/// default argument (`default_bare`), which expands in the caller.
|
||
pub(super) fn keeps_define_body(
|
||
&self,
|
||
file: usize,
|
||
macro_name: &str,
|
||
params: &[String],
|
||
dotted: bool,
|
||
default_bare: bool,
|
||
) -> bool {
|
||
if !self.scoped || dotted {
|
||
return true;
|
||
}
|
||
let shadowed =
|
||
params.iter().any(|p| p.split('=').next().is_some_and(|p| p.trim() == self.name));
|
||
if shadowed && !default_bare {
|
||
return false;
|
||
}
|
||
self.home.all.contains(&file)
|
||
|| self.invoked.contains(macro_name)
|
||
|| self.carriers.binds(macro_name)
|
||
}
|
||
|
||
/// Whether argument `position` of an invocation of `macro_name` may
|
||
/// reach the declaration wherever it is written (`carry.rs`).
|
||
pub(super) fn carries(&self, macro_name: &str, position: usize) -> bool {
|
||
!self.scoped || self.carriers.carries(macro_name, position)
|
||
}
|
||
|
||
/// Whether a spelling in `file` — dotted or bare, at `offset` — is news.
|
||
pub(super) fn keeps(&self, scope: &Scope, file: usize, dotted: bool, offset: u32) -> bool {
|
||
!self.scoped || dotted || self.bare_is_news(scope, file, offset)
|
||
}
|
||
|
||
/// A bare spelling: in a pasted file always (no scope to look in); in the
|
||
/// declaring file and an edited file when the lookup there finds the
|
||
/// declaration — only the declaring file's own analysis can; elsewhere
|
||
/// never.
|
||
fn bare_is_news(&self, scope: &Scope, file: usize, offset: u32) -> bool {
|
||
if self.home.included.contains(&file) || self.home.around.contains(&file) {
|
||
return true;
|
||
}
|
||
if file != self.declaring {
|
||
return false;
|
||
}
|
||
let Some(analysis) = scope.cached(file) else { return true };
|
||
nearest(&analysis.semantics, offset, &self.name) == Some(self.symbol)
|
||
}
|
||
}
|
||
|
||
/// K2: every file holding a `bind` into `unit` (by name or by an instance
|
||
/// path), or invoking a macro that expands to one — home, so the macros it
|
||
/// invokes are followed.
|
||
fn files_binding_into(scope: &Scope, unit: &str, carriers: &Carriers) -> Vec<usize> {
|
||
(0..scope.len())
|
||
.filter(|&i| {
|
||
let Some(text) = scope.text(i) else { return false };
|
||
let invokes_binder = carriers.any_binder()
|
||
&& text.contains('`')
|
||
&& macro_names(text).iter().any(|m| carriers.binds(m));
|
||
if invokes_binder {
|
||
return true;
|
||
}
|
||
if !super::contains_word(text, "bind") {
|
||
return false;
|
||
}
|
||
// A file that spells `bind` but does not lex is counted (L-4).
|
||
vlog_parser::tokenize(text).map_or(true, |tokens| !binds_into(&tokens, unit).is_empty())
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
impl<'a> Scope<'a> {
|
||
/// H4: bare uses of the name in the plain code of a file the declaring
|
||
/// file includes (or that includes it). That text is analysed on its own,
|
||
/// outside the module's scope, so no reference there is the declaration's
|
||
/// and the rename cannot edit it: one warning per file, with its lines.
|
||
/// A use the rename does edit (`edits`: a cross-file reference the index
|
||
/// resolved, such as an instantiation of a renamed module) is not one.
|
||
pub(super) fn fragment_use_warnings(
|
||
&mut self,
|
||
scoping: &Scoping,
|
||
edits: &[(usize, Vec<TextEdit>)],
|
||
) -> Vec<String> {
|
||
let name = scoping.name.clone();
|
||
let declaring = self.name_at(scoping.declaring());
|
||
let mut out = Vec::new();
|
||
for (file, included) in scoping.pasted() {
|
||
let Some(text) = self.text(file) else { continue };
|
||
if !super::contains_word(text, &name) {
|
||
continue;
|
||
}
|
||
let shown = self.name_at(file);
|
||
let relation = match included {
|
||
true => format!("a file `{declaring}` includes"),
|
||
false => format!("a file that includes `{declaring}` or is included with it"),
|
||
};
|
||
// A fragment that does not lex cannot be scanned: say it spells
|
||
// the name rather than drop it (review L-4).
|
||
let tokens = vlog_parser::tokenize(text).ok();
|
||
let (Some(tokens), Some(analysis)) = (tokens, self.analysis(file)) else {
|
||
out.push(format!(
|
||
"{shown}: `{name}` is spelled in {relation}, which lucisv could not read, and was left unchanged."
|
||
));
|
||
continue;
|
||
};
|
||
let edited: Vec<TextRange> = edits
|
||
.iter()
|
||
.filter(|(i, _)| *i == file)
|
||
.flat_map(|(_, e)| e.iter().map(|e| e.range))
|
||
.collect();
|
||
let lines = bare_unbound_uses(&analysis.semantics, &tokens, &name, &edited);
|
||
if lines.is_empty() {
|
||
continue;
|
||
}
|
||
let at = lines.iter().map(u32::to_string).collect::<Vec<_>>().join(",");
|
||
out.push(format!(
|
||
"{shown}:{at}: `{name}` is used in {relation} and was left unchanged; lucisv does not rename inside `included text."
|
||
));
|
||
}
|
||
out
|
||
}
|
||
}
|
||
|
||
/// The lines of `name` tokens in one fragment's plain code that are a use no
|
||
/// declaration of that fragment answers: not a declaration, not after a `.`,
|
||
/// not a reference resolved inside the fragment itself, and not covered by
|
||
/// one of the rename's `edited` ranges in it.
|
||
fn bare_unbound_uses(
|
||
sem: &Semantics,
|
||
tokens: &[Token],
|
||
name: &str,
|
||
edited: &[TextRange],
|
||
) -> Vec<u32> {
|
||
let mut lines: Vec<u32> = Vec::new();
|
||
for (i, token) in tokens.iter().enumerate() {
|
||
if token.kind != TokenKind::Ident || token.text != name {
|
||
continue;
|
||
}
|
||
if i.checked_sub(1).and_then(|p| tokens.get(p)).is_some_and(|t| t.is_sym(".")) {
|
||
continue;
|
||
}
|
||
if sem.symbol_at(token.span.start).is_some() {
|
||
continue;
|
||
}
|
||
if edited.iter().any(|e| e.start <= token.span.start && token.span.end <= e.end) {
|
||
continue;
|
||
}
|
||
let local = sem.reference_at(token.span.start).is_some_and(|r| r.resolved().is_some());
|
||
if !local && lines.last() != Some(&token.line) {
|
||
lines.push(token.line);
|
||
}
|
||
}
|
||
lines
|
||
}
|
||
|
||
/// H3: the byte ranges of the `bind` statements in one file whose target is
|
||
/// `unit` — by name, or by an instance path, which lucisv cannot follow to a
|
||
/// unit and so counts — from `bind` to its `;`.
|
||
pub(super) fn binds_into(tokens: &[Token], unit: &str) -> Vec<TextRange> {
|
||
let mut out = Vec::new();
|
||
for (i, token) in tokens.iter().enumerate() {
|
||
// `bind` lexes as an identifier (it is not a reserved word of every
|
||
// standard the lexer serves); a `bind` statement starts with it.
|
||
if !(token.kind == TokenKind::Ident && token.text == "bind") {
|
||
continue;
|
||
}
|
||
let Some(target) = tokens.get(i + 1) else { continue };
|
||
let path = tokens.get(i + 2).is_some_and(|t| t.is_sym(".") || t.is_sym("["));
|
||
if target.text != unit && !path {
|
||
continue;
|
||
}
|
||
let Some(end) = tokens[i..].iter().find(|t| t.is_sym(";")) else { continue };
|
||
out.push(TextRange::new(token.span.start, end.span.end));
|
||
}
|
||
out
|
||
}
|
||
|
||
/// Macro name → every `` `define`` of it in the set.
|
||
fn define_defs(scope: &Scope) -> Defs {
|
||
let mut out = Defs::new();
|
||
for i in 0..scope.len() {
|
||
let Some(defines) = scope.file_id(i).and_then(|id| scope.index().defines(id)) else {
|
||
continue;
|
||
};
|
||
for define in defines.entries() {
|
||
let params = define.params.clone().unwrap_or_default();
|
||
let def = MacroDef { params, body: define.body.clone() };
|
||
out.entry(define.name.clone()).or_default().push(def);
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
/// The module or interface a declaration written in `scope` is a member of:
|
||
/// the first owned scope outward that is an instantiable unit's (a block,
|
||
/// function or task in between does not end the walk). A package, a class or
|
||
/// the file scope ends it with `None`.
|
||
fn enclosing_unit(sem: &Semantics, scope: ScopeId) -> Option<String> {
|
||
let mut here = Some(scope);
|
||
while let Some(id) = here {
|
||
let current = sem.scope(id)?;
|
||
if let Some(owner) = current.owner.and_then(|o| sem.symbol(o)) {
|
||
if owner.kind.is_instantiable() {
|
||
return Some(owner.name.clone());
|
||
}
|
||
if matches!(
|
||
owner.kind,
|
||
vlog_semantic::SymbolKind::Package | vlog_semantic::SymbolKind::Class
|
||
) {
|
||
return None;
|
||
}
|
||
}
|
||
here = current.parent;
|
||
}
|
||
None
|
||
}
|
||
|
||
/// The whole-word spellings of `name` in `text`: the byte offsets of the bare
|
||
/// ones, and whether any is dotted (a `.` before it, past blanks).
|
||
pub(super) fn spellings(text: &str, name: &str) -> (Vec<usize>, bool) {
|
||
let bytes = text.as_bytes();
|
||
let word = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'$';
|
||
let (mut bare, mut dotted) = (Vec::new(), false);
|
||
let mut from = 0;
|
||
while let Some(hit) = text.get(from..).and_then(|s| s.find(name)) {
|
||
let start = from + hit;
|
||
let end = start + name.len();
|
||
from = start + 1;
|
||
let glued = start.checked_sub(1).and_then(|p| bytes.get(p)).is_some_and(|&b| word(b))
|
||
|| bytes.get(end).is_some_and(|&b| word(b));
|
||
if glued {
|
||
continue;
|
||
}
|
||
match after_dot(&text[..start]) {
|
||
true => dotted = true,
|
||
false => bare.push(start),
|
||
}
|
||
}
|
||
(bare, dotted)
|
||
}
|
||
|
||
/// Whether `before` ends in a `.`, past blanks, `` `` `` pastes
|
||
/// (`` u_m.``sig `` pastes a path) and block comments (`u_m./*x*/sig`,
|
||
/// review L-3).
|
||
fn after_dot(before: &str) -> bool {
|
||
let mut rest = before.trim_end();
|
||
loop {
|
||
if let Some(shorter) = rest.strip_suffix("``") {
|
||
rest = shorter.trim_end();
|
||
} else if let Some(open) = rest.strip_suffix("*/").and_then(|r| r.rfind("/*")) {
|
||
rest = rest[..open].trim_end();
|
||
} else {
|
||
return rest.ends_with('.');
|
||
}
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn a_spelling_is_dotted_past_blanks_and_bare_otherwise() {
|
||
assert_eq!(spellings("x(state_q, a.state_q)", "state_q"), (vec![2], true));
|
||
assert_eq!(spellings("x(u . state_q)", "state_q"), (vec![], true));
|
||
assert_eq!(spellings("x(state_qq, my_state_q)", "state_q"), (vec![], false));
|
||
assert_eq!(spellings("u_m.``state_q", "state_q"), (vec![], true));
|
||
assert_eq!(spellings("pre``state_q", "state_q"), (vec![5], false));
|
||
assert_eq!(spellings("u_m./*x*/state_q", "state_q"), (vec![], true));
|
||
assert_eq!(spellings("u_m. /* c */ state_q", "state_q"), (vec![], true));
|
||
assert_eq!(spellings("/* a. */ state_q", "state_q"), (vec![9], false));
|
||
}
|
||
}
|