Files
lucisv/crates/vlog_linter/src/rules/instance_shadowing.rs
T
lucioandClaude Fable 5 cebeff45b4 Linter expansion, wave 1: severities end to end, per-rule editor toggles generated from the registry, and nineteen Error/Warning-class rules
TODO section 33. Every rule states a Severity (error: would likely fail
to compile or elaborate, or silently mis-synthesize; warning: a probable
bug; style), printed in lucisv check text and JSON, mapped to
ERROR/WARNING/INFORMATION in the editor, grouped in --rules-doc, and
accepted by --select/--ignore and [lint] as a class word. VS Code gains
lucisv.lint.severity.{error,warning,style} and one tri-state
lucisv.lint.rules.<rule> per rule (default/on/off - a client sends
every key, so a boolean cannot say unset), generated by
vlog_linter::vscode with a drift test, and lint::enabled_rules is the
one documented ladder: defaults -> select -> class switches -> per-rule
-> ignore. Nineteen new rules (17 -> 36), one file each with true
positives and near-misses: Error - mismatched-labels,
duplicate-declaration (Semantics::duplicates(), additive),
undeclared-identifier (with a project; silent for macro text, included
fragments, hierarchical tails, any name another file mentions),
unknown-port, unknown-parameter; Warning - forbid-defparam,
invalid-system-task-function, truncated-numeric-literal,
undersized-binary-literal (safe fix), suspicious-semicolon,
packed-dimensions-range-ordering, module-port, module-parameter,
explicit-function-task-parameter-type, plusarg-assignment,
instance-shadowing, forbid-negative-array-dim, void-cast,
incomplete-assignment. Every false-positive class found on opentitan
closed with a named test; 3 383 tests / 48 binaries; corpus 814/820
and byte-identical (formatter untouched); vsix smoke OK.

docs/features/linter-expansion-1/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 17:49:03 -07:00

205 lines
7.6 KiB
Rust

//! `instance-shadowing` — a declaration hiding one from an enclosing scope.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_semantic::{Scope, ScopeKind, Semantics, SymbolKind};
/// See [`Rule::doc`].
pub struct InstanceShadowing;
const NAME: &str = "instance-shadowing";
impl Rule for InstanceShadowing {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not hide an enclosing declaration with a new one of the same name"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A `logic count;` inside a `begin : blk` where the module already has \
a `count` compiles, and from then on every mention of `count` inside \
the block means the inner one — including the ones written before the \
inner declaration was added, which is how this arrives in a review \
diff that looks like it changed nothing. Verible's `instance-\
shadowing` (\"Warns if there are multiple declarations in the same \
scope that shadow each other with the same name.\") is the same rule; \
**lucisv turns it on by default where Verible ships it off**, because \
the finding is always worth a second look and the repair is a rename \
in one block.\n\n\
Only the scopes **inside one design unit** are compared: a module, a \
package or a class opens a fresh namespace, and a signal called `data` \
in two different modules shadows nothing. A generate scope is \
compared like any other block — the shadowing is real there too. No \
automatic fix: renaming reaches every use inside the block."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
// Shadowing is a claim about *which scope* a name was declared in,
// and error recovery moves declarations between scopes — so a file
// that did not fully parse gets no opinion, exactly as
// `duplicate-declaration` gives it none.
if !ctx.parsed_cleanly() {
return Vec::new();
}
let semantics = ctx.semantics();
let mut out = Vec::new();
for scope in semantics.scopes() {
if opens_a_unit(scope.kind) {
continue;
}
for &id in &scope.symbols {
let Some(symbol) = semantics.symbol(id) else { continue };
let Some(hidden) = shadowed(semantics, scope, &symbol.name) else { continue };
if !judged(symbol.kind) {
continue;
}
// The two are exclusive when a conditional-compilation
// directive stands between them, exactly as they are for
// `duplicate-declaration`.
if ctx.signals().conditional_between(&[hidden, symbol.name_span.start]) {
continue;
}
out.push(Violation::new(
NAME,
format!(
"`{}` shadows a declaration of the same name outside this scope",
symbol.name
),
symbol.name_span,
));
}
}
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The name span of the enclosing declaration `name` hides, if there is one
/// **within the same design unit**.
///
/// The walk stops at the scope that opens a unit — a module, package or class
/// body — because a name declared in a different unit is reached by a
/// qualified path, never by shadowing.
fn shadowed(semantics: &Semantics, scope: &Scope, name: &str) -> Option<u32> {
let mut parent = scope.parent;
while let Some(id) = parent {
let outer = semantics.scope(id)?;
if let Some(hidden) = outer.lookup_local(name) {
return semantics.symbol(hidden).map(|symbol| symbol.name_span.start);
}
if opens_a_unit(outer.kind) {
return None;
}
parent = outer.parent;
}
None
}
/// True for the scopes that open a design unit's own namespace.
fn opens_a_unit(kind: ScopeKind) -> bool {
matches!(kind, ScopeKind::File | ScopeKind::Module | ScopeKind::Package | ScopeKind::Class)
}
/// True for the declarations worth reporting.
///
/// A subroutine argument named after an enclosing signal is idiomatic
/// (`function automatic f(input logic clk)`), a block label is not a value,
/// and a `genvar` is scoped to its own loop by construction — so those stay
/// out. What is left is data and instances, which is where the surprise is.
fn judged(kind: SymbolKind) -> bool {
matches!(
kind,
SymbolKind::Net | SymbolKind::Var | SymbolKind::Instance | SymbolKind::LocalParam
)
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
InstanceShadowing.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_block_local_that_hides_a_module_signal() {
let src = "module m;\n\
logic count;\n\
always_comb begin : blk\n\
logic count;\n\
count = 1'b0;\n\
end\n\
endmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`count`"), "{}", found[0].message);
assert!(found[0].span.start as usize > src.find("blk").unwrap_or(0), "the inner one");
assert!(found[0].fix.is_none());
}
#[test]
fn a_name_declared_once_is_never_flagged() {
let src = "module m;\n\
logic count;\n\
always_comb begin : blk\n\
logic other;\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_different_unit_shadows_nothing() {
let src = "module a;\n logic data;\nendmodule\nmodule b;\n logic data;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
// Nor does a package-level name reached from a module.
let pkg = "package p;\n logic data;\nendpackage\nmodule m;\n logic data;\nendmodule\n";
assert!(violations(pkg).is_empty(), "{:?}", violations(pkg));
}
#[test]
fn a_generate_block_is_compared_like_any_other() {
let src = "module m;\n\
logic x;\n\
generate\n\
if (A) begin : g\n\
logic x;\n\
end\n\
endgenerate\n\
endmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_subroutine_argument_named_after_a_signal_is_idiomatic() {
let src = "module m;\n\
logic clk;\n\
function automatic void f(input logic clk);\n\
endfunction\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn conditional_arms_are_exclusive() {
let src = "module m;\n\
logic x;\n\
always_comb begin : blk\n\
`ifdef A\n\
logic x;\n\
`endif\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}