Files
lucisv/crates/vlog_linter/src/lib.rs
T

338 lines
13 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;
mod waiver_file;
use std::path::PathBuf;
pub use context::{LintContext, MentionOracle, ModuleInterface, ParsedSource};
pub use interfaces::{module_interfaces, package_exports, package_exports_in};
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;
/// The package table a [`MentionOracle`] answers `package_exports` with,
/// re-exported so an implementor names one crate rather than two.
pub use vlog_semantic::Exports;
pub use vscode::{rule_setting, severity_setting, vscode_lint_settings, RULE_CHOICES};
pub use waiver::UNUSED_WAIVER;
pub use waiver_file::{ExternalWaivers, UnusedReport, WaiverUse};
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> {
lint_with(ctx, enabled, &ExternalWaivers::default()).0
}
/// [`lint`] with the run's external waiver files applied too, reporting which
/// of their directives fired.
///
/// **Precedence is union**: a violation is dropped when an inline waiver *or*
/// an external one covers it, and one both cover marks both used, so neither
/// is then reported as dead. The usage half is the caller's to keep — only a
/// whole run knows whether a `--location` matched some file somewhere, which
/// is why `lucisv check` reports unused external waivers and the server does
/// not. See `docs/features/waiver-files/README.md`.
pub fn lint_with(
ctx: &LintContext,
enabled: &[&'static dyn Rule],
external: &ExternalWaivers,
) -> (Vec<Violation>, WaiverUse) {
let names: Vec<&'static str> = enabled.iter().map(|rule| rule.name()).collect();
let mut waivers = Waivers::collect(ctx);
let mut used = WaiverUse::default();
let mut found = Vec::new();
for rule in enabled {
found.extend(rule.check(ctx));
}
let mut kept = waive(ctx, &mut waivers, external, &mut used, 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 = waive(ctx, &mut waivers, external, &mut used, 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, used)
}
/// The violations neither an inline waiver nor an external one covers.
///
/// Both are always asked — never `||` short-circuited — because a violation
/// two waivers cover has to mark both of them used.
fn waive(
ctx: &LintContext,
inline: &mut Waivers,
external: &ExternalWaivers,
used: &mut WaiverUse,
violations: Vec<Violation>,
) -> Vec<Violation> {
let path = ctx.path();
violations
.into_iter()
.filter(|violation| {
let (line, _) = ctx.line_index().line_col(violation.span.start);
let inline_waived = inline.covers(violation.rule, line);
let external_waived =
!external.is_empty() && external.covers(path, violation.rule, line, used);
!(inline_waived || external_waived)
})
.collect()
}
/// 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());
}
}