Files
lucisv/crates/vlog_linter/src/lib.rs
T
lucioandClaude Fable 5 8adb6c8ac1 Linter expansion, wave 3: the remaining nineteen Verible rules, forbidden-macro, void-cast's forbidden calls, and the e2e options case
TODO section 35 (54 -> 73 rules: every rule in Verible's published
list but forbid-implicit-declarations).
module-begin-block, legacy-generate-region, legacy-genvar-declaration,
v2001-generate-begin, explicit-function-lifetime,
explicit-task-lifetime (both exempt out-of-body definitions after a
census showed 948 of 960 findings were exactly that shape),
positive-meaning-parameter-name, suggest-parentheses (safe fix,
truth-tabled), unpacked-dimensions-range-ordering, uvm-macro-semicolon,
create-object-name-match, numeric-format-string-style,
macro-string-concatenation, disable-statement, forbidden-macro,
endif-comment (safe fix), forbid-line-continuations, dff-name-style,
proper-parameter-declaration. Verible's forbidden-symbol is the
source-file name of invalid-system-task-function (read in its
rule .cc), so it is that rule's symbols option, nothing fires twice;
void-cast gains forbidden_calls. Shared readers: walk_items_scoped,
exprs.rs, preproc.rs. A checked-in e2e case drives lucisv.lint.options
over the wire. Two rules fire on an error leaf because the parser
refuses a module-scope begin/end and a bare generate begin - filed as
docs/topo.md 2.9-25.
3 695 tests / 48 binaries; corpus 814/820 byte-identical to 0.38.0;
opentitan default-set census 1 053 -> 1 169, the arithmetic balancing
to the six default-on additions; timing unchanged.

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

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 04:55:10 -05:00

291 lines
11 KiB
Rust

