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

233 lines
8.6 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 naming;
mod registry;
mod rule_docs;
mod rules;
mod signals;
mod violation;
mod visit;
mod waiver;
use std::path::PathBuf;
pub use context::{LintContext, ParsedSource};
pub use registry::{all_rules, default_rules, rule_by_name, select_rules, Rule};
pub use rule_docs::rules_markdown;
pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation};
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))
});
kept
}
#[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 macro-name-style\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 macro-name-style\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()]).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()]).unwrap();
assert!(run(src, None, &enabled).is_empty());
}
#[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());
}
}