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

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

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

201 lines
7.0 KiB
Rust

//! What a rule reports, and what it offers to change.
use vlog_parser::span::TextRange;
use crate::severity::Severity;
/// One rule finding: which rule, what is wrong, where, and — sometimes —
/// how to repair it.
#[derive(Debug, Clone)]
pub struct Violation {
/// The reporting rule's stable kebab-case name.
pub rule: &'static str,
/// How bad it is. **Set by the runner from the reporting rule**, not by
/// the rule's own `check` — [`crate::lint`] stamps every finding with
/// [`crate::Rule::severity`] before it is returned, so a rule cannot
/// contradict its own declared class. A violation built by hand (a rule's
/// unit test calling `check` directly) carries the placeholder below until
/// it goes through the runner.
pub severity: Severity,
/// One sentence, lower case, no trailing period — the diagnostic line.
pub message: String,
/// Byte range the diagnostic points at.
pub span: TextRange,
/// An automatic repair, when the rule can offer one.
pub fix: Option<Fix>,
}
impl Violation {
/// A finding with no automatic repair.
pub fn new(rule: &'static str, message: impl Into<String>, span: TextRange) -> Violation {
Violation { rule, severity: Severity::Warning, message: message.into(), span, fix: None }
}
/// The same finding, carrying a repair.
pub fn with_fix(mut self, fix: Fix) -> Violation {
self.fix = Some(fix);
self
}
}
/// A repair for one violation: replace each range with the given text.
///
/// The edits are applied as a set — either all of them or none — so a rule
/// may split one logical repair across several places in the file.
#[derive(Debug, Clone)]
pub struct Fix {
/// `(range, replacement)` pairs; a replacement of `""` is a deletion.
pub edits: Vec<(TextRange, String)>,
/// Whether applying this without review can change behavior.
pub applicability: Applicability,
}
impl Fix {
/// A repair that cannot change what the code means.
pub fn safe(edits: Vec<(TextRange, String)>) -> Fix {
Fix { edits, applicability: Applicability::Safe }
}
/// A repair that may change what the code means; `--unsafe-fixes` only.
pub fn unsafe_fix(edits: Vec<(TextRange, String)>) -> Fix {
Fix { edits, applicability: Applicability::Unsafe }
}
}
/// ruff's fix-safety classification, adopted verbatim: `--fix` applies
/// [`Safe`](Applicability::Safe) fixes, `--unsafe-fixes` widens that to all.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Applicability {
/// Preserves meaning and intent — whitespace, spelling of a keyword.
Safe,
/// Preserves meaning as far as the rule can tell, but the author may
/// have meant what they wrote (`=` → `<=` in a clocked block).
Unsafe,
}
impl Applicability {
/// The word used for this level in `--output-format json`.
pub fn as_str(&self) -> &'static str {
match self {
Applicability::Safe => "safe",
Applicability::Unsafe => "unsafe",
}
}
}
/// The result of rewriting a source text with the fixes it had.
#[derive(Debug, Clone)]
pub struct Fixed {
/// The rewritten text.
pub output: String,
/// How many violations' fixes were applied.
pub applied: usize,
}
/// Applies the fixes of `violations` to `source`.
///
/// Fixes are applied left to right; one that overlaps an already-applied fix
/// is skipped, so a single pass never produces garbled text. Running the
/// linter again picks the skipped ones up — this is why the CLI's `--fix`
/// loops until nothing changes.
pub fn apply_fixes(source: &str, violations: &[Violation], include_unsafe: bool) -> Fixed {
let mut fixes: Vec<Vec<(TextRange, String)>> = Vec::new();
for violation in violations {
let Some(fix) = &violation.fix else { continue };
if fix.applicability == Applicability::Unsafe && !include_unsafe {
continue;
}
let mut edits = fix.edits.clone();
edits.sort_by_key(|(range, _)| (range.start, range.end));
if edits.is_empty() || overlaps_itself(&edits) {
continue;
}
fixes.push(edits);
}
fixes.sort_by_key(|edits| edits.first().map_or(0, |(range, _)| range.start));
let mut output = String::with_capacity(source.len());
let mut cursor = 0usize;
let mut applied = 0usize;
for edits in fixes {
let start = edits[0].0.start as usize;
if start < cursor {
continue; // Overlaps a fix already applied; next round gets it.
}
for (range, replacement) in &edits {
let (start, end) = (range.start as usize, range.end as usize);
if start < cursor || end > source.len() || !source.is_char_boundary(start) {
continue;
}
output.push_str(&source[cursor..start]);
output.push_str(replacement);
cursor = end;
}
applied += 1;
}
output.push_str(&source[cursor.min(source.len())..]);
Fixed { output, applied }
}
/// True when two edits of one fix cover the same byte — a rule bug, and a
/// reason to drop that fix rather than produce nonsense.
fn overlaps_itself(edits: &[(TextRange, String)]) -> bool {
edits.windows(2).any(|pair| pair[0].0.end > pair[1].0.start)
}
#[cfg(test)]
mod tests {
use super::*;
fn violation(fix: Fix) -> Violation {
Violation::new("t", "m", TextRange::new(0, 0)).with_fix(fix)
}
fn edit(start: u32, end: u32, text: &str) -> (TextRange, String) {
(TextRange::new(start, end), text.to_string())
}
#[test]
fn applies_edits_in_order() {
let v = vec![
violation(Fix::safe(vec![edit(6, 11, "there")])),
violation(Fix::safe(vec![edit(0, 5, "howdy")])),
];
let fixed = apply_fixes("hello world", &v, false);
assert_eq!(fixed.output, "howdy there");
assert_eq!(fixed.applied, 2);
}
#[test]
fn unsafe_fixes_need_asking_for() {
let v = vec![violation(Fix::unsafe_fix(vec![edit(0, 5, "howdy")]))];
assert_eq!(apply_fixes("hello", &v, false).applied, 0);
assert_eq!(apply_fixes("hello", &v, true).output, "howdy");
}
#[test]
fn an_overlapping_fix_is_skipped_not_garbled() {
let v = vec![
violation(Fix::safe(vec![edit(0, 5, "howdy")])),
violation(Fix::safe(vec![edit(3, 8, "XX")])),
];
let fixed = apply_fixes("hello world", &v, false);
assert_eq!(fixed.output, "howdy world");
assert_eq!(fixed.applied, 1);
}
#[test]
fn a_multi_edit_fix_is_all_or_nothing() {
let v = vec![violation(Fix::safe(vec![edit(0, 1, "H"), edit(6, 7, "W")]))];
let fixed = apply_fixes("hello world", &v, false);
assert_eq!(fixed.output, "Hello World");
assert_eq!(fixed.applied, 1);
}
#[test]
fn a_self_overlapping_fix_is_dropped() {
let v = vec![violation(Fix::safe(vec![edit(0, 4, "a"), edit(2, 6, "b")]))];
assert_eq!(apply_fixes("hello world", &v, false).applied, 0);
}
}