//! Syntactic lint rules for Verilog/SystemVerilog — the engine behind
//! `lucisv check`.
//!
//! This crate plays the role of `ruff_linter` in ruff's architecture: a
//! registry of named rules, each handed a prepared file ([`LintContext`]) and
//! returning [`Violation`]s that may carry a [`Fix`] classified as
//! [`Applicability::Safe`] or [`Applicability::Unsafe`]. Rule ergonomics —
//! stable kebab-case names, a style-guide rationale per rule, inline waivers —
//! follow Verible.
//!
//! ```
//! use vlog_linter::{run, default_rules};
//!
//! let violations = run("module m;\n\twire a;\nendmodule\n", None, &default_rules());
//! assert_eq!(violations[0].rule, "no-tabs");
//! ```
//!
//! The parse is error-tolerant, so a file that does not fully parse is still
//! linted — the parts that failed are `Error` leaves no AST rule matches, and
//! the text- and token-level rules do not care. See
//! `docs/features/linter-core/README.md`.
mod context;
mod decls;
mod exprs;
mod interfaces;
mod literal;
mod module_decls;
mod naming;
mod options;
mod preproc;
mod regex;
mod registry;
mod rule_docs;
mod rules;
mod severity;
mod signals;
mod violation;
mod visit;
mod vscode;
mod waiver;
use std::path::PathBuf;
pub use context::{LintContext, MentionOracle, ModuleInterface, ParsedSource};
pub use interfaces::module_interfaces;
pub use options::{OptionDefault, OptionKind, OptionSpec, OptionValue, RuleOptions};
pub use registry::{
all_rules, default_rules, rule_by_name, rules_named, select_rules, workspace_rules, Rule,
};
pub use rule_docs::rules_markdown;
pub use severity::Severity;
pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation};
/// The identifier census a [`MentionOracle`] is answered from, re-exported
/// from `vlog_semantic` so a front end that implements the oracle needs this
/// crate alone. One harvest for the whole workspace — see
/// `docs/features/semantic-lints-on/README.md`.
pub use vlog_semantic::words;
pub use vscode::{rule_setting, severity_setting, vscode_lint_settings, RULE_CHOICES};
pub use waiver::UNUSED_WAIVER;
use waiver::Waivers;
/// Lints one source text with `enabled`, in one step.
///
/// `path` is the file the text came from; `None` (a stdin buffer) only makes
/// the rules that need a file name go quiet.
pub fn run(source: &str, path: Option<PathBuf>, enabled: &[&'static dyn Rule]) -> Vec<Violation> {
lint(&LintContext::new(source, path), enabled)
}
/// Lints a prepared file with `enabled`, applying waivers.
///
/// The result is sorted by position, then by rule name, so two runs over the
/// same file print in the same order whatever order the registry has.
pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation> {
let names: Vec<&'static str> = enabled.iter().map(|rule| rule.name()).collect();
let mut waivers = Waivers::collect(ctx);
let mut found = Vec::new();
for rule in enabled {
found.extend(rule.check(ctx));
}
let mut kept = waivers.filter(ctx, found);
if names.contains(&UNUSED_WAIVER) {
// `unused-waiver` findings are themselves waivable, which is circular:
// waiving one marks another waiver used, and that one must then stop
// being reported. Usage only ever grows, so re-deriving the findings
// until no further waiver is used terminates — in practice after one
// extra round.
loop {
let before = waivers.used_count();
let unused = waivers.unused(&names);
let surviving = waivers.filter(ctx, unused);
if waivers.used_count() == before {
kept.extend(surviving);
break;
}
}
}
kept.sort_by(|a, b| {
(a.span.start, a.span.end, a.rule).cmp(&(b.span.start, b.span.end, b.rule))
});
stamp_severities(&mut kept);
kept
}
/// Gives every finding the class its rule declares.
///
/// One place rather than one per rule: a rule's `check` builds violations
/// without knowing what it is called, the `unused-waiver` findings are built by
/// the waiver scanner and not by a rule at all, and a severity written twice
/// would eventually be written differently. See [`Violation::severity`].
fn stamp_severities(violations: &mut [Violation]) {
for violation in violations {
if let Some(rule) = rule_by_name(violation.rule) {
violation.severity = rule.severity();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn names(violations: &[Violation]) -> Vec<&str> {
violations.iter().map(|v| v.rule).collect()
}
fn lint_all(src: &str) -> Vec<Violation> {
run(src, None, &default_rules())
}
#[test]
fn findings_come_back_in_source_order() {
let src = "module m;\n wire a; \n\twire b;\nendmodule\n";
assert_eq!(names(&lint_all(src)), vec!["no-trailing-whitespace", "no-tabs"]);
}
#[test]
fn a_same_line_waiver_suppresses_that_line_only() {
let src = "module m;\n\twire a; // lucisv: waive no-tabs\n\twire b;\nendmodule\n";
let found = lint_all(src);
assert_eq!(names(&found), vec!["no-tabs"]);
assert_eq!(found[0].span.start as usize, src.find("\twire b").unwrap());
}
#[test]
fn a_waiver_on_its_own_line_covers_the_next_one() {
let src = "module m;\n // lucisv: waive no-tabs\n\twire a;\n\twire b;\nendmodule\n";
let found = lint_all(src);
assert_eq!(names(&found), vec!["no-tabs"], "only the second tab line survives");
assert_eq!(found[0].span.start as usize, src.find("\twire b").unwrap());
}
#[test]
fn the_verible_spelling_is_accepted() {
let src = "module m;\n\twire a; // verilog_lint: waive no-tabs\nendmodule\n";
assert!(lint_all(src).is_empty());
}
#[test]
fn a_start_stop_range_covers_its_markers_and_everything_between() {
let src = "module m;\n\
// lucisv: waive-start no-tabs\n\
\twire a;\n\
\twire b;\n\
// lucisv: waive-stop no-tabs\n\
\twire c;\n\
endmodule\n";
let found = lint_all(src);
assert_eq!(names(&found), vec!["no-tabs"]);
assert_eq!(found[0].span.start as usize, src.find("\twire c").unwrap());
}
#[test]
fn an_unclosed_range_runs_to_the_end_of_the_file() {
let src = "module m;\n// lucisv: waive-start no-tabs\n\twire a;\n\twire b;\nendmodule\n";
assert!(lint_all(src).is_empty());
}
#[test]
fn a_waiver_that_suppresses_nothing_is_reported() {
let src = "module m;\n wire a; // lucisv: waive no-tabs\nendmodule\n";
let found = lint_all(src);
assert_eq!(names(&found), vec![UNUSED_WAIVER]);
assert!(found[0].message.contains("no-tabs"), "{}", found[0].message);
}
#[test]
fn an_unknown_or_malformed_waiver_is_reported() {
let src = "module m;\n // lucisv: waive no-such-rule\n // lucisv: waive\nendmodule\n";
let found = lint_all(src);
assert_eq!(names(&found), vec![UNUSED_WAIVER, UNUSED_WAIVER]);
assert!(found[0].message.contains("unknown rule"), "{}", found[0].message);
assert!(found[1].message.contains("malformed"), "{}", found[1].message);
}
#[test]
fn a_verible_waiver_for_a_rule_lucisv_does_not_have_is_ignored() {
// Real corpus RTL is annotated for Verible. Waivers naming rules lucisv
// has not implemented are that codebase's, not typos, so they are
// neither honored nor reported.
let src = "module m;\n // verilog_lint: waive forbid-implicit-declarations\n wire a;\nendmodule\n";
assert!(lint_all(src).is_empty());
// lucisv's own spelling gets no such benefit of the doubt.
let src =
"module m;\n // lucisv: waive forbid-implicit-declarations\n wire a;\nendmodule\n";
assert_eq!(names(&lint_all(src)), vec![UNUSED_WAIVER]);
}
#[test]
fn a_waive_stop_without_a_start_is_reported() {
let src = "module m;\n // lucisv: waive-stop no-tabs\nendmodule\n";
let found = lint_all(src);
assert_eq!(names(&found), vec![UNUSED_WAIVER]);
assert!(found[0].message.contains("no matching"), "{}", found[0].message);
}
#[test]
fn a_waiver_for_a_rule_this_run_did_not_enable_is_silent() {
let src = "module m;\n wire a; // lucisv: waive no-tabs\nendmodule\n";
let enabled = select_rules(&[], &["no-tabs".to_string()], false).unwrap();
assert!(run(src, None, &enabled).is_empty());
}
#[test]
fn unused_waiver_findings_can_themselves_be_waived() {
let src = "module m;\n\
// lucisv: waive unused-waiver\n\
wire a; // lucisv: waive no-tabs\n\
endmodule\n";
assert!(lint_all(src).is_empty());
}
#[test]
fn disabling_the_pseudo_rule_silences_unused_reporting() {
let src = "module m;\n wire a; // lucisv: waive no-tabs\nendmodule\n";
let enabled = select_rules(&[], &[UNUSED_WAIVER.to_string()], false).unwrap();
assert!(run(src, None, &enabled).is_empty());
}
/// Every finding the runner returns carries its rule's class — including
/// the `unused-waiver` ones, which no rule's `check` produced.
#[test]
fn the_runner_stamps_every_finding_with_its_rules_severity() {
let src = "module m;\n\
\treg a; // lucisv: waive no-such-rule\n\
\talways_comb a <= 1'b0;\n\
endmodule\n";
let found = run(src, Some(PathBuf::from("rtl/m.sv")), &default_rules());
assert!(found.len() >= 3, "{found:#?}");
for violation in &found {
let rule = rule_by_name(violation.rule).expect("a registered rule");
assert_eq!(violation.severity, rule.severity(), "{}", violation.rule);
}
let by_rule =
|name: &str| found.iter().find(|v| v.rule == name).map(|v| v.severity).expect(name);
assert_eq!(by_rule("wire-reg-mixup"), Severity::Error);
assert_eq!(by_rule("always-comb-blocking"), Severity::Warning);
assert_eq!(by_rule(UNUSED_WAIVER), Severity::Style);
}
#[test]
fn a_file_that_does_not_parse_still_gets_its_text_rules() {
let src = "module m;\n\t@@@ this is not verilog\nendmodule\n";
assert_eq!(names(&lint_all(src)), vec!["no-tabs"]);
}
#[test]
fn fixing_leaves_the_file_clean_for_the_fixed_rules() {
// A tab that is also trailing whitespace needs two rounds: the two
// fixes overlap, so the first pass applies one and the second the
// other. This is the loop `lucisv check --fix` runs.
let mut src = "module m;\n\twire a;\t\n wire b; \nendmodule\n".to_string();
for _ in 0..10 {
let found = run(&src, None, &default_rules());
let fixed = apply_fixes(&src, &found, false);
if fixed.applied == 0 {
break;
}
src = fixed.output;
}
assert_eq!(src, "module m;\n wire a;\n wire b;\nendmodule\n");
assert!(run(&src, None, &default_rules()).is_empty());
}
}