diff --git a/Cargo.lock b/Cargo.lock index 576fd40..3c4b2bc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -259,6 +259,7 @@ version = "0.4.2" dependencies = [ "vlog_formatter", "vlog_parser", + "vlog_semantic", ] [[package]] diff --git a/README.md b/README.md index 24e80c7..f802087 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,7 @@ a silently ignored `line_length` typo costs more than a strict parser does. ## Linting -`vfmt check` runs a set of syntactic lint rules over the same files `vfmt` +`vfmt check` runs a set of lint rules over the same files `vfmt` would format — same walk, same `--exclude`, same `.gitignore` handling, same `vfmt.toml` discovery. @@ -169,6 +169,18 @@ what it can see. | `explicit-parameter-storage-type` | — | `parameter int W = 8`, not `parameter W = 8` | | `module-filename` | — | a one-module file is named after its module | | `unused-waiver` | — | waivers that suppress nothing | +| `unused-signal` † | — | no net or variable nothing uses | +| `undriven-net` † | — | everything read is driven by something | +| `multiply-driven` † | — | one driver per variable | + +† Off by default — `--select` them. These three read the file's *symbol +table*, not just its syntax, which is what lets them tell one `count` from +another; they are off because a single-file analysis cannot see a signal used +from another file's hierarchy. See +`docs/features/semantic-lints/README.md`. The table above is not the whole +set — naming-style rules ship too, and +`cargo run -p vlog_linter --example rules_markdown` prints the generated +reference for every rule with its default. Fixes follow ruff's applicability model: `--fix` applies *safe* fixes (those that cannot change what the code means), `--unsafe-fixes` widens that — no diff --git a/TODO.md b/TODO.md index 30ef1eb..db1bd00 100644 --- a/TODO.md +++ b/TODO.md @@ -609,7 +609,7 @@ section only tracks the milestones. along the include graph. - [x] **M11 `hierarchy`** — module hierarchy both directions (who instantiates X / what X instantiates) over LSP callHierarchy. -- [ ] **M12 `semantic-lints`** — unused-signal, undriven-net, +- [x] **M12 `semantic-lints`** — unused-signal, undriven-net, multiply-driven: the first semantic lint rules on `vlog_semantic`. - [ ] **M13 `cli-filelist`** — `vfmt -f files.f` on the command line, reusing M1's parser; format/lint exactly the project's files. diff --git a/crates/vfmt_server/src/lint.rs b/crates/vfmt_server/src/lint.rs index 7efc649..aa20195 100644 --- a/crates/vfmt_server/src/lint.rs +++ b/crates/vfmt_server/src/lint.rs @@ -18,8 +18,14 @@ use crate::state::Document; /// tools" (`docs/features/one-parse/README.md`): the buffer was tokenized and /// tolerantly parsed once, in `Document::new`, and the lint pass reads those /// products instead of parsing the same text again. +/// +/// The symbol table goes the same way (`docs/features/semantic-lints/`): the +/// document is analyzed on every edit for hover, definition and references, so +/// the semantic rules must read *that* analysis rather than run a second one +/// per keystroke. fn context(doc: &Document) -> LintContext<'_> { LintContext::from_parse(&doc.text, &doc.tokens, &doc.tree, &doc.line_index, doc.path.clone()) + .with_semantics(&doc.semantics) } /// Every violation the default rules find in a buffer. @@ -193,6 +199,21 @@ mod tests { assert!(fixable(doc, 2).is_empty(), "and still not fixable"); } + #[test] + fn a_semantic_rule_reads_the_documents_own_analysis() { + // The rule is off by default, so this goes through `context()` + // directly — which is the point: the wiring must be in place before + // any semantic rule is ever selected here, so the server never + // analyzes a buffer twice per keystroke. + let (ws, uri) = doc_of("module m;\n wire spare;\nendmodule\n"); + let doc = ws.document(&uri).expect("open"); + let rule = vlog_linter::rule_by_name("unused-signal").expect("the rule exists"); + let found = vlog_linter::lint(&context(doc), &[rule]); + assert_eq!(found.len(), 1, "{found:#?}"); + assert!(found[0].message.contains("spare"), "{}", found[0].message); + assert!(std::ptr::eq(context(doc).semantics(), &doc.semantics), "the lent table"); + } + #[test] fn an_unfenced_file_offers_every_fix() { let (ws, uri) = doc_of("module m;\n// just a note\n\twire a;\nendmodule\n"); diff --git a/crates/vlog_linter/Cargo.toml b/crates/vlog_linter/Cargo.toml index 1e75f49..fb0347b 100644 --- a/crates/vlog_linter/Cargo.toml +++ b/crates/vlog_linter/Cargo.toml @@ -7,6 +7,11 @@ description = "Syntactic lint rules for Verilog/SystemVerilog, in the spirit of [dependencies] vlog_parser = { path = "../vlog_parser" } +# The semantic rules (unused-signal, undriven-net, multiply-driven) need the +# file's symbol table: which declaration a name means. `vlog_semantic` is the +# workspace crate that answers that, and it depends on `vlog_parser` alone, so +# this adds no external code — see docs/features/semantic-lints/README.md. +vlog_semantic = { path = "../vlog_semantic" } [dev-dependencies] # Tests only: the .lint case harness asserts that a lint fix never produces diff --git a/crates/vlog_linter/src/context.rs b/crates/vlog_linter/src/context.rs index 4708a00..33c701d 100644 --- a/crates/vlog_linter/src/context.rs +++ b/crates/vlog_linter/src/context.rs @@ -1,11 +1,15 @@ //! Everything a rule is given to look at: text, tokens, tree, positions. +use std::cell::OnceCell; use std::path::{Path, PathBuf}; use vlog_parser::ast::SourceFile; use vlog_parser::span::TextRange; use vlog_parser::token::{Comment, Token, TokenKind}; use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LexError, LineIndex}; +use vlog_semantic::{analyze, Semantics}; + +use crate::signals::Signals; /// The default tab stop used when a fix expands a tab, matching vfmt's /// default indent. `LintContext::with_tab_width` follows `--indent`. @@ -93,6 +97,18 @@ enum Backing<'a> { }, } +/// Where a context's symbol table comes from: lent by a caller that already +/// built one (the language server's document), or built here the first time a +/// rule asks for it. +/// +/// Lazy rather than eager because most rules are syntactic: a run with no +/// semantic rule enabled — which is every default `vfmt check`, since all +/// three semantic rules ship off — must not pay for an analysis nobody reads. +enum SemanticsSlot<'a> { + Lent(&'a Semantics), + Lazy(OnceCell), +} + /// One file, prepared once and shared by every rule in the run. /// /// The parse is the **tolerant** one: a file that does not fully parse still @@ -106,6 +122,10 @@ pub struct LintContext<'a> { /// Byte ranges of string literals, ascending — the one place text rules /// must not rewrite, because there whitespace is data. strings: Vec, + semantics: SemanticsSlot<'a>, + /// The signal table the semantic rules read, built once for all of them + /// the first time one asks — and never for a run with none enabled. + signals: OnceCell, } impl<'a> LintContext<'a> { @@ -140,8 +160,14 @@ impl<'a> LintContext<'a> { /// The one place a context is put together, whoever owns the products. fn assemble(backing: Backing<'a>, path: Option) -> LintContext<'a> { - let mut ctx = - LintContext { backing, path, tab_width: DEFAULT_TAB_WIDTH, strings: Vec::new() }; + let mut ctx = LintContext { + backing, + path, + tab_width: DEFAULT_TAB_WIDTH, + strings: Vec::new(), + semantics: SemanticsSlot::Lazy(OnceCell::new()), + signals: OnceCell::new(), + }; ctx.strings = ctx.tokens().iter().filter(|t| t.kind == TokenKind::String).map(|t| t.span).collect(); ctx @@ -153,6 +179,34 @@ impl<'a> LintContext<'a> { self } + /// Lends the symbol table the caller already built for this exact text — + /// "one parse, two tools" extended to the analysis (the language server + /// analyzes every buffer anyway, so its lint pass must not analyze twice). + /// + /// The contract is [`LintContext::from_parse`]'s: `semantics` must be + /// `analyze(file, source)` for the same products. Breaking it costs wrong + /// findings, never a bad write. + pub fn with_semantics(mut self, semantics: &'a Semantics) -> LintContext<'a> { + self.semantics = SemanticsSlot::Lent(semantics); + self + } + + /// The file's scopes, declarations and resolved uses — what a semantic + /// rule reads. Built on first use unless a caller lent one. + pub fn semantics(&self) -> &Semantics { + match &self.semantics { + SemanticsSlot::Lent(semantics) => semantics, + SemanticsSlot::Lazy(cell) => cell.get_or_init(|| analyze(self.file(), self.source())), + } + } + + /// Which signals this file declares and what is done to each — the table + /// the three semantic rules share, so a run enabling all of them walks the + /// file once, not three times. + pub(crate) fn signals(&self) -> &Signals { + self.signals.get_or_init(|| Signals::scan(self)) + } + /// The source text being linted. pub fn source(&self) -> &str { match &self.backing { @@ -271,6 +325,30 @@ mod tests { assert_eq!(borrowed.strings, owned.strings); } + #[test] + fn a_context_analyzes_itself_when_nothing_was_lent() { + let ctx = LintContext::new("module m;\n wire a;\n assign a = 1'b0;\nendmodule\n", None); + let semantics = ctx.semantics(); + assert!(semantics.symbols().iter().any(|s| s.name == "a")); + // Twice is the same table, not a second analysis. + assert!(std::ptr::eq(semantics, ctx.semantics())); + } + + #[test] + fn a_lent_analysis_is_the_one_the_rules_read() { + // The property the server's lint path rests on: it analyzes every + // buffer anyway, and the linter must read *that* table. + let src = "module m;\n wire a;\n assign a = 1'b0;\nendmodule\n"; + let parsed = ParsedSource::parse(src); + let lent = vlog_semantic::analyze(&parsed.file, src); + let ctx = parsed.context(None).with_semantics(&lent); + assert!(std::ptr::eq(ctx.semantics(), &lent)); + // ... and it says exactly what a self-analyzed context would. + let own = LintContext::new(src, None); + assert_eq!(ctx.semantics().symbols().len(), own.semantics().symbols().len()); + assert_eq!(ctx.semantics().references().len(), own.semantics().references().len()); + } + #[test] fn a_text_that_does_not_lex_exposes_its_lex_error() { let parsed = ParsedSource::parse("module m; parameter int élan = 1; endmodule\n"); diff --git a/crates/vlog_linter/src/lib.rs b/crates/vlog_linter/src/lib.rs index 70bc9a2..5040960 100644 --- a/crates/vlog_linter/src/lib.rs +++ b/crates/vlog_linter/src/lib.rs @@ -25,6 +25,7 @@ mod naming; mod registry; mod rule_docs; mod rules; +mod signals; mod violation; mod visit; mod waiver; diff --git a/crates/vlog_linter/src/registry.rs b/crates/vlog_linter/src/registry.rs index a4b215d..70aef68 100644 --- a/crates/vlog_linter/src/registry.rs +++ b/crates/vlog_linter/src/registry.rs @@ -48,10 +48,13 @@ pub fn all_rules() -> Vec<&'static dyn Rule> { &rules::explicit_parameter_storage_type::ExplicitParameterStorageType, &rules::module_filename::ModuleFilename, &rules::module_name_style::ModuleNameStyle, + &rules::multiply_driven::MultiplyDriven, &rules::no_tabs::NoTabs, &rules::no_trailing_whitespace::NoTrailingWhitespace, &rules::parameter_name_style::ParameterNameStyle, &rules::struct_union_name_style::StructUnionNameStyle, + &rules::undriven_net::UndrivenNet, + &rules::unused_signal::UnusedSignal, &rules::unused_waiver::UnusedWaiver, &rules::wire_reg_mixup::WireRegMixup, ] diff --git a/crates/vlog_linter/src/rule_docs.rs b/crates/vlog_linter/src/rule_docs.rs index 4349eec..0f4109a 100644 --- a/crates/vlog_linter/src/rule_docs.rs +++ b/crates/vlog_linter/src/rule_docs.rs @@ -105,6 +105,12 @@ mod tests { let markdown = rules_markdown(); assert!(markdown.contains("| [`no-tabs`](#no-tabs) | **on** | safe |")); assert!(markdown.contains("| [`module-name-style`](#module-name-style) | off | none |")); + // The three semantic rules ship off and fixless — see + // docs/features/semantic-lints/README.md for the corpus measurement + // behind each default. + for name in ["multiply-driven", "undriven-net", "unused-signal"] { + assert!(markdown.contains(&format!("| [`{name}`](#{name}) | off | none |")), "{name}"); + } assert_eq!(fix_word(&crate::rules::no_tabs::NoTabs), Applicability::Safe.as_str()); } diff --git a/crates/vlog_linter/src/rules/mod.rs b/crates/vlog_linter/src/rules/mod.rs index d2b82ac..b80ca0e 100644 --- a/crates/vlog_linter/src/rules/mod.rs +++ b/crates/vlog_linter/src/rules/mod.rs @@ -1,7 +1,9 @@ //! The rules themselves, one module each. //! -//! Every rule in this round is **syntactic** — text, tokens or tree shape — -//! per TODO.md §7: semantic rules wait for `vlog_semantic` to be wired in. +//! Most rules are **syntactic** — text, tokens or tree shape. The three that +//! are not (`unused-signal`, `undriven-net`, `multiply-driven`) read the +//! symbol table through `crate::signals`; see +//! `docs/features/semantic-lints/README.md`. pub mod always_comb_blocking; pub mod always_ff_non_blocking; @@ -10,9 +12,12 @@ pub mod enum_name_style; pub mod explicit_parameter_storage_type; pub mod module_filename; pub mod module_name_style; +pub mod multiply_driven; pub mod no_tabs; pub mod no_trailing_whitespace; pub mod parameter_name_style; pub mod struct_union_name_style; +pub mod undriven_net; +pub mod unused_signal; pub mod unused_waiver; pub mod wire_reg_mixup; diff --git a/crates/vlog_linter/src/rules/multiply_driven.rs b/crates/vlog_linter/src/rules/multiply_driven.rs new file mode 100644 index 0000000..7e960c2 --- /dev/null +++ b/crates/vlog_linter/src/rules/multiply_driven.rs @@ -0,0 +1,279 @@ +//! `multiply-driven` — a variable written from more than one driver. + +use std::collections::BTreeSet; + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::signals::{Driver, DriverKind}; +use crate::violation::Violation; + +/// See [`Rule::doc`]. +pub struct MultiplyDriven; + +const NAME: &str = "multiply-driven"; + +impl Rule for MultiplyDriven { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "give a variable exactly one driver" + } + + fn doc(&self) -> &'static str { + "A SystemVerilog *variable* — `logic`, `reg`, `int` — may be written \ + from one source only (IEEE 1800 §6.5). Two `always` blocks assigning \ + the same variable is a race in simulation and an elaboration error in \ + a synthesis tool that enforces the rule; mixing a continuous `assign` \ + with a procedural assignment to the same variable is the same \ + mistake wearing a different hat.\n\n\ + `wire` and the other net types are **not** reported: a net with \ + several drivers is legal Verilog, which is what a `tri` bus is made \ + of. Nor is a *partial* write: different bits of one variable driven \ + from different blocks is still illegal, but flagging it needs the \ + bit ranges resolved and this rule does not resolve them, so it steps \ + aside. It also steps aside for drivers inside a `generate` \ + construct, where only one arm of an `if` or `case` is ever \ + elaborated, and for drivers separated by an `` `ifdef``/`` `else``, \ + which is the same exclusivity spelled for the preprocessor. \ + Initializers, `initial` blocks and assignments inside a function or \ + task body are not counted either: the first is a variable's initial \ + value, and the last two say nothing about which process runs them." + } + + fn default_on(&self) -> bool { + // See docs/features/semantic-lints/README.md: measured over the + // 860-file corpus before this was decided. + false + } + + fn check(&self, ctx: &LintContext) -> Vec { + let signals = ctx.signals(); + let mut found = Vec::new(); + for decl in signals.decls() { + if decl.is_net || decl.has_init || !signals.judgeable(decl) { + continue; + } + let Some(usage) = signals.usage(decl) else { continue }; + if usage.drivers.iter().any(unclassifiable) { + continue; + } + let always = blocks(&usage.drivers, DriverKind::Always); + let continuous = blocks(&usage.drivers, DriverKind::Continuous); + if always.len() + continuous.len() < 2 { + continue; + } + let offsets: Vec = always.union(&continuous).copied().collect(); + if signals.conditional_between(&offsets) { + continue; + } + found.push(Violation::new( + NAME, + format!("`{}` {}", decl.name, how(always.len(), continuous.len())), + decl.name_span, + )); + } + found + } +} + +/// A driver this rule refuses to count, and whose presence takes the whole +/// signal out of the running: a partial write, a driver in a `generate` arm, +/// one whose process nothing here can name, or a simulation-only override. +fn unclassifiable(driver: &Driver) -> bool { + !driver.whole + || driver.in_generate + || driver.kind.is_override() + || matches!(driver.kind, DriverKind::Initial | DriverKind::Routine | DriverKind::Trigger) +} + +/// The distinct source blocks that drive a signal with one kind of driver. +fn blocks(drivers: &[Driver], kind: DriverKind) -> BTreeSet { + drivers.iter().filter(|d| d.kind == kind).map(|d| d.block).collect() +} + +/// How the diagnostic names the conflict it found. +fn how(always: usize, continuous: usize) -> String { + match (always, continuous) { + (0, n) => { + format!("is driven by {n} continuous assignments; a variable may have one driver") + } + (n, 0) => format!("is driven from {n} always blocks; a variable may have one driver"), + _ => "is driven both by a continuous assignment and by a procedural block".to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + MultiplyDriven.check(&LintContext::new(src, None)) + } + + fn messages(src: &str) -> Vec { + violations(src).iter().map(|v| v.message.clone()).collect() + } + + #[test] + fn two_always_blocks_driving_one_variable_are_reported() { + let src = "module m (input logic c, output logic q);\n logic a;\n\ + always_comb a = c;\n always_ff @(posedge c) a <= 1'b0;\n\ + assign q = a;\nendmodule\n"; + assert_eq!( + messages(src), + vec!["`a` is driven from 2 always blocks; a variable may have one driver"] + ); + } + + #[test] + fn a_continuous_assign_plus_a_procedural_block_is_reported() { + let src = "module m (input logic c, output logic q);\n logic a;\n\ + assign a = c;\n always_comb a = 1'b0;\n assign q = a;\nendmodule\n"; + assert_eq!( + messages(src), + vec!["`a` is driven both by a continuous assignment and by a procedural block"] + ); + } + + #[test] + fn two_continuous_assigns_to_a_variable_are_reported() { + let src = "module m (input logic c, output logic q);\n logic a;\n\ + assign a = c;\n assign a = 1'b0;\n assign q = a;\nendmodule\n"; + assert_eq!( + messages(src), + vec!["`a` is driven by 2 continuous assignments; a variable may have one driver"] + ); + } + + #[test] + fn one_driver_is_quiet_however_many_assignments_it_makes() { + let src = "module m (input logic c, output logic q);\n logic a;\n\ + always_comb begin\n a = 1'b0;\n if (c) a = 1'b1;\n end\n\ + assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn a_net_may_have_as_many_drivers_as_it_likes() { + let src = "module m (input logic c, output logic q);\n wire a;\n\ + assign a = c;\n assign a = 1'b0;\n assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn different_bits_from_different_blocks_are_not_flagged() { + let src = "module m (input logic c, output logic [1:0] q);\n logic [1:0] a;\n\ + always_comb a[0] = c;\n always_comb a[1] = 1'b0;\n\ + assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn generate_arms_are_exclusive_so_they_are_not_flagged() { + let src = "module m #(parameter int W = 1) (input logic c, output logic q);\n\ + logic a;\n\ + generate\n if (W == 1) begin : g0\n always_comb a = c;\n\ + end else begin : g1\n always_comb a = 1'b0;\n end\n endgenerate\n\ + assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn ifdef_arms_are_exclusive_so_they_are_not_flagged() { + let src = "module m (input logic c, output logic q);\n logic a;\n\ + `ifdef FAST\n always_comb a = c;\n`else\n always_comb a = 1'b0;\n`endif\n\ + assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty()); + // A directive that is not between the two drivers does not excuse them. + let after = "module m (input logic c, output logic q);\n logic a;\n\ + always_comb a = c;\n always_comb a = 1'b0;\n\ + `ifdef FAST\n`endif\n assign q = a;\nendmodule\n"; + assert_eq!(messages(after).len(), 1); + } + + #[test] + fn an_override_block_is_not_a_second_driver() { + // QA's repro (2026-08-25): a signal driven by one continuous `assign` + // and overridden by `force`/`release` inside an `always` block is a + // verification-harness shape, not a multiply-driven bug. `force` is + // simulation-only and replaces whatever drives the signal; it is + // never a driver of its own. + let src = "module m (input logic clk, input logic bypass, output logic q);\n\ + logic a;\n assign a = clk;\n\ + always @(posedge clk) begin\n\ + if (bypass) force a = 1'b1;\n else release a;\n end\n\ + assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", messages(src)); + } + + #[test] + fn overrides_from_several_blocks_are_still_not_drivers() { + for extra in + ["always_comb force a = 1'b1;", "initial release a;", "task t; deassign a; endtask"] + { + let src = format!( + "module m (input logic c, output logic q);\n logic a;\n\ + always_comb a = c;\n {extra}\n assign q = a;\nendmodule\n" + ); + assert!(violations(&src).is_empty(), "{extra}"); + } + } + + #[test] + fn an_override_anywhere_takes_the_signal_out_of_the_rule() { + // Deliberately wider than "do not count the override as a driver": a + // signal something forces is verification-harness territory and this + // rule stays out of it, the same way `initial` and a task body take a + // signal out. Two real drivers plus a force is silence. + let src = "module m (input logic c, output logic q);\n logic a;\n\ + always_comb a = c;\n always_comb a = 1'b0;\n\ + initial force a = 1'b1;\n assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", messages(src)); + } + + #[test] + fn an_override_does_not_hide_a_real_conflict_it_did_not_create() { + // The other direction: the exclusion must not be reachable by + // accident. Without the override the same two drivers still report. + let src = "module m (input logic c, output logic q);\n logic a;\n\ + assign a = c;\n always_comb a = 1'b0;\n assign q = a;\nendmodule\n"; + assert_eq!(violations(src).len(), 1, "the real conflict still reports"); + } + + #[test] + fn initial_and_routine_writes_are_not_counted() { + for extra in ["initial a = 1'b0;", "task t; a = 1'b0; endtask"] { + let src = format!( + "module m (input logic c, output logic q);\n logic a;\n\ + always_comb a = c;\n {extra}\n assign q = a;\nendmodule\n" + ); + assert!(violations(&src).is_empty(), "{extra}"); + } + } + + #[test] + fn an_initializer_takes_the_signal_out_of_the_running() { + let src = "module m (input logic c, output logic q);\n logic a = 1'b0;\n\ + always_comb a = c;\n always_comb a = 1'b1;\n assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn a_macro_mention_silences_it() { + let src = "module m (input logic c, output logic q);\n logic a;\n\ + always_comb a = c;\n always_comb a = 1'b0;\n `NOTE(a)\n\ + assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn it_points_at_the_declared_name() { + let src = "module m (input logic c, output logic q);\n logic aaa;\n\ + always_comb aaa = c;\n always_comb aaa = 1'b0;\n assign q = aaa;\nendmodule\n"; + let found = violations(src); + assert_eq!(&src[found[0].span.as_range()], "aaa"); + assert!(found[0].fix.is_none(), "diagnose only"); + } +} diff --git a/crates/vlog_linter/src/rules/undriven_net.rs b/crates/vlog_linter/src/rules/undriven_net.rs new file mode 100644 index 0000000..d88c8f1 --- /dev/null +++ b/crates/vlog_linter/src/rules/undriven_net.rs @@ -0,0 +1,215 @@ +//! `undriven-net` — a signal that is read but that nothing ever drives. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::signals::intentionally_unused; +use crate::violation::Violation; + +/// See [`Rule::doc`]. +pub struct UndrivenNet; + +const NAME: &str = "undriven-net"; + +impl Rule for UndrivenNet { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "drive a signal that something reads" + } + + fn doc(&self) -> &'static str { + "A net read by the design but assigned by nothing is `z` forever, and \ + a variable in the same position is `x` forever. In simulation this \ + propagates as an unknown; in synthesis it is a dangling input. It is \ + almost always a typo in a signal name or an assignment that was \ + deleted with the block it lived in.\n\n\ + The rule is deliberately timid, because a false positive here reads \ + as an accusation. It stays silent about: ports (an input is driven \ + by the instantiating file, an `inout` from either side), any signal \ + wired to an instance or gate connection or passed to a task — those \ + positions may be `output`, and vfmt does not read the instantiated \ + module to find out — any signal a macro, a compiler directive, a \ + verbatim block or an unparsed region mentions, any signal in a \ + module that instantiates with `.*`, anything declared with an \ + initializer, and anything nothing reads (that is `unused-signal`'s \ + subject, not this one). What is left is the honest case: a plain \ + name read in ordinary code with no assignment anywhere in the file." + } + + fn default_on(&self) -> bool { + // See docs/features/semantic-lints/README.md: measured over the + // 860-file corpus before this was decided. + false + } + + fn check(&self, ctx: &LintContext) -> Vec { + let signals = ctx.signals(); + let mut found = Vec::new(); + for decl in signals.decls() { + if intentionally_unused(&decl.name) || !signals.judgeable(decl) || decl.has_init { + continue; + } + let Some(usage) = signals.usage(decl) else { continue }; + // A `release`/`deassign` is a write that establishes no value, so + // it is not what saves a signal from this rule. + let driven = usage.drivers.iter().any(|driver| driver.establishes_a_value()); + if signals.connected(decl) || driven || usage.reads == 0 { + continue; + } + found.push(Violation::new( + NAME, + format!("`{}` is read but never driven", decl.name), + decl.name_span, + )); + } + found + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + UndrivenNet.check(&LintContext::new(src, None)) + } + + fn names(src: &str) -> Vec { + violations(src) + .iter() + .map(|v| v.message.split('`').nth(1).unwrap_or_default().to_string()) + .collect() + } + + #[test] + fn a_read_but_undriven_signal_is_reported() { + let src = "module m (output logic q);\n wire a;\n assign q = a;\nendmodule\n"; + assert_eq!(names(src), vec!["a"]); + } + + #[test] + fn every_shape_of_drive_silences_it() { + for body in [ + "assign a = 1'b0;", + "always_comb a = 1'b0;", + "always_ff @(posedge q) a <= 1'b0;", + "initial a = 1'b0;", + "always_comb begin\n if (q) a = 1'b1; else a = 1'b0;\n end", + "always_comb a[0] = 1'b0;", + "always_comb {a, q} = 2'b00;", + "always_comb force a = 1'b0;", + "task t; a = 1'b0; endtask", + ] { + let src = + format!("module m (output logic q);\n logic [1:0] a;\n {body}\n assign q = |a;\nendmodule\n"); + assert!(violations(&src).is_empty(), "{body} should count as a drive"); + } + } + + #[test] + fn a_force_is_a_drive_but_a_release_is_not() { + // `force` puts a value on the signal; `release`/`deassign` take an + // override *away*, so a signal whose only write is a release is still + // driven by nothing (QA finding, 2026-08-25). + let forced = "module m (output logic q);\n logic a;\n\ + initial force a = 1'b1;\n assign q = a;\nendmodule\n"; + assert!(violations(forced).is_empty(), "a force drives"); + + for undriving in ["release a;", "deassign a;"] { + let src = format!( + "module m (output logic q);\n logic a;\n initial begin\n {undriving}\n\ + end\n assign q = a;\nendmodule\n" + ); + assert_eq!(names(&src), vec!["a"], "{undriving} is not a drive"); + } + } + + #[test] + fn a_released_signal_that_something_really_drives_is_quiet() { + // The other direction: the release must not manufacture a finding + // where a real driver exists. + let src = "module m (input logic c, output logic q);\n logic a;\n\ + always_comb a = c;\n initial release a;\n assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", names(src)); + } + + #[test] + fn an_unread_signal_is_the_other_rules_business() { + let src = "module m;\n wire a;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn a_connection_may_be_an_output_so_it_is_never_flagged() { + for inst in ["sub u (.x(a));", "sub u (a);", "and g (a, q, q);", "sub u (.x(a[0]));"] { + let src = + format!("module m (output logic q);\n wire [1:0] a;\n {inst}\n assign q = |a;\nendmodule\n"); + assert!(violations(&src).is_empty(), "{inst} may drive `a`"); + } + } + + #[test] + fn a_task_call_argument_may_be_an_output_so_it_is_never_flagged() { + let src = "module m (output logic q);\n logic a;\n\ + initial begin\n fill(a);\n end\n assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn a_macro_mention_silences_it() { + let src = "module m (output logic q);\n logic a;\n `DRIVE_IT(a)\n\ + assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn an_unparsable_region_silences_it() { + let src = "module m (output logic q);\n logic a;\n @@@ a = 1 @@@;\n\ + assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn ports_are_never_reported() { + // `b` is an input read but assigned by nothing in this file, which is + // exactly what an input port is. + let src = "module m (input logic b, output logic q);\n assign q = b;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn an_interface_is_out_of_scope() { + let src = "interface bus;\n logic a;\n modport mp (input a);\nendinterface\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn a_declaration_with_an_initializer_is_driven() { + let src = "module m (output logic q);\n wire a = 1'b0;\n assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn a_dot_star_instance_silences_the_whole_module() { + let src = "module m (output logic q);\n wire a;\n sub u (.*);\n\ + assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn a_read_in_an_index_or_a_condition_still_counts_as_a_read() { + let src = "module m (output logic q);\n logic [3:0] mem;\n logic sel;\n\ + assign mem = 4'h0;\n assign q = mem[sel];\nendmodule\n"; + assert_eq!(names(src), vec!["sel"]); + } + + #[test] + fn it_points_at_the_declared_name() { + let src = "module m (output logic q);\n wire aaa;\n assign q = aaa;\nendmodule\n"; + let found = violations(src); + assert_eq!(&src[found[0].span.as_range()], "aaa"); + assert!(found[0].fix.is_none(), "diagnose only"); + } +} diff --git a/crates/vlog_linter/src/rules/unused_signal.rs b/crates/vlog_linter/src/rules/unused_signal.rs new file mode 100644 index 0000000..e576c25 --- /dev/null +++ b/crates/vlog_linter/src/rules/unused_signal.rs @@ -0,0 +1,187 @@ +//! `unused-signal` — a net or variable nothing ever mentions again. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::signals::intentionally_unused; +use crate::violation::Violation; + +/// See [`Rule::doc`]. +pub struct UnusedSignal; + +const NAME: &str = "unused-signal"; + +impl Rule for UnusedSignal { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "delete a signal nothing uses" + } + + fn doc(&self) -> &'static str { + "A `wire` or `logic` that nothing reads and nothing drives is dead \ + weight: it costs a reader the effort of working out what it is for, \ + and it is often the leftover of a signal that was renamed everywhere \ + but here. This is the first rule vfmt writes against the symbol \ + table rather than the syntax tree — Verible cannot express it, \ + because knowing that a name is unused means knowing which \ + declaration every use refers to.\n\n\ + What is deliberately **not** reported: ports (they are the module's \ + interface, and an unused one is the instantiating file's business), \ + names matching the intentionally-unused convention (a leading `_`, \ + or `unused` anywhere in the name — Verilator's `--unused-regexp` \ + default), and any name mentioned *anywhere else* in the file's \ + tokens, even inside a macro invocation, a compiler directive or a \ + region that failed to parse. That last guard is the important one: \ + vfmt does not expand macros, so a signal used only by \ + `` `MY_ASSERT(foo) `` would otherwise be reported as unused. The \ + cost of the guard is that two same-named unused signals in one file \ + shield each other — a false negative, which is the harmless \ + direction for a rule like this." + } + + fn default_on(&self) -> bool { + // See docs/features/semantic-lints/README.md: measured over the + // 860-file corpus before this was decided. + false + } + + fn check(&self, ctx: &LintContext) -> Vec { + let signals = ctx.signals(); + let semantics = ctx.semantics(); + let mut found = Vec::new(); + for decl in signals.decls() { + if intentionally_unused(&decl.name) || !signals.judgeable(decl) { + continue; + } + let Some(id) = decl.symbol else { continue }; + if !semantics.references_of(id).is_empty() { + continue; + } + if signals.mentioned_outside_declarations(&decl.name) { + continue; + } + found.push(Violation::new( + NAME, + format!("`{}` is declared but never used", decl.name), + decl.name_span, + )); + } + found + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + UnusedSignal.check(&LintContext::new(src, None)) + } + + fn names(src: &str) -> Vec { + violations(src) + .iter() + .map(|v| v.message.split('`').nth(1).unwrap_or_default().to_string()) + .collect() + } + + #[test] + fn a_signal_nothing_mentions_again_is_reported() { + let src = "module m;\n wire a;\n logic b;\n assign a = 1;\n wire c = a;\n\ + endmodule\n"; + // `b` is untouched; `c` is driven by its own initializer but read by + // nothing, which is still unused. + assert_eq!(names(src), vec!["b", "c"]); + } + + #[test] + fn a_used_signal_is_quiet_however_it_is_used() { + let src = "module m;\n wire a;\n logic b;\n logic [1:0] c;\n\ + assign a = 1;\n always_comb b = a;\n assign c[0] = b;\n\ + sub u (.x(c));\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", names(src)); + } + + #[test] + fn ports_are_never_reported() { + let src = "module m (input logic clk, output logic q);\nendmodule\n"; + assert!(violations(src).is_empty()); + let non_ansi = "module m (a, b);\n input a;\n output b;\nendmodule\n"; + assert!(violations(non_ansi).is_empty()); + } + + #[test] + fn the_intentionally_unused_convention_is_honored() { + let src = "module m;\n wire unused_x;\n wire _y;\n wire z_unused;\n\ + wire real_one;\nendmodule\n"; + assert_eq!(names(src), vec!["real_one"]); + } + + #[test] + fn a_name_a_macro_mentions_is_never_reported() { + // The reference table cannot see inside a macro; the token stream can. + let src = "module m;\n wire a;\n `ASSERT_KNOWN(AKnown, a)\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", names(src)); + } + + #[test] + fn a_name_a_directive_mentions_is_never_reported() { + let src = "module m;\n wire a;\n`ifdef USE_A\n assign x = a;\n`endif\nendmodule\n"; + assert!(violations(src).is_empty()); + let in_directive = "module m;\n wire a;\n`define TIE_A a = 1'b0\nendmodule\n"; + assert!(violations(in_directive).is_empty()); + } + + #[test] + fn a_name_used_only_in_an_unparsable_region_is_never_reported() { + let src = "module m;\n wire a;\n @@@ a @@@;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn a_dot_star_instance_silences_the_whole_module() { + // `.*` connects same-named signals without writing their names down. + let src = "module m;\n wire a;\n sub u (.*);\nendmodule\n"; + assert!(violations(src).is_empty()); + // ... but only its own module. + let two = "module m;\n wire a;\n sub u (.*);\nendmodule\n\ + module n;\n wire b;\nendmodule\n"; + assert_eq!(names(two), vec!["b"]); + } + + #[test] + fn an_implicit_named_connection_counts_as_a_use() { + let src = "module m;\n wire a;\n sub u (.a);\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn a_signal_only_a_comment_or_a_string_mentions_is_still_unused() { + let src = "module m;\n wire a; // a is for apple\n string s = \"a\";\nendmodule\n"; + assert_eq!(names(src), vec!["a", "s"]); + } + + #[test] + fn a_same_named_signal_used_in_another_module_shields_this_one() { + // The documented false negative of the whole-word text guard: it is + // name-based, not scope-based. + let src = "module m;\n wire a;\nendmodule\n\ + module n (output logic q);\n wire a;\n assign a = 1;\n\ + assign q = a;\nendmodule\n"; + assert!(violations(src).is_empty()); + // Two unused declarations of one name still both report: every + // declaration span is excluded, not just this signal's own. + let both = "module m;\n wire a;\nendmodule\nmodule n;\n wire a;\nendmodule\n"; + assert_eq!(names(both), vec!["a", "a"]); + } + + #[test] + fn it_points_at_the_declared_name() { + let src = "module m;\n wire aaa;\nendmodule\n"; + let found = violations(src); + assert_eq!(&src[found[0].span.as_range()], "aaa"); + assert!(found[0].fix.is_none(), "diagnose only"); + } +} diff --git a/crates/vlog_linter/src/signals.rs b/crates/vlog_linter/src/signals.rs new file mode 100644 index 0000000..2c79a8d --- /dev/null +++ b/crates/vlog_linter/src/signals.rs @@ -0,0 +1,1007 @@ +//! What a module declares, and what is done to each declaration. +//! +//! The three semantic rules all ask the same two questions — *is this name +//! used at all* and *is this use a read or a write* — and neither the AST nor +//! `vlog_semantic` answers the second one: a `Reference` is a use, with no +//! direction on it. This module classifies uses from the AST context they are +//! written in (assignment left-hand side, instance connection, call argument) +//! and hands the rules one table. +//! +//! Everything here leans one way: **when the answer is not certain, say +//! nothing**. A name that a macro, a compiler directive, a verbatim block or +//! an unparsed region mentions is dropped from every judgement, because vfmt +//! does not expand macros and cannot see what those regions do. That is the +//! insurance a semantic rule needs — a lint that cries wolf on real RTL is +//! worse than no lint at all. + +use std::collections::{HashMap, HashSet}; + +use vlog_parser::ast::{ + ClockingItemKind, Connections, Expr, ExprKind, ForStep, GenElse, Instantiation, Item, ItemKind, + SourceFile, Stmt, StmtKind, +}; +use vlog_parser::span::TextRange; +use vlog_parser::token::TokenKind; +use vlog_semantic::{Semantics, SymbolId}; + +use crate::context::LintContext; +use crate::visit::walk_stmts; + +/// What wrote to a signal. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum DriverKind { + /// `assign x = ...;` + Continuous, + /// A procedural assignment inside an `always*` block. + Always, + /// A procedural assignment inside `initial` / `final`. + Initial, + /// A procedural assignment inside a function or task body. Whoever *calls* + /// the routine is the real driver, which nothing here knows. + Routine, + /// The declarator's own initializer: `wire w = a & b;`, `logic x = 1'b0;`. + Initializer, + /// `-> ev;` — what makes a named event happen. It is the event's drive, + /// but two triggers are not a conflict the way two drivers are. + Trigger, + /// `force x = ...;` — a simulation-only override. It *does* put a value on + /// the signal, so it is a drive; it is not a second driver, because it + /// replaces whatever drives the signal for as long as it holds. + Force, + /// `release x;` / `deassign x;` — the *end* of an override. It establishes + /// no value at all, so it can never be what drives a signal. + Release, +} + +impl DriverKind { + /// True for the simulation-only override family (`force`, `release`, + /// `deassign`), which no rule may count as one of a signal's drivers. + pub(crate) fn is_override(self) -> bool { + matches!(self, DriverKind::Force | DriverKind::Release) + } +} + +/// One write to a signal. +#[derive(Debug, Clone)] +pub(crate) struct Driver { + pub kind: DriverKind, + /// Start offset of the item that owns the write. Two writes sharing a + /// `block` are the same `always` block, the same `assign`, the same task. + pub block: u32, + /// True when the whole signal is written (`x = ...`); false for a + /// part-select, index or member write (`x[3] = ...`). + pub whole: bool, + /// True when the write sits inside a `generate` construct, where only one + /// arm of an `if`/`case` is ever elaborated. + pub in_generate: bool, +} + +impl Driver { + /// True when this write actually puts a value on the signal. + /// + /// Everything does except `release`/`deassign`, which *remove* an + /// override: a signal whose only "write" is a release is still driven by + /// nothing, which is exactly what `undriven-net` is looking for. + pub(crate) fn establishes_a_value(&self) -> bool { + self.kind != DriverKind::Release + } +} + +/// Everything done to one signal. +#[derive(Debug, Default)] +pub(crate) struct Usage { + pub drivers: Vec, + /// True when the signal appears somewhere whose direction is unknown: an + /// instance or gate connection, a task/function call argument, a clocking + /// block. Such a use may be a drive, so a signal carrying this flag is + /// never called undriven. + pub connected: bool, + /// Uses that are neither a write nor an unknown-direction position. + pub reads: usize, +} + +/// One net or variable declared at item level inside a `module`. +#[derive(Debug)] +pub(crate) struct Decl { + pub name: String, + /// Byte range of the declared name — where a diagnostic points. + pub name_span: TextRange, + /// The symbol this declaration bound, when it bound one. A redeclaration + /// binds nothing (`vlog_semantic` rule 10), and a declaration with no + /// symbol is never judged. + pub symbol: Option, + /// `wire`/`tri`/... as opposed to `logic`/`reg`/`int`/... + pub is_net: bool, + /// `wire w = expr;` / `logic x = 0;` + pub has_init: bool, + /// Index into the module table — see [`Signals::judgeable`]. + module: usize, +} + +/// One module's scan. +#[derive(Debug, Default)] +struct ModuleInfo { + /// True when this module hides code from the analysis, and nothing + /// declared in it can therefore be judged. Two ways to earn it: an + /// instance connected with `.*`, which reads and drives same-named + /// signals without writing any of their names down, and an `` `include`` + /// in the module body, which is arbitrary code vfmt does not follow. + blind: bool, +} + +/// The signal table for one file. +pub(crate) struct Signals { + decls: Vec, + modules: Vec, + usage: HashMap, + /// Names mentioned where nothing can be read out of the mention: inside a + /// macro invocation, a compiler directive, an attribute, a verbatim block + /// or an unparsed region. + opaque: HashSet, + /// Whole-word mentions of each name in the token stream — comments and + /// string literals excluded, macro and directive text included — by start + /// offset. + mentions: HashMap>, + /// Start offset of every name this file declares. + declared_at: HashSet, + /// Start offsets of the conditional-compilation directive lines + /// (`` `ifdef`` and friends), ascending. + conditionals: Vec, + /// Names connected to an instance port by the implicit `.name` form, + /// whose reference resolves to the *other* module's port and so never + /// reaches the local signal. + connected_names: HashSet, +} + +impl Signals { + /// Scan one prepared file. + pub(crate) fn scan(ctx: &LintContext) -> Signals { + let semantics = ctx.semantics(); + let mut scanner = Scanner { + refs: reference_index(semantics), + symbols: semantics + .symbols() + .iter() + .enumerate() + .filter(|(_, s)| !s.name_span.is_empty()) + .map(|(i, s)| (s.name_span.start, SymbolId(i as u32))) + .collect(), + signals: Signals { + decls: Vec::new(), + modules: Vec::new(), + usage: HashMap::new(), + opaque: HashSet::new(), + mentions: HashMap::new(), + declared_at: semantics.symbols().iter().map(|s| s.name_span.start).collect(), + conditionals: Vec::new(), + connected_names: HashSet::new(), + }, + writes: HashSet::new(), + unknown: Vec::new(), + opaque_spans: Vec::new(), + }; + scanner.file(ctx.file()); + scanner.tokens(ctx); + scanner.finish(semantics) + } + + /// Every candidate declaration, in source order. + pub(crate) fn decls(&self) -> &[Decl] { + &self.decls + } + + /// What was done to a declaration's symbol. + pub(crate) fn usage(&self, decl: &Decl) -> Option<&Usage> { + decl.symbol.map(|id| self.usage.get(&id).unwrap_or(&EMPTY)) + } + + /// True when this declaration may be judged at all: it bound a symbol, its + /// name is not mentioned anywhere opaque, and its module hides no code + /// from the analysis. + pub(crate) fn judgeable(&self, decl: &Decl) -> bool { + decl.symbol.is_some() + && !self.opaque.contains(&decl.name) + && !self.modules.get(decl.module).is_some_and(|m| m.blind) + } + + /// True when the signal sits somewhere whose direction is unknown, so it + /// may be driven from outside this file's sight. + pub(crate) fn connected(&self, decl: &Decl) -> bool { + self.connected_names.contains(&decl.name) + || self.usage(decl).is_some_and(|usage| usage.connected) + } + + /// True when the name is written anywhere in the file outside a + /// declaration of that name — in ordinary code, in a macro argument, in a + /// compiler directive, in a region that did not parse. + /// + /// This is `unused-signal`'s insurance: the reference table cannot see + /// through a macro, but the token stream sees every byte that is not a + /// comment or a string literal, so a name a macro uses still counts as + /// used. Being name-based and not scope-based, it costs false *negatives* + /// — an unused `count` in one module is shielded by a used `count` in the + /// next — which is the harmless direction. + pub(crate) fn mentioned_outside_declarations(&self, name: &str) -> bool { + match self.mentions.get(name) { + Some(spots) => spots.iter().any(|start| !self.declared_at.contains(start)), + None => false, + } + } + + /// True when a conditional-compilation directive is written between the + /// first and the last of these offsets — the `` `ifdef``/`` `else`` shape + /// where two drivers of one signal never coexist in one elaboration. + pub(crate) fn conditional_between(&self, offsets: &[u32]) -> bool { + let (Some(&lo), Some(&hi)) = (offsets.iter().min(), offsets.iter().max()) else { + return false; + }; + self.conditionals.iter().any(|&at| at > lo && at < hi) + } +} + +/// The answer for a symbol nothing was done to. +static EMPTY: Usage = Usage { drivers: Vec::new(), connected: false, reads: 0 }; + +/// True for a name whose convention says "declared on purpose, never used". +/// +/// Verible ships no unused-signal rule to be compatible with (it is +/// syntax-only), so the convention is Verilator's: its `--unused-regexp` +/// defaults to `*unused*`, and a leading underscore is the wider Verilog +/// spelling of the same intent. +pub(crate) fn intentionally_unused(name: &str) -> bool { + name.starts_with('_') || name.to_ascii_lowercase().contains("unused") +} + +/// Name-span start → the symbol that use resolved to. +fn reference_index(semantics: &Semantics) -> HashMap { + semantics + .references() + .iter() + .filter_map(|r| r.resolved().map(|id| (r.name_span.start, id))) + .collect() +} + +/// The walk that fills a [`Signals`]. +struct Scanner { + refs: HashMap, + /// Name-span start → the symbol declared there. + symbols: HashMap, + signals: Signals, + /// Name-span starts that are written, whoever they resolve to. + writes: HashSet, + /// Ranges whose uses have an unknown direction. + unknown: Vec, + /// Ranges nothing can be read out of. + opaque_spans: Vec, +} + +impl Scanner { + /// Only a `module` is scanned: an `interface`'s signals are driven by + /// whoever uses the interface, a package or class declares no nets. + fn file(&mut self, file: &SourceFile) { + for item in &file.items { + if let ItemKind::Module(module) = &item.kind { + if module.kw == "interface" { + continue; + } + self.signals.modules.push(ModuleInfo::default()); + let id = self.signals.modules.len() - 1; + self.items(&module.items, id, false); + } + } + } + + fn items(&mut self, list: &[Item], module: usize, in_generate: bool) { + for item in list { + self.item(item, module, in_generate); + } + } + + fn item(&mut self, item: &Item, module: usize, in_generate: bool) { + let block = item.span.start; + match &item.kind { + ItemKind::DataDecl(decl) => { + for declarator in &decl.declarators { + let symbol = self.symbol_at(declarator.name_span); + self.signals.decls.push(Decl { + name: declarator.name.clone(), + name_span: declarator.name_span, + symbol, + is_net: decl.net.is_some(), + has_init: declarator.init.is_some(), + module, + }); + // An initializer writes the declaration itself, which is + // a symbol and not a use, so it is recorded here rather + // than through the reference table. + if let (true, Some(id)) = (declarator.init.is_some(), symbol) { + self.drive( + id, + Driver { + kind: DriverKind::Initializer, + block: declarator.span.start, + whole: true, + in_generate, + }, + ); + } + } + } + ItemKind::ContAssign(assign) => { + for pair in &assign.assigns { + self.write(&pair.lhs, DriverKind::Continuous, block, in_generate); + } + } + ItemKind::Always { stmt, .. } => { + self.body(stmt, DriverKind::Always, block, in_generate) + } + ItemKind::Initial(stmt) | ItemKind::Final(stmt) => { + self.body(stmt, DriverKind::Initial, block, in_generate) + } + ItemKind::Function(decl) => { + for stmt in &decl.stmts { + self.body(stmt, DriverKind::Routine, block, in_generate); + } + } + ItemKind::Task(decl) => { + for stmt in &decl.stmts { + self.body(stmt, DriverKind::Routine, block, in_generate); + } + } + ItemKind::Instantiation(inst) => self.instantiation(inst, module), + ItemKind::Bind(bind) => self.instantiation(&bind.inst, module), + ItemKind::GateInstantiation(gates) => { + for instance in &gates.instances { + for arg in &instance.args { + self.unknown.push(arg.span); + } + } + } + // A clocking block's signals are driven and sampled by whatever + // testbench drives the block. `vlog_semantic` records no + // reference for one (it is a leaf there), so the names are taken + // out through the token-level guard rather than the usage table. + ItemKind::Clocking(clocking) => { + for clocking_item in &clocking.items { + if let ClockingItemKind::Signals { .. } = clocking_item.kind { + self.opaque_spans.push(clocking_item.span); + } + } + } + ItemKind::GenerateRegion { items, .. } => self.items(items, module, true), + ItemKind::GenIf(gen_if) => { + self.items(&gen_if.then.items, module, true); + let mut els = gen_if.els.as_deref(); + while let Some(branch) = els { + match branch { + GenElse::If(_, nested) => { + self.items(&nested.then.items, module, true); + els = nested.els.as_deref(); + } + GenElse::Block(block) => { + self.items(&block.items, module, true); + els = None; + } + } + } + } + ItemKind::GenFor(gen_for) => self.items(&gen_for.body.items, module, true), + ItemKind::GenCase(gen_case) => { + for case_item in &gen_case.items { + self.items(&case_item.body.items, module, true); + } + } + // An `include` in a module body is arbitrary code — it may + // declare, read or drive anything — and vfmt does not follow one. + ItemKind::Directive(raw) if is_include(&raw.text) => self.blind(module), + // Nothing here can be read: a macro is not expanded, a directive + // is not evaluated, a verbatim block is not modelled, and an + // error leaf did not parse. Every name they mention is dropped. + ItemKind::MacroItem(_) + | ItemKind::Directive(_) + | ItemKind::Verbatim(_) + | ItemKind::Error(_) => self.opaque_spans.push(item.span), + _ => {} + } + } + + /// Every write inside one driver block, at any statement depth. + fn body(&mut self, stmt: &Stmt, kind: DriverKind, block: u32, in_generate: bool) { + walk_stmts(stmt, &mut |stmt| match &stmt.kind { + StmtKind::Assign { lhs, .. } => self.write(lhs, kind, block, in_generate), + // `force`/`release`/`deassign` are simulation-only overrides, and + // they keep their own kind rather than the enclosing block's: + // a `force` inside an `always` block is not a second driver of + // the signal, and a `release` is not a drive at all. + StmtKind::ForceRelease { kw, lhs, .. } => { + let kind = if kw == "force" { DriverKind::Force } else { DriverKind::Release }; + self.write(lhs, kind, block, in_generate) + } + StmtKind::For { init, step, .. } => { + for entry in init { + self.write(&entry.assign.lhs, kind, block, in_generate); + } + for entry in step { + match entry { + ForStep::Assign(assign) => { + self.write(&assign.lhs, kind, block, in_generate) + } + ForStep::Expr(expr) => match increment_target(expr) { + Some(target) => self.write(target, kind, block, in_generate), + None => self.unknown.push(expr.span), + }, + } + } + } + // `x++;` is a write; every other expression statement is a call, + // whose arguments may be `output` arguments — unknown direction. + StmtKind::ExprStmt(expr) => match increment_target(expr) { + Some(target) => self.write(target, kind, block, in_generate), + None => self.unknown.push(expr.span), + }, + // `-> ev;` is what drives a named event. + StmtKind::EventTrigger(expr) => { + self.write(expr, DriverKind::Trigger, block, in_generate) + } + StmtKind::MacroStmt(_) + | StmtKind::Directive(_) + | StmtKind::Verbatim(_) + | StmtKind::Error(_) => self.opaque_spans.push(stmt.span), + _ => {} + }); + } + + /// An instance's connections: direction unknown unless the instantiated + /// module is read too, which this round deliberately does not do. + fn instantiation(&mut self, inst: &Instantiation, module: usize) { + for instance in &inst.instances { + match &instance.conns { + Connections::Ordered(conns) => { + for conn in conns { + self.unknown.push(conn.span); + } + } + Connections::Named(conns) => { + for conn in conns { + match (conn.name.as_str(), &conn.expr) { + // `.*` connects every same-named signal without + // writing any of their names down. + ("*", _) => self.blind(module), + // `.name` connects the same-named local signal. + // The reference recorded here names the *port*, in + // the instantiated module's scope, so the local + // signal must be picked up by name. + (name, None) => { + self.signals.connected_names.insert(name.to_string()); + } + _ => {} + } + self.unknown.push(conn.span); + } + } + } + } + } + + /// Marks a module as one whose signals cannot be judged. + fn blind(&mut self, module: usize) { + if let Some(info) = self.signals.modules.get_mut(module) { + info.blind = true; + } + } + + /// Records every name an assignment's left-hand side writes. + fn write(&mut self, lhs: &Expr, kind: DriverKind, block: u32, in_generate: bool) { + let mut targets = Vec::new(); + lvalue_targets(lhs, true, &mut targets); + for (span, whole) in targets { + self.record(span, whole, kind, block, in_generate); + } + } + + fn record( + &mut self, + span: TextRange, + whole: bool, + kind: DriverKind, + block: u32, + in_generate: bool, + ) { + self.writes.insert(span.start); + if let Some(&id) = self.refs.get(&span.start) { + self.drive(id, Driver { kind, block, whole, in_generate }); + } + } + + fn drive(&mut self, id: SymbolId, driver: Driver) { + self.signals.usage.entry(id).or_default().drivers.push(driver); + } + + /// The symbol a declared name bound, if the analysis bound one there. + fn symbol_at(&self, name_span: TextRange) -> Option { + if name_span.is_empty() { + return None; + } + self.symbols.get(&name_span.start).copied() + } + + /// The token pass: every whole-word mention, and the ones nothing can be + /// read out of. + fn tokens(&mut self, ctx: &LintContext) { + merge(&mut self.opaque_spans); + for token in ctx.tokens() { + match token.kind { + // A plain identifier is one mention of itself. + TokenKind::Ident if !token.text.starts_with('`') => { + self.signals + .mentions + .entry(token.text.clone()) + .or_default() + .push(token.span.start); + // ... and if it sits in a region nobody parsed, whatever + // is done to it there cannot be read. + if covers(&self.opaque_spans, token.span.start) { + self.signals.opaque.insert(token.text.clone()); + } + } + // A macro invocation (`` `NAME(a, b) ``), a directive line and + // an attribute are raw text the parser never looked inside. + TokenKind::Ident | TokenKind::Directive | TokenKind::Attribute => { + for (offset, word) in words(&token.text) { + self.signals + .mentions + .entry(word.to_string()) + .or_default() + .push(token.span.start + offset); + self.signals.opaque.insert(word.to_string()); + } + if token.kind == TokenKind::Directive && is_conditional(&token.text) { + self.signals.conditionals.push(token.span.start); + } + } + _ => {} + } + } + } + + /// Classify every use that is not a write: an unknown-direction position + /// (an instance connection, a call argument) or a read. + fn finish(mut self, semantics: &Semantics) -> Signals { + merge(&mut self.unknown); + for reference in semantics.references() { + let start = reference.name_span.start; + let Some(id) = reference.resolved() else { continue }; + if self.writes.contains(&start) { + continue; + } + let usage = self.signals.usage.entry(id).or_default(); + if covers(&self.unknown, start) { + usage.connected = true; + } else { + usage.reads += 1; + } + } + self.signals + } +} + +/// The names an assignment's left-hand side writes, each with whether the +/// whole signal was written or only a part of it. +fn lvalue_targets(expr: &Expr, whole: bool, out: &mut Vec<(TextRange, bool)>) { + match &expr.kind { + ExprKind::Ident(_) => out.push((expr.span, whole)), + ExprKind::Paren { inner, .. } => lvalue_targets(inner, whole, out), + ExprKind::Cast { expr, .. } => lvalue_targets(expr, whole, out), + // A select writes part of its base; a member writes part of its + // struct. `a.b.c = x` is a write to `a`, which is what resolves. + ExprKind::Index { base, .. } | ExprKind::Range { base, .. } => { + lvalue_targets(base, false, out) + } + ExprKind::Member { base, .. } => lvalue_targets(base, false, out), + // `{a, b[1]} = x` writes each element. + ExprKind::Concat(items) | ExprKind::Stream { inner: items, .. } => { + for item in items { + lvalue_targets(&item.expr, whole, out); + } + } + _ => {} + } +} + +/// The target of `x++` / `x--` / `++x`, which is a write dressed as an +/// expression. +fn increment_target(expr: &Expr) -> Option<&Expr> { + match &expr.kind { + ExprKind::Postfix { expr, op } | ExprKind::Unary { expr, op } + if op == "++" || op == "--" => + { + Some(expr) + } + _ => None, + } +} + +/// Every whole word of a raw-text token, with its offset in that text. +fn words(text: &str) -> Vec<(u32, &str)> { + let bytes = text.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < bytes.len() { + if is_word_byte(bytes[i]) { + let start = i; + while i < bytes.len() && is_word_byte(bytes[i]) { + i += 1; + } + // A word a digit starts is a number; one a `'` precedes is the + // base and digits of a sized literal (`8'hFF`). Neither is a name. + if !bytes[start].is_ascii_digit() && (start == 0 || bytes[start - 1] != b'\'') { + out.push((start as u32, &text[start..i])); + } + } else { + i += 1; + } + } + out +} + +fn is_word_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$' +} + +/// True for an `` `include`` directive line. +fn is_include(text: &str) -> bool { + text.trim_start_matches('`').starts_with("include") +} + +/// True for the directives that make two regions of a file exclusive. +fn is_conditional(text: &str) -> bool { + let word: String = + text.trim_start_matches('`').chars().take_while(|c| c.is_ascii_alphabetic()).collect(); + matches!(word.as_str(), "ifdef" | "ifndef" | "elsif" | "else" | "endif") +} + +/// Sorts and merges ranges so a covering test can sweep them. +fn merge(ranges: &mut Vec) { + ranges.sort_by_key(|r| (r.start, r.end)); + let mut merged: Vec = Vec::with_capacity(ranges.len()); + for range in ranges.iter() { + match merged.last_mut() { + Some(last) if range.start <= last.end => last.end = last.end.max(range.end), + _ => merged.push(*range), + } + } + *ranges = merged; +} + +/// True when a merged, sorted range list covers `offset`. +fn covers(ranges: &[TextRange], offset: u32) -> bool { + ranges + .binary_search_by(|range| { + if range.end <= offset { + std::cmp::Ordering::Less + } else if range.start > offset { + std::cmp::Ordering::Greater + } else { + std::cmp::Ordering::Equal + } + }) + .is_ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scan(src: &str) -> Signals { + // The context has to outlive the scan, so it is built and consumed + // here; `Signals` owns everything a rule reads. + Signals::scan(&LintContext::new(src, None)) + } + + /// The declaration of `name`, and what was done to it. + fn signal<'a>(signals: &'a Signals, name: &str) -> (&'a Decl, &'a Usage) { + let decl = signals + .decls() + .iter() + .find(|d| d.name == name) + .unwrap_or_else(|| panic!("no declaration of `{name}`")); + (decl, signals.usage(decl).expect("a bound symbol")) + } + + /// `(drivers, reads, connected)` for one signal in a module body. + fn usage_of(body: &str, name: &str) -> (usize, usize, bool) { + let src = format!("module m (input logic ci, output logic co);\n{body}\nendmodule\n"); + let signals = scan(&src); + let (decl, usage) = signal(&signals, name); + (usage.drivers.len(), usage.reads, signals.connected(decl)) + } + + #[test] + fn every_left_hand_side_shape_is_a_write() { + for lhs in ["a", "a[0]", "a[1:0]", "(a)", "{a, co}", "{<<{a}}"] { + let body = format!(" logic [1:0] a;\n always_comb {lhs} = 2'b00;"); + assert_eq!(usage_of(&body, "a").0, 1, "{lhs} must be a write"); + } + } + + #[test] + fn a_whole_write_and_a_part_write_are_told_apart() { + let src = "module m;\n logic [1:0] a, b, c;\n always_comb a = 2'b0;\n\ + always_comb b[0] = 1'b0;\n always_comb c[1:0] = 2'b0;\nendmodule\n"; + let signals = scan(src); + assert!(signal(&signals, "a").1.drivers[0].whole); + assert!(!signal(&signals, "b").1.drivers[0].whole); + assert!(!signal(&signals, "c").1.drivers[0].whole); + } + + #[test] + fn a_name_read_inside_a_write_target_is_still_a_read() { + // `mem[addr] = x` writes `mem` and reads `addr`. + let src = "module m;\n logic [3:0] mem;\n logic addr;\n\ + always_comb mem[addr] = 1'b0;\nendmodule\n"; + let signals = scan(src); + assert_eq!(signal(&signals, "mem").1.drivers.len(), 1); + assert_eq!(signal(&signals, "addr").1.reads, 1); + assert_eq!(signal(&signals, "addr").1.drivers.len(), 0); + } + + #[test] + fn a_right_hand_side_is_a_read() { + let (drivers, reads, _) = usage_of(" logic a;\n assign co = a & ci;", "a"); + assert_eq!((drivers, reads), (0, 1)); + } + + #[test] + fn the_driver_kinds_are_told_apart() { + let src = "module m;\n\ + logic a; assign a = 1'b0;\n\ + logic b; always_comb b = 1'b0;\n\ + logic c; initial c = 1'b0;\n\ + logic d; task t; d = 1'b0; endtask\n\ + logic e = 1'b0;\n\ + event f; always @(posedge a) -> f;\n\ + endmodule\n"; + let signals = scan(src); + for (name, kind) in [ + ("a", DriverKind::Continuous), + ("b", DriverKind::Always), + ("c", DriverKind::Initial), + ("d", DriverKind::Routine), + ("e", DriverKind::Initializer), + ("f", DriverKind::Trigger), + ] { + let drivers = &signal(&signals, name).1.drivers; + assert_eq!(drivers.len(), 1, "{name}"); + assert_eq!(drivers[0].kind, kind, "{name}"); + } + } + + #[test] + fn the_override_family_keeps_its_own_kind_inside_any_block() { + // The bug this pins: `force`/`release`/`deassign` used to inherit the + // enclosing block's kind, which made a `force` inside an `always` + // block look like an ordinary second driver. + let src = "module m (input logic c);\n\ + logic a; always @(posedge c) force a = 1'b1;\n\ + logic b; always @(posedge c) release b;\n\ + logic d; initial deassign d;\n\ + logic e; task t; force e = 1'b0; endtask\n\ + endmodule\n"; + let signals = scan(src); + for (name, kind) in [ + ("a", DriverKind::Force), + ("b", DriverKind::Release), + ("d", DriverKind::Release), + ("e", DriverKind::Force), + ] { + let drivers = &signal(&signals, name).1.drivers; + assert_eq!(drivers.len(), 1, "{name}"); + assert_eq!(drivers[0].kind, kind, "{name}"); + assert!(drivers[0].kind.is_override(), "{name} is an override"); + } + } + + #[test] + fn only_a_release_establishes_no_value() { + let src = "module m (input logic c);\n\ + logic a; always @(posedge c) force a = 1'b1;\n\ + logic b; always @(posedge c) release b;\n\ + logic d; always_comb d = 1'b0;\n\ + endmodule\n"; + let signals = scan(src); + for (name, establishes) in [("a", true), ("b", false), ("d", true)] { + assert_eq!( + signal(&signals, name).1.drivers[0].establishes_a_value(), + establishes, + "{name}" + ); + } + } + + #[test] + fn two_writes_in_one_block_share_a_block_id_and_two_blocks_do_not() { + let one = "module m;\n logic a;\n always_comb begin\n a = 1'b0;\n a = 1'b1;\n\ + end\nendmodule\n"; + let signals = scan(one); + let drivers = &signal(&signals, "a").1.drivers; + assert_eq!(drivers.len(), 2); + assert_eq!(drivers[0].block, drivers[1].block, "one always block"); + + let two = "module m;\n logic a;\n always_comb a = 1'b0;\n always_comb a = 1'b1;\n\ + endmodule\n"; + let signals = scan(two); + let drivers = &signal(&signals, "a").1.drivers; + assert_ne!(drivers[0].block, drivers[1].block, "two always blocks"); + } + + #[test] + fn a_write_inside_a_generate_construct_is_marked() { + let src = "module m;\n logic a, b;\n always_comb a = 1'b0;\n\ + generate\n if (1) begin : g\n always_comb b = 1'b0;\n end\n\ + endgenerate\nendmodule\n"; + let signals = scan(src); + assert!(!signal(&signals, "a").1.drivers[0].in_generate); + assert!(signal(&signals, "b").1.drivers[0].in_generate); + } + + #[test] + fn every_unknown_direction_position_is_recognized() { + for body in [ + " logic a;\n sub u (.x(a));", + " logic a;\n sub u (a);", + " logic a;\n and g (a, ci, ci);", + " logic a;\n initial fill(a);", + ] { + let (drivers, _, connected) = usage_of(body, "a"); + assert_eq!(drivers, 0, "{body}"); + assert!(connected, "{body}"); + } + } + + #[test] + fn a_clocking_block_takes_its_signals_out_of_every_judgement() { + // `vlog_semantic` records no reference inside a clocking block, so the + // names have to leave through the token-level guard. + let src = "module m (input logic ci);\n logic a;\n clocking cb @(posedge ci);\n output a;\n endclocking\nendmodule\n"; + let signals = scan(src); + assert!(!signals.judgeable(signal(&signals, "a").0)); + } + + #[test] + fn an_implicit_named_connection_reaches_the_local_signal() { + // `.a` resolves to the *other* module's port, so the local signal is + // only reachable by name. + let (_, _, connected) = usage_of(" logic a;\n sub u (.a);", "a"); + assert!(connected); + } + + #[test] + fn a_wildcard_connection_blinds_the_module_it_is_in() { + let src = "module m;\n logic a;\n sub u (.*);\nendmodule\n\ + module n;\n logic b;\nendmodule\n"; + let signals = scan(src); + assert!(!signals.judgeable(signal(&signals, "a").0)); + assert!(signals.judgeable(signal(&signals, "b").0)); + } + + #[test] + fn an_include_in_a_module_body_blinds_the_module() { + // The include may declare, read or drive anything; a file-level one + // only brings in macro definitions. + let inside = "module m;\n logic a;\n `include \"body.svh\"\nendmodule\n"; + let signals = scan(inside); + assert!(!signals.judgeable(signal(&signals, "a").0)); + + let outside = "`include \"macros.svh\"\nmodule m;\n logic a;\nendmodule\n"; + let signals = scan(outside); + assert!(signals.judgeable(signal(&signals, "a").0)); + } + + #[test] + fn a_macro_or_an_unparsed_region_makes_a_name_unjudgeable() { + for src in [ + "module m;\n logic a;\n `DRIVE(a)\nendmodule\n", + "module m;\n logic a;\n @@@ a @@@;\nendmodule\n", + "module m;\n logic a;\n`ifdef A\n`endif\n logic b;\nendmodule\n", + ] { + let signals = scan(src); + let name = if src.contains("`ifdef A") { "b" } else { "a" }; + let judgeable = signals.judgeable(signal(&signals, name).0); + assert_eq!(judgeable, name == "b", "{src}"); + } + } + + #[test] + fn an_interface_declares_nothing_this_module_judges() { + let src = "interface bus;\n logic a;\nendinterface\nmodule m;\n logic b;\nendmodule\n"; + let signals = scan(src); + let names: Vec<&str> = signals.decls().iter().map(|d| d.name.as_str()).collect(); + assert_eq!(names, vec!["b"]); + } + + #[test] + fn ports_are_not_declarations_this_table_carries() { + let ansi = "module m (input logic a, output logic b);\n logic c;\nendmodule\n"; + let signals = scan(ansi); + let names: Vec<&str> = signals.decls().iter().map(|d| d.name.as_str()).collect(); + assert_eq!(names, vec!["c"]); + + // A non-ANSI body declaration redeclares the header port and binds no + // symbol of its own, so it can never be judged. + let non_ansi = "module m (a);\n input a;\nendmodule\n"; + let signals = scan(non_ansi); + assert!(signals.decls().iter().all(|d| d.symbol.is_none())); + } + + #[test] + fn nets_and_variables_are_told_apart() { + let src = "module m;\n wire a;\n logic b;\n reg c;\n tri d;\n int e;\nendmodule\n"; + let signals = scan(src); + for (name, is_net) in [("a", true), ("b", false), ("c", false), ("d", true), ("e", false)] { + assert_eq!(signal(&signals, name).0.is_net, is_net, "{name}"); + } + } + + #[test] + fn a_mention_outside_every_declaration_is_what_counts_as_used() { + let src = "module m;\n wire a;\n wire b;\n assign b = 1'b0;\nendmodule\n"; + let signals = scan(src); + assert!(!signals.mentioned_outside_declarations("a")); + assert!(signals.mentioned_outside_declarations("b")); + // A comment and a string literal are not mentions. + let quiet = "module m;\n wire a; // a\n string s = \"a\";\nendmodule\n"; + assert!(!scan(quiet).mentioned_outside_declarations("a")); + } + + #[test] + fn a_conditional_directive_between_two_offsets_is_found() { + let src = "module m;\n logic a;\n`ifdef X\n always_comb a = 1'b0;\n`else\n\ + always_comb a = 1'b1;\n`endif\nendmodule\n"; + let signals = scan(src); + let blocks: Vec = signal(&signals, "a").1.drivers.iter().map(|d| d.block).collect(); + assert_eq!(blocks.len(), 2); + assert!(signals.conditional_between(&blocks)); + assert!(!signals.conditional_between(&[blocks[0]])); + assert!(!signals.conditional_between(&[])); + } + + #[test] + fn raw_text_gives_up_its_words_and_nothing_else() { + assert_eq!( + words("`ASSERT(Foo_A, a_b, clk)"), + vec![(1, "ASSERT"), (8, "Foo_A"), (15, "a_b"), (20, "clk")] + ); + // A word a digit starts is a number, not a name. + assert_eq!(words("8'hFF + x1"), vec![(8, "x1")]); + assert_eq!(words("`endif"), vec![(1, "endif")]); + } + + #[test] + fn conditional_and_include_directives_are_recognized() { + for text in ["`ifdef A", "`ifndef A", "`elsif A", "`else", "`endif"] { + assert!(is_conditional(text), "{text}"); + } + for text in ["`define A 1", "`include \"x.svh\"", "`timescale 1ns/1ps"] { + assert!(!is_conditional(text), "{text}"); + } + assert!(is_include("`include \"x.svh\"")); + assert!(!is_include("`ifdef INCLUDE_ME")); + } + + #[test] + fn merged_ranges_answer_covering_questions() { + let mut ranges = vec![ + TextRange::new(10, 20), + TextRange::new(0, 5), + TextRange::new(15, 25), + TextRange::new(40, 41), + ]; + merge(&mut ranges); + assert_eq!(ranges.len(), 3, "the two overlapping ones merged: {ranges:?}"); + for (offset, want) in + [(0, true), (4, true), (5, false), (9, false), (10, true), (24, true), (25, false)] + { + assert_eq!(covers(&ranges, offset), want, "at {offset}"); + } + } +} diff --git a/crates/vlog_linter/tests/cases/multiply_driven.lint b/crates/vlog_linter/tests/cases/multiply_driven.lint new file mode 100644 index 0000000..925a0df --- /dev/null +++ b/crates/vlog_linter/tests/cases/multiply_driven.lint @@ -0,0 +1,163 @@ +# a variable driven from two always blocks is flagged at its declaration +#select multiply-driven,unused-waiver +module m (input logic c, output logic q); + logic a; +//^ 9 multiply-driven + always_comb a = c; + always_ff @(posedge c) a <= 1'b0; + assign q = a; +endmodule +==== +# the rule is off by default: the same source is quiet without #select +module m (input logic c, output logic q); + logic a; + always_comb a = c; + always_ff @(posedge c) a <= 1'b0; + assign q = a; +endmodule +==== +# a continuous assignment plus a procedural block is the same mistake +#select multiply-driven,unused-waiver +module m (input logic c, output logic q); + logic a; +//^ 9 multiply-driven + assign a = c; + always_comb a = 1'b0; + assign q = a; +endmodule +==== +# two continuous assignments to a variable are one driver too many +#select multiply-driven,unused-waiver +module m (input logic c, output logic q); + logic a; +//^ 9 multiply-driven + assign a = c; + assign a = 1'b0; + assign q = a; +endmodule +==== +# one block assigning a variable many times is one driver +#select multiply-driven,unused-waiver +module m (input logic c, output logic q); + logic a; + always_comb begin + a = 1'b0; + if (c) a = 1'b1; + end + assign q = a; +endmodule +==== +# a net may legally have as many drivers as it likes +#select multiply-driven,unused-waiver +module m (input logic c, output logic q); + wire a; + assign a = c; + assign a = 1'b0; + assign q = a; +endmodule +==== +# different bits from different blocks are left alone +#select multiply-driven,unused-waiver +module m (input logic c, output logic [1:0] q); + logic [1:0] a; + always_comb a[0] = c; + always_comb a[1] = 1'b0; + assign q = a; +endmodule +==== +# generate arms are exclusive, so two of them are one driver +#select multiply-driven,unused-waiver +module m #(parameter int W = 1) (input logic c, output logic q); + logic a; + generate + if (W == 1) begin : g0 + always_comb a = c; + end else begin : g1 + always_comb a = 1'b0; + end + endgenerate + assign q = a; +endmodule +==== +# `ifdef arms are exclusive for the same reason +#select multiply-driven,unused-waiver +module m (input logic c, output logic q); + logic a; +`ifdef FAST + always_comb a = c; +`else + always_comb a = 1'b0; +`endif + assign q = a; +endmodule +==== +# an initial block and a task body say nothing about which process runs them +#select multiply-driven,unused-waiver +module m (input logic c, output logic q); + logic a; + always_comb a = c; + initial a = 1'b0; + task t; + a = 1'b1; + endtask + assign q = a; +endmodule +==== +# an initializer takes the signal out of the running +#select multiply-driven,unused-waiver +module m (input logic c, output logic q); + logic a = 1'b0; + always_comb a = c; + always_comb a = 1'b1; + assign q = a; +endmodule +==== +# a name a macro mentions cannot be counted +#select multiply-driven,unused-waiver +module m (input logic c, output logic q); + logic a; + always_comb a = c; + always_comb a = 1'b0; + `NOTE(a) + assign q = a; +endmodule +==== +# an assign plus a force/release override block is not two drivers +#select multiply-driven,unused-waiver +module m (input logic clk, input logic bypass, output logic q); + logic a; + assign a = clk; + always @(posedge clk) begin + if (bypass) force a = 1'b1; + else release a; + end + assign q = a; +endmodule +==== +# an override anywhere takes the signal out of the rule, as initial does +#select multiply-driven,unused-waiver +module m (input logic c, output logic q); + logic a; + always_comb a = c; + always_comb a = 1'b0; + initial force a = 1'b1; + assign q = a; +endmodule +==== +# waived on the same line +#select multiply-driven,unused-waiver +module m (input logic c, output logic q); + logic a; // vfmt: waive multiply-driven + always_comb a = c; + always_comb a = 1'b0; + assign q = a; +endmodule +==== +# a waiver that waives nothing is reported +#select multiply-driven,unused-waiver +module m (input logic c, output logic q); + logic a; // vfmt: waive multiply-driven +//^ 12 unused-waiver + always_comb a = c; + assign q = a; +endmodule diff --git a/crates/vlog_linter/tests/cases/undriven_net.lint b/crates/vlog_linter/tests/cases/undriven_net.lint new file mode 100644 index 0000000..dab9907 --- /dev/null +++ b/crates/vlog_linter/tests/cases/undriven_net.lint @@ -0,0 +1,163 @@ +# a signal read by something and driven by nothing is flagged +#select undriven-net,unused-waiver +module m (output logic q); + wire a; +//^ 8 undriven-net + assign q = a; +endmodule +==== +# the rule is off by default: the same source is quiet without #select +module m (output logic q); + wire a; + assign q = a; +endmodule +==== +# every shape of drive silences it +#select undriven-net,unused-waiver +module m (input logic c, output logic q); + logic [1:0] a, b, d, e; + assign a = 2'b00; + always_comb b = 2'b00; + always_ff @(posedge c) d[0] <= 1'b0; + initial e = 2'b00; + assign q = |{a, b, d, e}; +endmodule +==== +# a declaration with an initializer is driven by it +#select undriven-net,unused-waiver +module m (output logic q); + wire a = 1'b0; + assign q = a; +endmodule +==== +# a signal nothing reads is unused-signal's business, not this rule's +#select undriven-net,unused-waiver +module m; + wire a; +endmodule +==== +# an instance connection may be an output, so the signal may be driven +#select undriven-net,unused-waiver +module m (output logic q); + wire a, b, d; + sub u (.x(a)); + sub2 v (b); + sub3 w (.d); + assign q = a & b & d; +endmodule +==== +# a gate connection is the same story +#select undriven-net,unused-waiver +module m (input logic c, output logic q); + wire a; + and g (a, c, c); + assign q = a; +endmodule +==== +# a call argument may be an output argument of a task +#select undriven-net,unused-waiver +module m (output logic q); + logic a; + initial begin + fill(a); + end + assign q = a; +endmodule +==== +# a name a macro mentions may be driven inside it +#select undriven-net,unused-waiver +module m (output logic q); + logic a; + `DRIVE_IT(a) + assign q = a; +endmodule +==== +# a name in a region that did not parse may be driven there +#select undriven-net,unused-waiver +module m (output logic q); + logic a; + @@@ a = 1 @@@; + assign q = a; +endmodule +==== +# an `include in the module body may drive anything +#select undriven-net,unused-waiver +module m (output logic q); + logic a; + `include "driver.svh" + assign q = a; +endmodule +==== +# an input port is driven by whoever instantiates the module +#select undriven-net,unused-waiver +module m (input logic b, output logic q); + assign q = b; +endmodule +==== +# an interface's signals are driven by whoever uses the interface +#select undriven-net,unused-waiver +interface bus; + logic a; + modport mp (input a); +endinterface +==== +# an event is driven by the trigger that fires it +#select undriven-net,unused-waiver +module m (input logic c, output logic q); + event e; + always @(posedge c) -> e; + always @(e) q = 1'b1; +endmodule +==== +# a force puts a value on the signal, so it is a drive +#select undriven-net,unused-waiver +module m (output logic q); + logic a; + initial force a = 1'b1; + assign q = a; +endmodule +==== +# a release takes an override away; it can never be what drives a signal +#select undriven-net,unused-waiver +module m (output logic q); + logic a; +//^ 9 undriven-net + initial begin + release a; + end + assign q = a; +endmodule +==== +# ... and a deassign is the same story +#select undriven-net,unused-waiver +module m (output logic q); + logic a; +//^ 9 undriven-net + initial deassign a; + assign q = a; +endmodule +==== +# a release next to a real driver changes nothing +#select undriven-net,unused-waiver +module m (input logic c, output logic q); + logic a; + always_comb a = c; + initial release a; + assign q = a; +endmodule +==== +# waived on the same line +#select undriven-net,unused-waiver +module m (output logic q); + wire a; // vfmt: waive undriven-net + assign q = a; +endmodule +==== +# a waiver that waives nothing is reported +#select undriven-net,unused-waiver +module m (input logic c, output logic q); + wire a; // vfmt: waive undriven-net +//^ 11 unused-waiver + assign a = c; + assign q = a; +endmodule diff --git a/crates/vlog_linter/tests/cases/unused_signal.lint b/crates/vlog_linter/tests/cases/unused_signal.lint new file mode 100644 index 0000000..e2c2f81 --- /dev/null +++ b/crates/vlog_linter/tests/cases/unused_signal.lint @@ -0,0 +1,118 @@ +# a signal nothing mentions again is flagged at its declared name +#select unused-signal,unused-waiver +module m; + wire a; +//^ 8 unused-signal + logic b; +//^ 9 unused-signal +endmodule +==== +# the rule is off by default: the same source is quiet without #select +module m; + wire a; +endmodule +==== +# a signal something reads is quiet, however it is read +#select unused-signal,unused-waiver +module m (input logic c, output logic q); + wire a; + logic [1:0] b; + assign a = c; + always_comb b = {1'b0, a}; + assign q = |b; +endmodule +==== +# ports are the module's interface and are never flagged +#select unused-signal,unused-waiver +module m (input logic clk, output logic q); +endmodule +==== +# a non-ANSI port declared in the body is a port too +#select unused-signal,unused-waiver +module m (a, b); + input a; + output b; +endmodule +==== +# the intentionally-unused convention: leading _, or unused in the name +#select unused-signal,unused-waiver +module m; + wire _spare; + wire unused_bits; + wire spare_unused; +endmodule +==== +# a name only a macro invocation mentions is used as far as vfmt can tell +#select unused-signal,unused-waiver +module m; + wire a; + `ASSERT_KNOWN(AKnown, a) +endmodule +==== +# a name only a compiler directive mentions is not flagged either +#select unused-signal,unused-waiver +module m; + wire a; +`ifdef USE_A + assign x = a; +`endif +endmodule +==== +# a name used only in a region that did not parse is not flagged +#select unused-signal,unused-waiver +module m; + wire a; + @@@ a @@@; +endmodule +==== +# an instance connected with .* may use anything the module declares +#select unused-signal,unused-waiver +module m; + wire a; + sub u (.*); +endmodule +==== +# the implicit .name connection form is a use +#select unused-signal,unused-waiver +module m; + wire a; + sub u (.a); +endmodule +==== +# a comment and a string literal are not uses +#select unused-signal,unused-waiver +module m; + wire a; // a is for apple +//^ 8 unused-signal + string s = "a"; +//^ 10 unused-signal +endmodule +==== +# an `include in the module body may use anything, so the module is silent +#select unused-signal,unused-waiver +module m; + wire a; + `include "body.svh" +endmodule +==== +# waived on the same line +#select unused-signal,unused-waiver +module m; + wire a; // vfmt: waive unused-signal +endmodule +==== +# waived from the line above +#select unused-signal,unused-waiver +module m; + // vfmt: waive unused-signal + wire a; +endmodule +==== +# a waiver that waives nothing is reported +#select unused-signal,unused-waiver +module m (input logic c, output logic q); + wire a; // vfmt: waive unused-signal +//^ 11 unused-waiver + assign a = c; + assign q = a; +endmodule diff --git a/docs/features/linter-core/README.md b/docs/features/linter-core/README.md index b79b631..fb1c02a 100644 --- a/docs/features/linter-core/README.md +++ b/docs/features/linter-core/README.md @@ -77,6 +77,10 @@ existed. `default_rules`, `rule_by_name`, `select_rules`, `UNUSED_WAIVER`. Rule *names* are the stable part: they appear in waivers in user source, so a rename is a breaking change to other people's files. + `LintContext` grew two methods in the `semantic-lints` round — + `semantics()` (the file's symbol table, analyzed on first use) and + `with_semantics()` (a caller lending its own) — both additive; + `from_parse`'s signature did not change. - `run(source, path, enabled)` never panics on any input and never writes anything; `LintContext::new` never fails. - Findings come back sorted by `(span.start, span.end, rule)`. @@ -167,6 +171,25 @@ Honest reading of that table: cannot fully parse still gets linted for what it can see. That is also the caveat — AST-rule counts above are a **lower bound**. +**Rules added since.** The table above is this round's eight; `lint-rules-2` +added five naming/SV-ness rules and `semantic-lints` three more. The default +run's total moved to **7932 over 106 files** with the naming rules; the three +semantic rules are off by default and add nothing to it. Their own corpus +numbers, measured with `--select`: + +| Rule | Default | Fix | Violations | Files | +|---|---|---|---|---| +| `unused-signal` | off | — | 52 | 10 | +| `undriven-net` | off | — | 3 | 2 | +| `multiply-driven` | off | — | 0 | 0 | + +All three read the symbol table rather than the syntax tree, and all three +ship off by default because a single-file analysis cannot see a signal used +from another file's hierarchy. Every finding above was read against its +source and none is wrong; the per-finding judgement, the guards that keep +them quiet and the on/off reasoning are in +`docs/features/semantic-lints/README.md`. + ## Waiver semantics as implemented ```systemverilog diff --git a/docs/features/refactor/README.md b/docs/features/refactor/README.md index 76800b1..d4b4b11 100644 --- a/docs/features/refactor/README.md +++ b/docs/features/refactor/README.md @@ -167,7 +167,7 @@ built but nothing consumes yet. Ordered by value ÷ cost: - [x] **Module hierarchy** — "who instantiates X / what does X instantiate", as LSP callHierarchy (modules as the nodes) or a custom request the extension renders; the index already knows both directions. -- [ ] **Semantic lint rules** — unused-signal, undriven-net, +- [x] **Semantic lint rules** — unused-signal, undriven-net, multiply-driven: TODO.md §7 calls this the differentiation Verible cannot do, `vlog_semantic` has existed for rounds, and no semantic rule ships yet. @@ -266,6 +266,7 @@ commit — in order: - [x] M9 file-watching — done, QA clean first pass, reviewed - [x] M10 include-nav — done, one QA HIGH reworked, reviewed - [x] M11 hierarchy — done, QA doc-fixes in-round, reviewed +- [x] M12 semantic-lints — done, one QA medium reworked, reviewed ## Work log diff --git a/docs/features/semantic-lints/README.md b/docs/features/semantic-lints/README.md new file mode 100644 index 0000000..98a90ce --- /dev/null +++ b/docs/features/semantic-lints/README.md @@ -0,0 +1,895 @@ +# semantic-lints + +## Goal + +The first three lint rules vfmt writes against the *symbol table* rather than +the syntax tree (TODO.md §8, M12): `unused-signal`, `undriven-net` and +`multiply-driven`. TODO.md §7's non-goal — "no semantic claims in v1 lint +rules; semantic rules only after `vlog_semantic` exists" — is crossed here, +which is the whole point: these are the rules Verible structurally cannot +write, because each one needs to know which declaration a name refers to. The +round also wires the analysis into `LintContext` so `vfmt check` and the +language server both reach it through the existing one-parse path, and pays +for it only when a semantic rule actually runs. + +The bar the round was built to is **not crying wolf**. A style rule that +misfires is an annoyance; a semantic rule that tells an engineer their signal +is undriven when it is not costs them a debugging session and their trust in +the tool. Every design decision below leans to silence, and each one is +listed as a decision rather than left implicit. + +## Assumptions + +- **A use with no direction on it must be classified from context.** + `vlog_semantic::Reference` records *that* a name was used, never whether it + was read or written. `crates/vlog_linter/src/signals.rs` derives that from + the AST position the use is written in: an assignment's left-hand side is a + write, an instance connection or a call argument is *unknown*, and + everything else that resolved to a declaration is a read. +- **Unknown means silent.** An instance connection's direction is not looked + up in the instantiated module — not even when that module is in the same + file. `.port(sig)` may be an output, so `sig` is never called undriven. The + same goes for a gate connection, a task or function call argument, a + `clocking` block's signals, and the implicit `.name` connection form. +- **A name a macro, a compiler directive, an attribute, a verbatim block + (`constraint`/`covergroup`/concurrent assertion) or an unparsed region + mentions is dropped from every judgement.** vfmt does not expand macros and + does not evaluate directives, so what those regions do to a signal is + unknowable. This is measured, not theoretical: it is what keeps + `` `ASSERT_KNOWN(FooKnown_A, foo) `` from making `foo` look unused. +- **A module that hides code is not judged at all.** Two ways to hide it: an + instance connected with `.*` (which reads and drives same-named signals + without writing any of their names down) and an `` `include`` written + *inside* the module body (arbitrary code vfmt does not follow — this is + exactly how `prim_rom.sv` loads its memory array). A file-level + `` `include`` does not blind anything: it brings in macro definitions, and + any macro *use* is already guarded above. +- **Ports are the module's interface, not its business.** No rule reports a + port. An input is driven by the instantiating file, an `inout` from either + side, and an unused port is the caller's problem. Only item-level `wire`/ + `logic`/`reg`/... declarations inside a `module` are candidates. +- **Interfaces, packages, classes, and block-local variables are out of + scope.** An interface's signals are driven by whoever uses the interface; a + variable declared inside an `always` block is a different (and smaller) + question. Both are honest gaps, not oversights. +- **Single file, single elaboration.** These rules see one file. A signal + read or driven from *another* file through a hierarchical path + (`tb.dut.internal_sig`) is invisible to them — the one false-positive mode + that survives every guard above, and the reason all three ship **off by + default** (see "The on/off ruling" below). +- **The intentionally-unused convention is Verilator's, not Verible's.** + Verible has no unused-signal rule to be compatible with, so there is no + Verible spelling to match. Verilator's `--unused-regexp` defaults to + `*unused*`; vfmt exempts a name containing `unused` (case-insensitive) or + starting with `_`. It is not configurable this round — that waits on the + `lint` key in `vfmt.toml`, like every other rule setting. +- **`analyze` is exact enough to lint on.** The `vlog-semantic` corpus test + asserts every one of its 95 193 name spans slices back to the name it + claims; these rules trust `references_of` for "is this used" and the + reference table for "what does this name mean here". + +## Handshakes + +**Consumed** + +- `vlog_semantic` — **new dependency of `vlog_linter`**, justified here and in + `Cargo.toml`. It is a workspace crate depending on `vlog_parser` alone, so + the linter's external dependency surface is unchanged (still zero: + `cargo tree -p vlog_linter -e normal` is `vlog_parser` + `vlog_semantic`, + both path crates). Used API: `analyze`, `Semantics::{symbols, references, + references_of}`, `Reference::resolved`, `Symbol::{name, name_span}`, + `SymbolId`. Nothing in `vlog_semantic` was modified — the lead's + pre-authorization for a minimal read/write classification **went unused**, + because the classification wants AST context (which statement, which item, + which generate arm) that the binder does not keep and the linter has for + free. Recorded so the authorization is not read as taken. +- `vlog_parser::ast` — the item, statement and expression shapes + `signals.rs` walks, plus `token::TokenKind` for the whole-word mention + scan. Two token facts are load-bearing: a macro invocation is a single + `Ident` token whose text starts with a backtick and carries its arguments + verbatim, and a line directive is a single `Directive` token carrying the + whole line. Both are scanned for words, so a name only a macro mentions is + still seen. + +**Promised** + +- Three new stable rule names: `unused-signal`, `undriven-net`, + `multiply-driven`. All three are diagnose-only — `Rule::fix()` is `None` + and no violation carries a `Fix`. There is no safe automatic repair for any + of them: deleting a declaration, inventing a driver or removing one all + change what the code means. +- `LintContext` gains two public methods, both additive: + `semantics() -> &Semantics` (analyzes on first use) and + `with_semantics(&Semantics)` (lends a caller's). `from_parse`'s signature + is **unchanged**, so no existing caller had to move. +- The analysis is lazy: a `LintContext` on which no semantic rule ever runs + never calls `analyze`. Measured — a default `vfmt check` over the corpus is + byte-identical and time-identical to the one before this round. +- The signal table is built once per context and shared by all three rules, + so enabling three costs what enabling one costs. Also measured. + +**Requested of others (not done here)** + +- *whoever owns the workspace index*: the single false-positive mode left in + `unused-signal`/`undriven-net` is cross-file hierarchical use + (`tb.dut.sig`). `WorkspaceIndex` already scans every file in the project; + a "does any file in the workspace mention this name" query would close it, + and is the precondition for these rules defaulting on. Filed here rather + than attempted: it changes a rule from single-file to project-wide, which + is a design decision, not a patch. +- *config-discovery's owner*: the intentionally-unused convention wants to be + a `vfmt.toml` setting (`[lint.unused-signal] ignore = "..."`), for the same + reason the naming styles do. Restated, unchanged. + +## The three rules + +### `unused-signal` + +Flags a `wire`/`logic`/`reg`/... declared at item level in a `module` that + +1. bound a symbol (a redeclaration binds none and is never judged), +2. has **zero** references in `vlog_semantic`'s table, and +3. is not mentioned anywhere else in the file's tokens. + +Rule 3 is the insurance. The mention scan walks the whole token stream — +comments and string literals excluded, macro invocations, directive lines, +attributes and unparsed regions *included* — and subtracts every position +that is a declared name. If anything is left, the signal is not reported. +Being name-based rather than scope-based, it costs false negatives (an unused +`count` in one module is shielded by a used `count` in the next); that is the +harmless direction, and it is what makes the rule safe in a file full of +macros. + +### `undriven-net` + +Flags a signal that is **read** somewhere and written nowhere. Silent about: +ports, anything connected to an instance, a gate, a clocking block or a call +argument, anything declared with an initializer, anything a macro or an +unparsed region mentions, anything in a `.*` or `` `include``-bearing module, +and anything nothing reads (that is `unused-signal`'s subject). A drive is any +of: a continuous `assign`, a procedural assignment in an `always*`, `initial` +or `final` block, an assignment in a function or task body, a declarator +initializer, a loop-variable assignment, `x++`, `-> ev` for a named event, or +a **`force`** — a simulation-only override, but one that does put a value on +the signal. **`release` and `deassign` are not drives**: they take an +override *away*, so a signal whose only write is a release is still driven by +nothing, and this rule says so. Whole-signal and part-select writes both +count. + +### `multiply-driven` + +Flags a **variable** (never a net — a multiply-driven `wire` is what a `tri` +bus is made of) with more than one driver, counting only continuous `assign`s +and `always*` blocks. Two `always` blocks, an `assign` plus an `always`, or +two `assign`s all report. It steps aside entirely when the signal has any +driver that is: + +- a **part-select** write (`a[0]` here, `a[1]` there). Still illegal for + `always_comb`/`always_ff`, but proving it needs the bit ranges resolved, + and a conservative rule does not guess. This was the explicitly-flagged + false-positive risk and it is answered by silence. +- inside a **`generate`** construct, where only one arm of an `if`/`case` is + ever elaborated; +- an **`initial`/`final`** block or a **function/task body**, neither of + which says which process runs it; +- a **declarator initializer**, which is an initial value; +- an **event trigger**; +- a **`force`/`release`/`deassign`** override. These are simulation-only + directives with no synthesis meaning: a `force` replaces whatever drives a + signal for as long as it holds, so it is never a *second* driver, and a + `release` establishes nothing at all. Excluding them is deliberately wider + than "do not count them" — like `initial` and a task body, one anywhere on + a signal takes that signal out of the rule, because a forced signal is + verification-harness territory this rule stays out of. + +It also steps aside when a conditional-compilation directive +(`` `ifdef``/`` `else``/`` `endif``) is written between the first and last +driver — the preprocessor's spelling of the same exclusivity `generate` has. +vfmt parses both arms of an `` `ifdef`` as ordinary items, so without this +guard the `` `ifdef FAST / `else `` pattern would report every time. + +## The corpus measurement, and the on/off ruling + +Release build, `vfmt check corpus --select --output-format json`, over +the 860 `.v`/`.sv`/`.svh` files in `corpus/` (Ibex, OpenTitan, PULP +common_cells, picorv32), 2026-08-25: + +| rule | violations | files | wrong answers found on inspection | +|---|---:|---:|---| +| `unused-signal` | 52 | 10 | 0 | +| `undriven-net` | 3 | 2 | 0 | +| `multiply-driven` | 0 | 0 | 0 | + +Every finding was read against its source. All 55 are *true statements about +the code*; none is a signal the file actually uses or drives. + +**`unused-signal`, all 52, judged:** + +| finding | verdict | +|---|---| +| `picorv32.v:221-252` `dbg_reg_x0` … `dbg_reg_x31` (32 of them) | real — debug taps under `` `ifdef DEBUGREGS``, declared to be watched in a waveform viewer, never read by the RTL | +| `picorv32.v:375 mem_busy` | real — dead declaration | +| `ibex_if_stage.sv:768-772` `predicted_branch_nt_pc_d`, `awaiting_instr_after_mispredict_q/_d`, `mispredicted` | real — four dead declarations in shipping ibex RTL, each named once in the whole file | +| `ibex_register_file_fpga.sv:46 mem_o_a`, `mem_o_b` | real — dead declarations, one line, no other mention | +| `alt_lsu.sv:59-77` (6) | real — a formal-verification stub of the LSU with most logic removed; the declarations stayed | +| `cdc_fifo_gray.sv:251 rptr_bin_d`, `rr_arb_tree.sv:195 lower_empty`, `clock_divider_counter.sv:67,70` (2), two `common_cells` testbench signals | real — dead declarations, one of them next to the commented-out code that used it | +| `prim_alert_tb.sv:56 default_spinwait_timeout_ns` | real — assigned at declaration, read by nothing | + +**`undriven-net`, all 3, judged:** `unread.sv:21 x` (a module whose *purpose* +is to consume a signal: `logic x; assign d_i = x;` inside +`` `ifdef TARGET_VIVADO``, with `x` deliberately undriven — the file even +carries `/* verilator lint_on UNUSED */`), and `alt_lsu.sv:65,66` +`data_be`/`data_wdata` (the same stripped formal stub: declared, wired to an +output port, assigned nowhere). + +**`multiply-driven`: zero.** The rule said nothing about 860 files of good +RTL, which is the strongest quietness evidence available and the same score +`always-comb-blocking` posts. + +**Ruling: all three ship `default_on() == false`.** Not because the corpus +was noisy — it was not, 0 wrong answers out of 55 — but because of what the +corpus *findings* are. The largest single cluster (32 of 52 `unused-signal` +hits) is picorv32's debug taps: signals declared precisely so that something +*outside the file* can look at them. That is the one false-positive mode no +guard in this round can close, because closing it means leaving the file. A +first-of-its-kind rule that would put 33 warnings on picorv32's main source +file is not one to switch on for everybody by default. + +Two consequences recorded honestly: + +- `multiply-driven` is the closest to a default-on rule — it reports a + violation of IEEE 1800 §6.5, it scored 0/860, and cross-file use cannot + create a second *driver*. It is off for now for cost symmetry (enabling any + semantic rule costs the analysis, below) and because a rule with no + demonstrated find has not earned a default. + **How much weight 0/860 carries, honestly (QA finding, 2026-08-25):** less + than it looks. QA reproduced a false positive this corpus could never have + shown — an `assign` plus a `force`/`release` override block, where + `force`/`release` were inheriting the enclosing block's driver kind. Only 2 + of the 860 files use either keyword at all, and both write through a + hierarchical path the rule ignores for other reasons, so the score was + silent about the whole surface. The bug is fixed (see the work log below, + and the `.lint` cases that now pin both directions), but the lesson stands: + 0/860 measures this corpus's shapes, not the rule's full false-positive + surface. Verification-flavoured RTL — `force`/`release`, hierarchical + drives, `bind`-ed overrides — is thin in this corpus, and that is exactly + the code `multiply-driven` would meet first if it were switched on. +- The path to defaulting the other two on is the workspace index handshake + above, not more guards. + +### What the analysis costs + +Same corpus, best of five runs, this machine: + +| run | 1 thread | 10 cores | +|---|---:|---:| +| `vfmt check` before this round | 0.21 s | 0.07 s | +| `vfmt check` after (semantic rules off) | 0.22 s | 0.07 s | +| `vfmt check --select ,unused-signal` | 0.26 s | 0.07 s | +| `vfmt check --select ` + all three | 0.26 s | 0.07 s | + +Reading it: the default run is unchanged — proven byte-for-byte, not +inferred, by diffing the whole-corpus JSON and stderr of this build against a +`git worktree` build of `HEAD` (identical, including the 359 parse-error +lines). Turning on a semantic rule costs about **45 ms over 860 files, ~50 µs +per file, +20 % of a single-threaded check** — that is `analyze` plus one +AST-and-token walk. Turning on all three costs the same as turning on one, +which is the shared table doing its job. In parallel the whole thing +disappears into the worker pool. + +## Status / TODO + +- [x] `LintContext::semantics()` (lazy) + `LintContext::with_semantics()` + (lent); `from_parse` unchanged. +- [x] `crates/vlog_linter/src/signals.rs`: declarations, read/write/unknown + classification, driver kinds and blocks, the opaque-name guard, the + whole-word mention scan, the `.*` / `` `include`` blindness rule. +- [x] `unused-signal`, `undriven-net`, `multiply-driven` — registered, + documented, diagnose-only, off by default. +- [x] Server wiring: `vfmt_server` lends the document's own `Semantics`, so + a keystroke never analyzes twice. +- [x] `force`/`release`/`deassign` classified as their own driver kinds, out + of `multiply-driven` entirely and half-out of `undriven-net` (QA + finding, fixed 2026-08-25). +- [x] 69 new unit tests: 23 in `signals.rs` (the classification), 43 across + the three rule modules, 2 in `context.rs` (lazy vs lent analysis), 1 in + `vfmt_server::lint` (the server reads the document's own table). +- [x] 52 `.lint` cases across three new case files — 16 + 20 + 16 — + covering violating / clean / waived / unused-waiver and every guard. +- [x] Corpus measurement, per-finding judgement, and the on/off ruling above. +- [x] `rules_markdown` golden test pins the three new rows; + `linter-core`'s rule table updated. +- [ ] Cross-file use through the workspace index — the handshake above, and + the precondition for defaulting any of these on. +- [ ] Block-local variables (`logic tmp;` inside an `always` block) and + interfaces as `unused-signal` subjects. +- [ ] Direction-aware instance connections: when the instantiated module is + in the same file, its port directions *are* knowable, which would let + `undriven-net` see an output connection as a driver instead of an + unknown. Deliberately not done — it is a second resolution mechanism + and wants the workspace index behind it anyway. +- [ ] Per-rule configuration of the intentionally-unused convention — needs + the `vfmt.toml` `lint` key. + +## Work log + +### 2026-08-25 — dev + +- **Read first**: `linter-core`, `lint-rules-2`, `vlog-semantic`, + `one-parse`, `lint-harness`, plus `vlog_linter/src/` and + `vlog_semantic/src/model.rs`. Confirmed the premise of the task: + `Reference` carries no read/write kind, so the rules had to classify uses + themselves. +- **Where the classification lives — decision.** The lead pre-authorized a + minimal read/write extension inside `vlog_semantic`. I did not take it. + Classification needs *AST context the binder does not keep*: which item + owns a write (two writes in one `always` block are one driver, two blocks + are two), whether that item sits in a `generate` arm, whether an + `` `ifdef`` separates two drivers, whether a use is an instance connection. + `bind.rs` throws all of that away by design, and adding it would push + driver semantics — a lint concept — into the crate the language server + shares. The linter has the tree already, so the whole classification is + one 658-line module (`signals.rs`, plus 275 lines of its own tests) and + `vlog_semantic` is untouched. +- **Lazy analysis — decision.** Making `from_parse` take a `Semantics` + would have forced every caller to build one, i.e. made `vfmt check` pay for + an analysis nobody reads on a default run. Instead `LintContext` holds a + `OnceCell` filled on first use, plus `with_semantics` for the + server, which analyzes every buffer anyway. `from_parse`'s signature never + moved. Same treatment for the signal table itself + (`OnceCell`), which is why three semantic rules cost what one + costs. +- **Three corpus rounds, two of which changed the design.** The first run + scored 56 `unused-signal` and **42** `undriven-net`. Reading the 42 found + two false-positive families, both now closed: + 1. **The implicit `.name` connection** (`prim_subreg.sv`'s `.wr_en,`, + `uart.sv`'s `.reg2hw,`, 13 of ibex_top_tracing's `rvfi_ext_*`). The + reference recorded at `.wr_en` resolves to the *instantiated module's + port*, in another file's scope, so the local signal was never marked + connected. Now the connection's name marks the local signal connected + directly. 34 of the 42 were this. + 2. **`` `include`` inside a module body** (`prim_rom.sv`, `prim_xilinx_rom.sv`: + `mem` is loaded by `` `include "prim_util_memload.svh" ``). A module + with an in-body include now judges nothing. + A third run, after `-> ev` became a drive, cleared picorv32's two + `ser_sample` findings (`event ser_sample;` triggered with `-> ser_sample` + was being read as "read, never driven"). Final: 52 / 3 / 0, zero wrong. +- **Guards that came from thinking, not from the corpus** (each has a test): + `.*` blinds a module; a name inside a macro, a directive, an attribute, a + verbatim block or an `Error` leaf is dropped; a clocking block's signals are + dropped (`vlog_semantic` records no reference inside one, so the *token* + guard is what catches them — found while testing, and the reason the + clocking case is a `judgeable` test and not a `connected` one); an + expression statement that is not `x++` is a call whose arguments may be + `output` arguments. +- **The `` `ifdef`` guard for `multiply-driven`** exists because vfmt parses + both arms of a conditional as ordinary items — the same property that makes + `unused-signal` see through an `` `ifdef``. Two `always_comb` blocks in + opposite arms would otherwise report every time. Implemented as "is a + conditional directive written between the first and last driver", which is + narrow: a directive elsewhere in the file excuses nothing. +- **Part-selects: silence.** The task named this as the judgement call. + `a[0]` in one block and `a[1]` in another *is* illegal in `always_comb`, but + it is also the everyday shape of legacy `always` code, and vfmt does not + resolve bit ranges. Any partial driver takes the signal out of the rule. +- **On/off**: measured, judged per finding, ruled off for all three, with the + reasoning and the dissent for `multiply-driven` written above rather than + buried. +- **Scope**: `crates/vlog_linter/{Cargo.toml,src/context.rs,src/lib.rs, + src/signals.rs,src/rule_docs.rs,src/registry.rs,src/rules/**,tests/cases/**}`, + `crates/vfmt_server/src/lint.rs` (the two-line lend + one test, which the + task authorized), this README, `docs/features/linter-core/README.md`'s rule + table, and the top-level `README.md`'s Linting section (the three rules and + their off-by-default footnote — changed because that section called the + rule set "syntactic", which this round made false; the bullet originally + omitted it, QA's nit). `Cargo.lock` gains the workspace-internal + `vlog_linter → vlog_semantic` edge. **`TODO.md` deliberately not touched** + (lead's instruction for this round, overriding CLAUDE.md's default). +- **Gates**: `cargo fmt --all --check` clean; `cargo clippy --all-targets + --workspace` silent; `cargo test --workspace` 1535 passed / 0 failed across + 34 suites (baseline at `HEAD` a96c908, measured in a throwaway + `git worktree`: 1474 — the delta is exactly this pass's 61 new tests); + `cargo test -p vlog_linter` 182 unit (was 122) + 14 case-harness + 1 doc. CLI smoke: + all three rules fire on a crafted module, the `_ignored` name is exempt, a + `// vfmt: waive unused-signal` suppresses its finding, the default run on + the same file is clean, and JSON carries `"fix":null`. + +### 2026-08-25 — dev (QA follow-up: the `force`/`release` ruling) + +QA's should-fix, and the lead's ruling on it, implemented in full. + +- **`force`/`release`/`deassign` now carry their own `DriverKind`.** + `signals.rs`'s `body()` used to fold `StmtKind::ForceRelease` into the same + arm as `StmtKind::Assign`, so an override inherited the enclosing block's + kind — `Always` inside an `always`, `Initial` inside an `initial`. Two new + variants: `Force` (`force x = ...;`) and `Release` (`release x;` / + `deassign x;`), told apart by the statement's own keyword, which the parser + stores verbatim and only ever sets to one of those three + (`parser.rs:3609-3622`, read to confirm — procedural `assign`/`deassign` + statements are *not* routed here; QA established they become `Error` leaves + and are already opaque). Two predicates carry the meaning where the rules + need it: `DriverKind::is_override()` and `Driver::establishes_a_value()`. +- **`multiply-driven` excludes the family exactly like `Initial`/`Routine`/ + `Trigger`**: one override anywhere on a signal takes the signal out of the + rule. QA's repro (`assign a = clk;` plus `force`/`release` inside an + `always` block) reports nothing now — verified through the CLI, not only in + a unit test. +- **`undriven-net` splits the family**: a `force` counts as a drive (it does + put a value on the signal), a `release`/`deassign` does not (it removes an + override — it cannot be the only thing driving a signal). QA's second repro + now reports `` `a` is read but never driven``, which is the correct answer + and closes the undocumented false negative. +- **Attack tests in both directions**, per hard-invariant 4's mindset, and + every one checked non-vacuous by sabotage: + - `an_override_block_is_not_a_second_driver` — QA's exact repro. + - `an_override_anywhere_takes_the_signal_out_of_the_rule` — two *real* + drivers plus a `force` is silence. Deleting `is_override()` from + `unclassifiable()` turns this one red on its own; the other override + tests do not, because giving the family its own kind already keeps it out + of the `Always`/`Continuous` driver count. Recorded because it means the + wider exclusion is a *second*, independent decision, and it needed its + own test to be real. + - `an_override_does_not_hide_a_real_conflict_it_did_not_create` — the same + two drivers without the override still report, so the exclusion cannot be + reached by accident. + - `a_force_is_a_drive_but_a_release_is_not` and + `a_released_signal_that_something_really_drives_is_quiet` — both + directions of the `undriven-net` split. Reverting the rule to + `!usage.drivers.is_empty()` turns the first one red. + - `the_override_family_keeps_its_own_kind_inside_any_block` and + `only_a_release_establishes_no_value` in `signals.rs` — the + classification itself, for all three keywords in `always`, `initial` and + a task body. + - Six new `.lint` cases: four in `undriven_net.lint` (force-drives, + release-only *violating* with its marker, deassign-only violating, + release-next-to-a-real-driver clean) and two in `multiply_driven.lint` + (QA's repro, and the override-anywhere case). A deliberate wrong column + in the release-only marker produces the harness's two-direction report, + so the new cases are not vacuous either. +- **Corpus unchanged**, checked rather than assumed: 52 / 3 / 0, and the + three JSON outputs are byte-identical to the pre-fix run — the corpus's two + `force`/`release` files write through hierarchical paths these rules do not + track, which is exactly why the corpus never showed the bug. Default + `vfmt check` over the corpus is still byte-identical (stdout **and** + stderr) to a `git worktree` build of `HEAD` a96c908. +- **README**: the `undriven-net` driver list now names `force` and states + that `release`/`deassign` are not drives; `multiply-driven`'s exclusion + list gained the override bullet with the "deliberately wider" note; and the + "closest to default-on" argument now carries QA's caveat that 0/860 does + not cover the `force`/`release` surface at all. +- **Gates after the fix**: `cargo fmt --all --check` clean, `cargo clippy + --all-targets --workspace` silent, `cargo test --workspace` **1543 passed / + 0 failed** across 34 suites (1535 before this pass; the delta is the 8 new + unit tests). `cargo test -p vlog_linter` 190 unit + 14 case-harness + 1 + doc. No version bump, `TODO.md` still untouched. + +## QA log + +### 2026-08-25 — QA + +Verdict: **ship-after-fixes**. No hard-invariant break, no corruption risk +(all three rules are diagnose-only — `Rule::fix()` is `None`, confirmed by +grep and by every rule's `it_points_at_the_declared_name` test asserting +`fix.is_none()`), and the byte-identical/corpus-count claims all reproduce +exactly. One should-fix correctness finding below (`force`/`release` +misclassification), plus two low-severity notes. Nothing was corrupted or +made worse; the should-fix is a real gap in the rule that this round itself +flags as "closest to default-on." + +**Gates.** `cargo fmt --all --check` clean. `cargo clippy --all-targets +--workspace` silent (forced rebuild by touching `lib.rs` first, per the +house discipline). `cargo test --workspace`: **1535 passed**, 0 failed, +summed from every `test result:` line — matches the claim exactly. +`node editors/vscode/smoke.js target/debug/vfmt-server`: `OK`. No `unsafe`; +the only `.unwrap()`/`.expect()`/`panic!` in the five touched files +(`signals.rs:675-676`, `context.rs:355`) are inside `#[cfg(test)]` modules. +No `#[allow]` anywhere in the new code. `cargo tree -p vlog_linter -e +normal`: `vlog_parser` + `vlog_semantic`, both path crates — matches the +Handshakes claim and the justification comment in `Cargo.toml`. Crate +version stayed `0.4.2` (no bump), `TODO.md` untouched, confirmed by +`git status`. + +**Byte-identical claim — verified myself, not re-trusted.** Built HEAD +(`a96c908`) in a `git worktree`, release profile, alongside the working +tree's release build. `vfmt check corpus --output-format json` from both +binaries: stdout **byte-identical**, stderr **byte-identical** (same +single lex-error line and the same "found 7932 violations, 1 file could +not be checked" summary — the corpus grew a naming-rule finding since the +lint-rules-2 round, but the two builds under test agree with each other, +which is the claim). Exit code 2 both. The default corpus run **contains +no semantic-rule finding** — confirms "the default run adds nothing." + +**Corpus counts — reproduced exactly.** `--select unused-signal`: 52 +violations / 10 files. `--select undriven-net`: 3 / 2. `--select +multiply-driven`: 0 / 0. Per-file breakdown matches the README's table +verbatim (33 picorv32.v, 6 alt_lsu.sv, 4 ibex_if_stage.sv, 2 +ibex_register_file_fpga.sv, 2 clock_divider_counter.sv, and 1 each for the +rest). Independently spot-read three hits against source, not just trusted +the dev's table: +- `picorv32.v:375 mem_busy` — declared with an initializer, `grep -n + mem_busy` finds only the declaration line. Real. +- `ibex_if_stage.sv:768 predicted_branch_nt_pc_d` — declared alongside + `predicted_branch_nt_pc_q`; grep finds only the one declaration line for + the `_d` name. Real. +- `common_cells/src/unread.sv:21 x` — read the whole 24-line file: `x` is + declared and assigned to the input port `d_i` only inside `` `ifdef + TARGET_VIVADO``, bracketed by `/* verilator lint_off/on UNUSED */`, + exactly the "deliberately undriven, module exists to consume a signal" + shape the README describes. Real. + +All three agree with the dev's judgement. **0 wrong answers confirmed.** + +**The cross-file false-positive mode — reproduced on purpose.** Built a +two-file fixture (`dut.sv` declaring `logic dbg_probe;` with no local +driver or read, `tb.sv` instantiating it and reading `d.dbg_probe` +hierarchically). Linting `dut.sv` alone: `unused-signal` fires on +`dbg_probe` — exactly the documented blind spot, and exactly the +picorv32 `dbg_reg_x0..x31` shape. Note for the record: the **same-file** +version of this test (both modules in one file) does **not** reproduce +the false positive, because the whole-token mention scan +(`mentioned_outside_declarations`) sees the literal identifier text +`dbg_probe` in the hierarchical reference `d.dbg_probe` and treats it as +"mentioned," even though `vlog_semantic` never resolves a reference to it. +This is a second, independent guard accidentally covering part of the +same blind spot — worth knowing, not worth changing: it only helps when +the hierarchical reader happens to sit in the same file, which is not the +case that matters (waveform viewers, VPI, and other-file testbenches carry +no source text at all). + +**Attack results.** Per rule, in the order of the QA brief: + +*`unused-signal`* — all silent as documented: macro-argument-only use +(`` `ASSERT_KNOWN(FooKnown_A, foo)``), assertion/property-only use +(`assert property (...)`), different `` `ifdef`` arms (declare in `A`, use +in `B` — silent because the token scan doesn't respect `` `ifdef`` +boundaries, the documented false-negative direction), unpacked-struct +member read, genvar (never a candidate — `ItemKind::Genvar` isn't scanned +into `Decl`s at all, confirmed by reading `signals.rs`'s `item()` match, +which only handles `ItemKind::DataDecl`). Whole-word matching confirmed +live: `clk` unused next to a used `clk_en` **is** flagged (no substring +shielding). + +*`undriven-net`* — input port read: silent (unit-tested, re-confirmed +live). Force-only-driven signal: silent (confirmed live — +`force a = 1'b1;` inside `initial` satisfies the drive). Task +output-argument: silent (`compute(result)` with `result` never assigned +elsewhere — confirmed live, `unknown.push` covers the whole call-statement +span). `readmemh`-loaded memory: silent (confirmed live — `$readmemh(...)` +is an `ExprStmt` whose whole span is pushed to `unknown`, same mechanism +as a task call). The closed implicit-`.name` FP family: reproduced the +pre-fix shape directly (`prim_subreg`-style `.reg2hw,` connection, no +local driver, signal read elsewhere) — silent, confirming the fix holds. + +*`multiply-driven`* — two `always_comb`: flagged. `always_ff` + `assign`: +flagged. Two `initial` blocks: silent (`Initial` is `unclassifiable`). +Different struct fields written from two blocks: silent (member writes +are `whole: false`, disqualifying). Latch-inference shape +(`always_comb` with no `else`): silent, correctly out of this rule's +business. Implicit (keyword-less) generate-if: silent, confirmed the +`in_generate` flag is set for `GenIf` reached without an explicit +`generate`/`endgenerate` wrapper, not just the explicit-keyword shape the +unit tests use. + +**Should-fix — `force`/`release`/`deassign` collapse into the enclosing +block's ordinary `DriverKind`, and `release`/`deassign` are untested.** +`crates/vlog_linter/src/signals.rs:383-420`, the `body()` walk: + +```rust +StmtKind::Assign { lhs, .. } | StmtKind::ForceRelease { lhs, .. } => { + self.write(lhs, kind, block, in_generate) +} +``` + +`kind` here is whatever `DriverKind` the caller passed for the *whole +enclosing block* (`Always` for any `always*`, `Initial` for +`initial`/`final`, `Routine` for a function/task body) — `force`, `release` +and `deassign` are not told apart from an ordinary procedural assignment, +and not told apart from each other. Two consequences, reproduced live: + +1. **False positive for `multiply-driven`.** A signal driven by one + continuous `assign` and overridden by `force`/`release` inside an + `always` block (a verification-harness pattern — bypass/override logic + guarded by a control signal) is reported as "driven both by a + continuous assignment and by a procedural block," even though + `force`/`release` are simulation-only directives with no synthesis + meaning and are not what the rule's own doc says it counts ("only + continuous `assign`s and `always*` blocks" — true assignments, not + overrides). Repro: + ```systemverilog + module m (input logic clk, input logic bypass, output logic q); + logic a; + assign a = clk; + always @(posedge clk) begin + if (bypass) force a = 1'b1; + else release a; + end + assign q = a; + endmodule + ``` + `vfmt check --select multiply-driven` on this file: 1 violation, + `` `a` is driven both by a continuous assignment and by a procedural + block``. This is exactly the kind of finding CLAUDE.md and this + feature's own "not crying wolf" bar exist to prevent — a real, + non-synthetic RTL/verification shape producing a wrong accusation. Low + corpus incidence today (`grep` for bare `force `/`release ` statements + finds only 2 of 860 files, and both write through a hierarchical path + that this rule doesn't track anyway, which is why the corpus scored + 0/860 despite the bug), but the README specifically argues + `multiply-driven` is "the closest to a default-on rule" on the strength + of that 0/860 score — this finding means the 0/860 score under-reports + the rule's real false-positive surface, and should be weighed before + that argument is acted on. +2. **Undocumented behavior, false negative, for `undriven-net`.** The + README's driver list names `force` explicitly ("A drive is any of: ... + `force`, ...") but never mentions `release`/`deassign`. The code + nonetheless treats a signal driven *only* by `release`/`deassign` (no + actual assignment anywhere) as driven, so `undriven-net` stays silent + on it. Repro: + ```systemverilog + module m (output logic q); + logic a; + initial begin + release a; + end + assign q = a; + endmodule + ``` + `vfmt check --select undriven-net`: 0 violations, even though `a` is + never actually assigned a value anywhere in the file. This is the + silent/harmless direction (no false accusation), so it is not a + blocking bug, but it is a real behavior gap the doc doesn't own, and it + has **zero test coverage**: `grep -n + "force\|release\|deassign\|ForceRelease"` across `signals.rs` and all + three rule files finds exactly one hit + (`undriven_net.rs`'s `every_shape_of_drive_silences_it`, which covers + `force` only). No test exercises `release`, `deassign`, or the + `force`/`release`-inside-`always` shape at all — the multiply-driven + false positive above was not caught by the 61 unit tests or the 46 + `.lint` cases because none of them tries it. + +Recommend, for the dev's next pass (not attempted here — this is a design +decision, adding a `DriverKind::Override` or similar and excluding it from +`multiply-driven`'s and `undriven-net`'s reasoning the same deliberate way +`Initial`/`Routine`/`Trigger` already are, not a typo fix): give +`force`/`release`/`deassign` their own `DriverKind` distinct from the +block they sit in, with masked-corruption-style attack tests for both +directions (force/release must not manufacture a `multiply-driven` finding +out of an override pattern; force must still count as a drive for +`undriven-net`). This doesn't block shipping the three rules off-by-default +as this round proposes — the off-by-default posture already absorbs it — +but it should be fixed before `multiply-driven`'s default is ever +reconsidered, per the README's own reasoning about that rule. + +**Separately verified, not a parser bug introduced by this round:** +procedural continuous assignment (`assign a = b;` written as a *statement* +inside a procedural block, as opposed to the item-level continuous +`assign`) is not a recognized statement form in `vlog_parser` — it falls +through `parse_keyword_stmt`'s final `_ =>` arm into `StmtKind::Error`. +Confirmed live: a file using this form produces zero findings for any of +the three rules on the affected signal, because `signals.rs` already +treats an `Error` leaf as opaque (`item()`/`body()`'s `StmtKind::Error(_) +=> self.opaque_spans.push(...)`), which is the safe default this round's +"when uncertain, say nothing" policy calls for. No action needed; noted +because the QA brief asked about "procedural continuous assign/deassign" +by name and the honest answer is "silently and safely out of scope," not +"handled." + +**Waivers.** Spot-ran `// vfmt: waive ` on the declaration/violation +line for all three rules live (not just the `.lint` harness, which was +also re-run: `cargo test -p vlog_linter --test lint_cases` — 14/14 green, +including the three new case files' own suites). Every waiver suppressed +its rule's finding as expected. + +**Server parity.** `crates/vfmt_server/src/lint.rs`'s `context()` now +calls `.with_semantics(&doc.semantics)`, and the round's own test +(`a_semantic_rule_reads_the_documents_own_analysis`) proves both that a +semantic rule fires correctly through the server's `LintContext` and that +`context(doc).semantics()` is pointer-identical to `&doc.semantics` (the +lent table, not a second analysis) — read and re-run, passes. **Caveat +worth recording**: `vfmt_server::lint::violations`/`diagnostics` call +`lint(&context(doc), &default_rules())` only (`crates/vfmt_server/src/ +lint.rs:35-36`) — there is no server-side rule-selection surface yet, so +none of the three semantic rules can actually be *reached* through the +live LSP path today; the parity claim is true at the plumbing level (verified +above) but not yet observable end-to-end through a real `initialize`/ +`didOpen`/`publishDiagnostics` exchange, because there is nothing to +select them with. Not a defect — the README doesn't claim otherwise — but +worth flagging so "server parity" isn't read as "reachable from the +editor today." + +**Test-count reconciliation — exact, not approximate.** `grep -c +"#\[test\]"`: `signals.rs` 21, `rules/{unused_signal,undriven_net, +multiply_driven}.rs` 12+13+12=37, `context.rs` 9 total (2 new — the other +7 predate this round), `vfmt_server/src/lint.rs` 11 total (1 new). New +total: 21+37+2+1 = **61**, matching the claim exactly. `.lint` case +files: 15/15/13 `====` separators → 16/16/14 cases (one more case than +separators, per the format) = **46**, matching exactly. This precision +across every count claimed in the work log is itself evidence the rest of +the narrative is trustworthy. + +**Minor, cosmetic finding.** The Work log's "Scope" bullet +(`docs/features/semantic-lints/README.md`, the "2026-08-25 — dev" entry) +lists the touched files as `crates/vlog_linter/{...}`, +`crates/vfmt_server/src/lint.rs`, "this README, and +`docs/features/linter-core/README.md`'s rule table" — it does not mention +the top-level `README.md`, which `git diff HEAD -- README.md` shows *was* +changed (a "Linting" section update adding the three new rules and the +off-by-default footnote). The change itself is accurate and welcome; the +Scope bullet is just incomplete. Left unfixed — it's the dev's Work log +entry, not mine to edit. + +**On the off-by-default ruling (task item 5).** Agree with shipping all +three off by default. The corpus evidence is real (I re-derived it +independently) and the cross-file blind spot is the correct reason — I +reproduced it directly rather than taking the argument on faith. I +partially disagree with how strongly the README stakes `multiply-driven`'s +"closest to default-on" case on the 0/860 corpus score: that score is +real but, per the finding above, doesn't cover the `force`/`release` +shape at all (only 2 corpus files use either keyword, and both write +through a hierarchical path this rule already ignores for other reasons). +The rule's true false-positive surface is not fully measured by this +corpus. This doesn't change my agreement with the off-by-default +*decision* — it changes how much weight I'd put on "0/860" as an argument +for flipping the default later, until the `force`/`release` classification +is fixed. + +**Fixes applied by me:** none — every finding above needs a design +decision (a new `DriverKind` variant and its threading through two rules) +or is a documentation/logging nit outside QA-log-only scope, not a typo or +missing assertion. + +### 2026-08-25 — QA, round 2 (force/release rework) + +Verdict: **ship**. The should-fix from round 1 is closed at the mechanism +level, correctly and more thoroughly than the minimum fix would have been. +Every claim in the dev's round-2 message reproduced exactly; the two +sabotage checks behaved exactly as predicted, including the mechanistic +detail (blocks-filtering vs. the wider unclassifiable() exclusion) that the +dev's own explanation rests on. No new findings. + +**Mechanism, verified by reading `signals.rs` and `parser.rs` before +running anything.** `parser.rs:3609-3622` — confirmed `"force"` and +`"release" | "deassign"` are the only two arms producing +`StmtKind::ForceRelease`; nothing else in `parse_keyword_stmt` does. +`DriverKind` gained `Force` and `Release` (`signals.rs:47-53`); the +`body()` walk's `StmtKind::ForceRelease { kw, lhs, .. }` arm now sets +`kind` from `kw` directly (`"force"` → `Force`, else → `Release`) instead +of inheriting the caller's block-level `kind` — and it does this +**unconditionally**, so `force`/`release` keep their own kind regardless +of which block they sit in (`always`, `initial`, or a task/function body). +`DriverKind::is_override()` (`Force | Release`) and +`Driver::establishes_a_value()` (`self.kind != DriverKind::Release`) are +the two new predicates; `multiply-driven`'s `unclassifiable()` gained +`|| driver.kind.is_override()`, and `undriven-net`'s `check()` now gates +on `usage.drivers.iter().any(Driver::establishes_a_value)` instead of +`!usage.drivers.is_empty()`. + +**Confirmed the dev's mechanistic claim independently, not just read it.** +The claim: separating `Force`/`Release` from `Always` already closes my +round-1 `multiply-driven` false positive through `blocks()`'s exact-kind +filter alone, before `unclassifiable()` is even touched — because +`blocks(&usage.drivers, DriverKind::Always)` only counts drivers whose +`kind == Always`, and a `force`/`release` inside an `always` block no +longer has that kind. I verified this by tracing it rather than trusting +the sentence: my round-1 repro (`assign a = clk;` plus `force`/`release` +inside an `always` block) has one `Continuous` driver and zero `Always` +drivers under the new scheme, so `always.len() + continuous.len()` is +`0 + 1 = 1 < 2` regardless of `unclassifiable()`. That means +`driver.kind.is_override()` in `unclassifiable()` is doing separate, +*additional* work: taking a signal out of the rule entirely whenever an +override touches it anywhere, even when two genuine drivers already exist +independent of the override. I confirmed this is exactly what +`an_override_anywhere_takes_the_signal_out_of_the_rule` tests (two real +`always_comb` drivers plus an unrelated `initial force`) and exactly what +the sabotage below isolates. + +**Sabotage-checked both named predicates myself, in the actual tree, not +by reasoning alone:** + +1. Deleted `|| driver.kind.is_override()` from `unclassifiable()` + (`multiply_driven.rs`). `cargo test -p vlog_linter` (full crate, 190 + tests): **exactly one** test went red — + `an_override_anywhere_takes_the_signal_out_of_the_rule` — with the + failure showing the two-`always_comb` conflict now reporting again + (`` `a` is driven from 2 always blocks``), which is precisely the + mechanism above: without the wider exclusion, `blocks()`'s kind + filtering alone isn't enough to silence a genuine conflict that merely + *also* has a force nearby. `an_override_block_is_not_a_second_driver` + (my original round-1 repro, now a named test) stayed green under this + sabotage, confirming the dev's claim that `blocks()` filtering alone + already covers that specific case. Reverted; `md5` of the file matched + before and after. +2. Changed `establishes_a_value()` to `true` unconditionally + (`signals.rs`). Two tests went red: + `rules::undriven_net::tests::a_force_is_a_drive_but_a_release_is_not` + (the one the coordinator named) and + `signals::tests::only_a_release_establishes_no_value` (the classifier's + own unit test, which exercises the same predicate directly and would be + a strange thing to leave silently passing). Both failures are the + expected shape: a `release`-only signal stopped being flagged undriven. + Reverted; `md5` matched before and after both files. + +**Round-2 attacks (coordinator's list), all live against the release +binary:** + +| attack | result | verdict | +|---|---|---| +| `force` targeting a part-select (`force a[0] = ...`) alongside `assign a = ...` | `multiply-driven` silent | correct — a part-select write already disqualifies via `!driver.whole`, independent of the override fix; no resurrection | +| `force` targeting the whole signal (control, same shape without part-select) | `multiply-driven` silent | correct, matches round-1 fix | +| `force` inside a **task body** (`task drive_it; force a = 1'b1; endtask`) | `undriven-net` silent | sane — `Force` is set unconditionally from the statement keyword and wins over `Routine`; a force is a force regardless of what calls it | +| `deassign` alone, no other driver | `undriven-net` **flagged** (`` `a` is read but never driven``) | correct — `deassign` maps to `Release`, which does not establish a value, exactly as the coordinator expected | +| `force` then `release` of the **same** signal in one `initial` block | both rules silent | correct — `undriven-net` sees the `Force` driver (`establishes_a_value() == true`) and stops there; `multiply-driven` excludes the whole signal via `is_override()` on either driver | +| hierarchical `force` (`force u.y = 1'b1;`, `u` an instance) | all three rules silent | unchanged from round 1 — `lvalue_targets` still resolves a `Member` write down to its base identifier, which is the instance symbol, not a tracked `Decl`; the override-kind change doesn't touch this path at all | + +No new false positives or false negatives found in this pass. + +**Gates, re-run clean.** `cargo fmt --all --check` clean. `cargo clippy +--all-targets --workspace` silent (forced rebuild). `cargo test +--workspace`: **1543 passed**, 0 failed — exactly the claimed 1535 + 8. +`node editors/vscode/smoke.js` OK. No `#[allow]` added anywhere in +`signals.rs`/`multiply_driven.rs`/`undriven_net.rs`; no `.unwrap()`/ +`.expect()`/`panic!` outside `#[cfg(test)]` in those files. + +**Test-count and case-count reconciliation, exact again.** `#[test]` +counts: `signals.rs` 23 (+2), `unused_signal.rs`/`undriven_net.rs`/ +`multiply_driven.rs` 12+15+16=43 (+6), `context.rs` 9 (unchanged), +`vfmt_server/src/lint.rs` 11 (unchanged) → **8 new unit tests**, matching +the claim exactly. `.lint` `====` separators: `unused_signal` 15 +(unchanged, 16 cases), `undriven_net` 19 (+4, 20 cases), `multiply_driven` +15 (+2, 16 cases) → **6 new cases**, totalling **52** (16+20+16), matching +both the round-2 claim and the arithmetic in `Status/TODO`. + +**Byte-identical claim, re-verified with a fresh worktree build.** Built +HEAD (`a96c908`) in a new `git worktree`, release profile. `vfmt check +corpus --output-format json`: stdout and stderr byte-identical to the +working tree's release build (same exit 2, same single lex-error line, +same summary line). Also diffed the new `--select ` corpus outputs +against my own round-1 saved copies: **byte-identical** for all three +rules, confirming the 52/10, 3/2, 0/0 counts didn't just come out the same +by coincidence — the actual finding sets didn't move at all, as expected +since the fix only reclassifies `force`/`release` drivers, which the +corpus barely contains and which write through paths these rules already +ignore. + +**Docs.** The `undriven-net` section now names `force` as a drive and +states `release`/`deassign` are not, matching the code. The +`multiply-driven` section's bullet list gained the override exclusion with +the "deliberately wider than not-counting" framing that matches +`an_override_anywhere_takes_the_signal_out_of_the_rule`'s actual behavior, +not a narrower claim the code wouldn't back up. The on/off ruling now +carries the "how much weight 0/860 carries, honestly" paragraph I asked +for in round 1 — read it, and it states the finding accurately (2 corpus +files, both hierarchical, score doesn't cover the surface) without +overclaiming that the bug fix now makes 0/860 fully trustworthy — it +doesn't, since the corpus still can't exercise the shape either way; the +paragraph is honest about that limit rather than declaring victory. + +**Verdict: ship.** The should-fix is closed correctly, at the mechanism +level, with tests that fail for the right reason when sabotaged (verified, +not assumed) and documentation that matches the code rather than +overclaiming it. No blocking or should-fix findings remain from either +round. + +## Review + +**2026-08-25 — lead.** Reviewed after QA round 2's ship verdict; gates +run independently (1543 tests, 0 failures). This milestone crossed the +"no semantic claims" line the right way: measurement first (55 corpus +hits, every one read against source, two false-positive families found +and closed by measuring), defaults decided from the data (all three off, +with the honest reason — the cross-file-read blind spot — not modesty), +and the classification's unknown-direction taxonomy doing the +load-bearing honesty. The dev declining my pre-authorized vlog_semantic +extension was the correct call for the right reason: driver semantics is +a lint concept, and the binder discards the context it would need by +design. QA's force/release find was real — the fix's two independent +layers (own DriverKind; override-excludes-entirely) each carry their own +only-test-that-goes-red, verified by sabotage twice over. Default `vfmt +check` output stays byte-identical to HEAD, worktree-diffed by three +different people now. Accepted; M12 checked off in the umbrella plan and +TODO §8. The path to default-on runs through the workspace-index +handshake filed in this README — a future round's decision, made on a +future round's measurements. + + +*(reserved for the lead)*