diff --git a/Cargo.lock b/Cargo.lock index b63257c..d806104 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -256,6 +256,7 @@ dependencies = [ name = "vlog_linter" version = "0.2.0" dependencies = [ + "vlog_formatter", "vlog_parser", ] diff --git a/TODO.md b/TODO.md index 56f851a..a16a8a0 100644 --- a/TODO.md +++ b/TODO.md @@ -273,16 +273,29 @@ Adapt each: unit tests for `lexer.rs` trivia attachment (comment → leading/trailing decisions, blank-line counting), `parser.rs` per-construct parse tests, and `printer.rs` group-breaking behavior on synthetic docs. -- [ ] **[V] Lint test harness with inline violation markers.** Port the +- [x] **[V] Lint test harness with inline violation markers.** Port the `LintTestCase` / `RunLintTestCases` idea: test cases embed expected findings positionally in the source (Verible splices `ExpectedTokenInfo` fragments inline). A Rust adaptation: annotate with a marker comment or a `^^^` caret line, e.g. `assert_lint::("module m;\n\twire x;\n ^ no-tabs\nendmodule")`. Exact-match: unexpected findings fail the test too. -- [ ] **[V] `RunApplyFixCases` equivalent:** every autofix rule gets + → File-driven: `crates/vlog_linter/tests/cases/*.lint` (76 cases, all 13 + rules with violating/clean/waived/unused-waiver coverage) run by + `tests/lint_cases.rs` — `//^ ` markers carry the exact + `line:col` the CLI prints, matched exactly in both directions, with + stale-marker detection (a marker naming a dead rule fails the suite) and + 12 self-policing tests pinning the failure reports. Format spec and + migration stats in `docs/features/lint-harness/README.md`. +- [x] **[V] `RunApplyFixCases` equivalent:** every autofix rule gets `(input, fixed_output)` pairs, and the fixed output must itself be lint-clean and formatter-idempotent. + → A `----` section in a `.lint` case: the CLI's fix→re-lint loop must land + exactly on the expected text, leave nothing Safe-fixable, and the fixed + output must be accepted and converged by `vlog_formatter::format_source` + (inputs the formatter refuses must say `#tolerant`, enforced in both + directions like `#SKIP`; that population is empty today — all 5 fix cases + for the 2 fixable rules run the full cross-tool check). - [ ] **[V] Error-case tests.** Table of inputs that must *fail* to parse with the expected error position — locks in the failsafe path. - [x] **[R] Real-world corpus check (ruff's "ecosystem check").** ruff diff --git a/crates/vlog_linter/Cargo.toml b/crates/vlog_linter/Cargo.toml index bfb6d67..1e75f49 100644 --- a/crates/vlog_linter/Cargo.toml +++ b/crates/vlog_linter/Cargo.toml @@ -7,3 +7,9 @@ description = "Syntactic lint rules for Verilog/SystemVerilog, in the spirit of [dependencies] vlog_parser = { path = "../vlog_parser" } + +[dev-dependencies] +# Tests only: the .lint case harness asserts that a lint fix never produces +# something the formatter would refuse. The library still depends on +# vlog_parser + std alone (`cargo tree -p vlog_linter -e normal`). +vlog_formatter = { path = "../vlog_formatter" } diff --git a/crates/vlog_linter/tests/cases/always_rules.lint b/crates/vlog_linter/tests/cases/always_rules.lint new file mode 100644 index 0000000..9bc3c3d --- /dev/null +++ b/crates/vlog_linter/tests/cases/always_rules.lint @@ -0,0 +1,44 @@ +# a blocking assignment in an always_ff is flagged +module m; + always_ff @(posedge clk) q = d; +//^ 28 always-ff-non-blocking +endmodule +==== +# a non-blocking assignment in an always_ff is what the rule wants +module m; + always_ff @(posedge clk) q <= d; +endmodule +==== +# always-ff-non-blocking waived on the same line +module m; + always_ff @(posedge clk) q = d; // vfmt: waive always-ff-non-blocking +endmodule +==== +# an always-ff waiver that waives nothing is reported +module m; + always_ff @(posedge clk) q <= d; // vfmt: waive always-ff-non-blocking +//^ 36 unused-waiver +endmodule +==== +# a non-blocking assignment in an always_comb is flagged +module m; + always_comb x <= y; +//^ 15 always-comb-blocking +endmodule +==== +# a blocking assignment in an always_comb is what the rule wants +module m; + always_comb x = y; +endmodule +==== +# always-comb-blocking waived with the verible spelling +module m; +// verilog_lint: waive always-comb-blocking + always_comb x <= y; +endmodule +==== +# an always-comb waiver that waives nothing is reported +module m; + always_comb x = y; // vfmt: waive always-comb-blocking +//^ 22 unused-waiver +endmodule diff --git a/crates/vlog_linter/tests/cases/case_missing_default.lint b/crates/vlog_linter/tests/cases/case_missing_default.lint new file mode 100644 index 0000000..3b8d14a --- /dev/null +++ b/crates/vlog_linter/tests/cases/case_missing_default.lint @@ -0,0 +1,50 @@ +# a case without a default is flagged +module m; + always_comb begin + case (s) +//^ 5 case-missing-default + 0: x = 1; + endcase + end +endmodule +==== +# a default arm satisfies the rule +module m; + always_comb begin + case (s) + 0: x = 1; + default: x = 0; + endcase + end +endmodule +==== +# a unique case with a default is quiet too +module m; + always_comb begin + unique case (s) + 0: x = 1; + default: x = 0; + endcase + end +endmodule +==== +# waived from the line above +module m; + always_comb begin + // vfmt: waive case-missing-default + case (s) + 0: x = 1; + endcase + end +endmodule +==== +# a waiver that waives nothing is reported +module m; + always_comb begin + case (s) + 0: x = 1; + default: x = 0; + endcase // vfmt: waive case-missing-default +//^ 13 unused-waiver + end +endmodule diff --git a/crates/vlog_linter/tests/cases/class_bodies.lint b/crates/vlog_linter/tests/cases/class_bodies.lint new file mode 100644 index 0000000..6cc5a73 --- /dev/null +++ b/crates/vlog_linter/tests/cases/class_bodies.lint @@ -0,0 +1,34 @@ +# case-missing-default reaches a class method +class c; + function void f(int x); + case (x) +//^ 5 case-missing-default + 1: a = 1; + endcase + endfunction +endclass +==== +# explicit-parameter-storage-type reaches a class body and header +class c #(parameter A = 1); +//^ 21 explicit-parameter-storage-type + localparam B = 2; +//^ 14 explicit-parameter-storage-type +endclass +==== +# a class inside a module is reached too +#path rtl/m.sv +module m; + class c; + localparam B = 2; +//^ 16 explicit-parameter-storage-type + endclass +endmodule +==== +# the always rules reach a class body too +# (not legal SystemVerilog — pins that no rule's walk stops at endclass) +class c; + always_comb x <= y; +//^ 15 always-comb-blocking + always_ff @(posedge clk) q = d; +//^ 28 always-ff-non-blocking +endclass diff --git a/crates/vlog_linter/tests/cases/enum_name_style.lint b/crates/vlog_linter/tests/cases/enum_name_style.lint new file mode 100644 index 0000000..cc8a7f6 --- /dev/null +++ b/crates/vlog_linter/tests/cases/enum_name_style.lint @@ -0,0 +1,22 @@ +# a typedef enum without the _e or _t suffix is flagged at its name +package p; + typedef enum logic { A, B } state; +//^ 31 enum-name-style +endpackage +==== +# a suffixed lower_snake_case name is quiet +package p; + typedef enum logic { A, B } state_e; +endpackage +==== +# waived with the verible spelling +package p; +// verilog_lint: waive enum-name-style + typedef enum logic { A } state; +endpackage +==== +# a waiver that waives nothing is reported +package p; + typedef enum logic { A } state_e; // vfmt: waive enum-name-style +//^ 37 unused-waiver +endpackage diff --git a/crates/vlog_linter/tests/cases/explicit_parameter_storage_type.lint b/crates/vlog_linter/tests/cases/explicit_parameter_storage_type.lint new file mode 100644 index 0000000..c37c0a7 --- /dev/null +++ b/crates/vlog_linter/tests/cases/explicit_parameter_storage_type.lint @@ -0,0 +1,21 @@ +# an untyped parameter is flagged at its name +module m; + parameter WIDTH = 8; +//^ 13 explicit-parameter-storage-type +endmodule +==== +# a typed parameter is quiet +module m; + parameter int WIDTH = 8; +endmodule +==== +# waived on the same line +module m; + parameter WIDTH = 8; // vfmt: waive explicit-parameter-storage-type +endmodule +==== +# a waiver that waives nothing is reported +module m; + parameter int WIDTH = 8; // vfmt: waive explicit-parameter-storage-type +//^ 28 unused-waiver +endmodule diff --git a/crates/vlog_linter/tests/cases/mixed.lint b/crates/vlog_linter/tests/cases/mixed.lint new file mode 100644 index 0000000..3a1c587 --- /dev/null +++ b/crates/vlog_linter/tests/cases/mixed.lint @@ -0,0 +1,9 @@ +# several rules on one file report independently +#path rtl/top.sv +module foo #(parameter W = 1) (); +//^ 8 module-filename +//^ 24 explicit-parameter-storage-type + always_comb x <= 1; +//^ 1 no-tabs +//^ 14 always-comb-blocking +endmodule diff --git a/crates/vlog_linter/tests/cases/module_filename.lint b/crates/vlog_linter/tests/cases/module_filename.lint new file mode 100644 index 0000000..67b0245 --- /dev/null +++ b/crates/vlog_linter/tests/cases/module_filename.lint @@ -0,0 +1,25 @@ +# a module named unlike its file is flagged at its name +#path rtl/bar.sv +module foo; +//^ 8 module-filename +endmodule +==== +# a module matching its file is quiet +#path rtl/foo.sv +module foo; +endmodule +==== +# without a file name the rule has nothing to say +module foo; +endmodule +==== +# waived on the same line +#path rtl/bar.sv +module foo; // vfmt: waive module-filename +endmodule +==== +# a waiver that waives nothing is reported +#path rtl/foo.sv +module foo; // vfmt: waive module-filename +//^ 13 unused-waiver +endmodule diff --git a/crates/vlog_linter/tests/cases/module_name_style.lint b/crates/vlog_linter/tests/cases/module_name_style.lint new file mode 100644 index 0000000..c4d033e --- /dev/null +++ b/crates/vlog_linter/tests/cases/module_name_style.lint @@ -0,0 +1,25 @@ +# a CamelCase module name is flagged when the rule is selected +#select module-name-style,unused-waiver +module FooBar; +//^ 8 module-name-style +endmodule +==== +# the rule is off by default: the same source is quiet without #select +module FooBar; +endmodule +==== +# lower_snake_case is what the rule wants +#select module-name-style,unused-waiver +module foo_bar; +endmodule +==== +# waived on the same line +#select module-name-style,unused-waiver +module FooBar; // vfmt: waive module-name-style +endmodule +==== +# a waiver that waives nothing is reported +#select module-name-style,unused-waiver +module foo_bar; // vfmt: waive module-name-style +//^ 17 unused-waiver +endmodule diff --git a/crates/vlog_linter/tests/cases/no_tabs.lint b/crates/vlog_linter/tests/cases/no_tabs.lint new file mode 100644 index 0000000..9763382 --- /dev/null +++ b/crates/vlog_linter/tests/cases/no_tabs.lint @@ -0,0 +1,79 @@ +# a tab is reported at its column +module m; + wire a; +//^ 1 no-tabs +endmodule +==== +# one finding per line, at the first tab, however many tabs there are +module m; + wire a; +//^ 1 no-tabs +endmodule +==== +# a tab in the middle of a line is found too +module m; + wire a; +//^ 7 no-tabs +endmodule +==== +# spaces are quiet +module m; + wire a; +endmodule +==== +# a tab inside a string literal is data +module m; + initial $display("a b"); +endmodule +==== +# waived on the same line +module m; + wire a; // vfmt: waive no-tabs +endmodule +==== +# waived from the line above +module m; +// vfmt: waive no-tabs + wire a; +endmodule +==== +# a waiver that waives nothing is reported +module m; + wire a; // vfmt: waive no-tabs +//^ 11 unused-waiver +endmodule +==== +# fix: each tab becomes the indent width +module m; + wire a; +//^ 1 no-tabs +endmodule +---- +module m; + wire a; +//^ 1 no-tabs +endmodule +==== +# fix: a tab inside a string survives fixing +module m; + initial $display("a b"); +//^ 1 no-tabs +endmodule +---- +module m; + initial $display("a b"); +//^ 1 no-tabs +endmodule +==== +# fix: a tab that is also trailing whitespace takes two rounds +module m; + wire a; +//^ 1 no-tabs +//^ 9 no-trailing-whitespace +endmodule +---- +module m; + wire a; +//^ 1 no-tabs +//^ 9 no-trailing-whitespace +endmodule diff --git a/crates/vlog_linter/tests/cases/no_trailing_whitespace.lint b/crates/vlog_linter/tests/cases/no_trailing_whitespace.lint new file mode 100644 index 0000000..88c84c4 --- /dev/null +++ b/crates/vlog_linter/tests/cases/no_trailing_whitespace.lint @@ -0,0 +1,48 @@ +# trailing spaces are reported where the trailing run starts +module m; + wire a; +//^ 10 no-trailing-whitespace +endmodule +==== +# a clean line is quiet +module m; + wire a; +endmodule +==== +# waived from the line above +module m; +// vfmt: waive no-trailing-whitespace + wire a; +endmodule +==== +# a waiver that waives nothing is reported +module m; + wire a; // vfmt: waive no-trailing-whitespace +//^ 11 unused-waiver +endmodule +==== +# fix: the trailing run is deleted +module m; + wire a; +//^ 10 no-trailing-whitespace +endmodule +---- +module m; + wire a; +//^ 10 no-trailing-whitespace +endmodule +==== +# fix: every trailing run in the file goes in one round +module m; + wire a; +//^ 10 no-trailing-whitespace + wire b; +//^ 10 no-trailing-whitespace +endmodule +---- +module m; + wire a; +//^ 10 no-trailing-whitespace + wire b; +//^ 10 no-trailing-whitespace +endmodule diff --git a/crates/vlog_linter/tests/cases/parameter_name_style.lint b/crates/vlog_linter/tests/cases/parameter_name_style.lint new file mode 100644 index 0000000..109c041 --- /dev/null +++ b/crates/vlog_linter/tests/cases/parameter_name_style.lint @@ -0,0 +1,21 @@ +# a lower_snake_case parameter name is flagged +module m; + parameter int addr_width = 8; +//^ 17 parameter-name-style +endmodule +==== +# CamelCase and ALL_CAPS are both accepted, header and body alike +module m #(parameter int AddrWidth = 8) (); + localparam int ADDR_W = 4; +endmodule +==== +# waived on the same line +module m; + parameter int addr_width = 8; // vfmt: waive parameter-name-style +endmodule +==== +# a waiver that waives nothing is reported +module m; + parameter int AddrWidth = 8; // vfmt: waive parameter-name-style +//^ 32 unused-waiver +endmodule diff --git a/crates/vlog_linter/tests/cases/struct_union_name_style.lint b/crates/vlog_linter/tests/cases/struct_union_name_style.lint new file mode 100644 index 0000000..6fa3d1a --- /dev/null +++ b/crates/vlog_linter/tests/cases/struct_union_name_style.lint @@ -0,0 +1,21 @@ +# a typedef struct without the _t suffix is flagged at its name +package p; + typedef struct packed { logic a; } addr; +//^ 38 struct-union-name-style +endpackage +==== +# a _t-suffixed union name is quiet +package p; + typedef union packed { logic a; } addr_t; +endpackage +==== +# waived on the same line +package p; + typedef struct packed { logic a; } addr; // vfmt: waive struct-union-name-style +endpackage +==== +# a waiver that waives nothing is reported +package p; + typedef struct packed { logic a; } addr_t; // vfmt: waive struct-union-name-style +//^ 46 unused-waiver +endpackage diff --git a/crates/vlog_linter/tests/cases/waivers.lint b/crates/vlog_linter/tests/cases/waivers.lint new file mode 100644 index 0000000..d9af050 --- /dev/null +++ b/crates/vlog_linter/tests/cases/waivers.lint @@ -0,0 +1,65 @@ +# a start/stop range covers its markers and everything between +module m; +// vfmt: waive-start no-tabs + wire a; + wire b; +// vfmt: waive-stop no-tabs + wire c; +//^ 1 no-tabs +endmodule +==== +# an unclosed range runs to the end of the file +module m; +// vfmt: waive-start no-tabs + wire a; + wire b; +endmodule +==== +# a stop closes the innermost open start +module m; +// vfmt: waive-start no-tabs +// vfmt: waive-start no-tabs + wire a; +// vfmt: waive-stop no-tabs + wire b; +// vfmt: waive-stop no-tabs + wire c; +//^ 1 no-tabs +endmodule +==== +# a verible waiver for a rule vfmt does not have is ignored +module m; + // verilog_lint: waive macro-name-style + wire a; +endmodule +==== +# vfmt's own spelling for an unknown rule is reported +module m; + // vfmt: waive macro-name-style +//^ 3 unused-waiver + wire a; +endmodule +==== +# a malformed waiver is reported +module m; + // vfmt: waive +//^ 3 unused-waiver +endmodule +==== +# a waive-stop with nothing open is reported +module m; + // vfmt: waive-stop no-tabs +//^ 3 unused-waiver +endmodule +==== +# a waiver for a rule this run did not enable is silent +#select no-trailing-whitespace,unused-waiver +module m; + wire a; // vfmt: waive no-tabs +endmodule +==== +# an unused waiver can itself be waived +module m; +// vfmt: waive unused-waiver + wire a; // vfmt: waive no-tabs +endmodule diff --git a/crates/vlog_linter/tests/cases/wire_reg_mixup.lint b/crates/vlog_linter/tests/cases/wire_reg_mixup.lint new file mode 100644 index 0000000..dd73459 --- /dev/null +++ b/crates/vlog_linter/tests/cases/wire_reg_mixup.lint @@ -0,0 +1,37 @@ +# reg in a .sv file is flagged at the keyword +#path rtl/m.sv +module m; + reg q; +//^ 3 wire-reg-mixup +endmodule +==== +# logic and wire are both fine in a .sv file +#path rtl/m.sv +module m; + logic q; + wire w; +endmodule +==== +# reg in a .v file is Verilog and the rule has no opinion +#path rtl/m.v +module m; + reg q; +endmodule +==== +# a nameless buffer gets no SystemVerilog-ness decision +module m; + reg q; +endmodule +==== +# waived on the same line +#path rtl/m.sv +module m; + reg q; // vfmt: waive wire-reg-mixup +endmodule +==== +# a waiver that waives nothing is reported +#path rtl/m.sv +module m; + logic q; // vfmt: waive wire-reg-mixup +//^ 12 unused-waiver +endmodule diff --git a/crates/vlog_linter/tests/lint_cases.rs b/crates/vlog_linter/tests/lint_cases.rs new file mode 100644 index 0000000..ca345d9 --- /dev/null +++ b/crates/vlog_linter/tests/lint_cases.rs @@ -0,0 +1,575 @@ +//! File-driven lint rule tests, in the spirit of Verible's `LintTestCase` / +//! `RunLintTestCases` and of the formatter's `tests/cases.rs` table harness. +//! +//! Every `tests/cases/*.lint` file holds a list of small cases separated by +//! `====` lines. A case is Verilog source with its expected findings written +//! into it: a line whose trimmed text is `//^ ` asserts one +//! finding of that rule at that 1-based column on the nearest preceding +//! non-marker line — the same `line:col` that `vfmt check` prints, so a +//! marker can be written by copying the diagnostic. Marker lines are ordinary +//! comments to the linter, so the source stays valid Verilog. +//! +//! The match is **exact**, in both directions: a marked finding that is not +//! reported fails the case, and a reported finding that is not marked fails +//! it too. +//! +//! `#` lines at the top of a case name it; three headers are special: +//! +//! - `#SKIP ...` — a known-bad case: it must still fail, and the moment it +//! passes the suite demands the marker's removal. +//! - `#path

` — lint the source as if it were read from this file path. +//! - `#select ...` — comma-separated rule names, `vfmt check --select` +//! semantics (replaces the default rule set). +//! +//! A `----` line splits a case into `(input, expected fixed output)`: the +//! harness then applies Safe fixes in the CLI's fix→re-lint loop and asserts +//! the fixpoint equals the expected text, that no enabled rule still offers a +//! Safe fix on it, and — the cross-tool guarantee — that the formatter +//! accepts the fixed output and formats it to a fixed point. A fix case whose +//! *input* the formatter refuses (the tolerant population only the linter +//! sees) must say so with a `#tolerant` header, which skips the formatter +//! checks; like `#SKIP`, the header must be true — the moment the input +//! formats, the suite demands its removal. Full format spec: +//! `docs/features/lint-harness/README.md`. + +use std::path::PathBuf; + +use vlog_formatter::{format_source, Config}; +use vlog_linter::{ + apply_fixes, lint, rule_by_name, run, select_rules, Applicability, ParsedSource, Rule, +}; +use vlog_parser::LineIndex; + +/// One case: source with inline markers, and optionally a fixed output. +struct Case { + name: String, + line: usize, + skip: bool, + tolerant: bool, + path: Option, + select: Vec, + input: String, + fixed: Option, +} + +/// One `//^ ` marker, resolved to the line it points at. +struct Expect { + line: u32, + col: u32, + rule: String, +} + +fn cases_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/cases") +} + +/// Splits one `.lint` file into cases; returns an error string on bad syntax. +fn parse_cases(file: &str, text: &str) -> Result, String> { + let mut cases = Vec::new(); + let mut start = 1usize; + let mut block: Vec<&str> = Vec::new(); + // A synthetic terminator lets the last case close like every other one. + for (idx, line) in text.lines().chain(std::iter::once("====")).enumerate() { + if line.trim_end() != "====" { + if block.is_empty() { + start = idx + 1; + } + block.push(line); + } else { + if block.iter().any(|l| !l.trim().is_empty()) { + cases.push(split_case(file, start, &block)?); + } + block.clear(); + } + } + Ok(cases) +} + +/// Splits one case block into headers, input and (optionally) fixed output. +fn split_case(file: &str, start: usize, block: &[&str]) -> Result { + let mut name = String::new(); + let mut skip = false; + let mut tolerant = false; + let mut path = None; + let mut select = Vec::new(); + let mut body = block; + while let Some(first) = body.first() { + if !first.starts_with('#') && !first.trim().is_empty() { + break; + } + if let Some(rest) = first.strip_prefix('#') { + // A directive is `#word` (no space after the `#`); a case name + // is `# text`. A `#word` that is not a known directive is a + // case-file error, so a typo'd `#patth` fails loudly instead of + // silently becoming name text and weakening what the case pins + // (QA finding, lead-fixed). + let directive_like = !rest.starts_with(char::is_whitespace) && !rest.is_empty(); + let rest = rest.trim(); + if let Some(p) = rest.strip_prefix("path ") { + path = Some(p.trim().to_string()); + } else if let Some(s) = rest.strip_prefix("select ") { + select = s.split(',').map(|r| r.trim().to_string()).collect(); + } else if rest == "tolerant" { + tolerant = true; + } else if rest.starts_with("SKIP") { + skip = true; + if !name.is_empty() { + name.push(' '); + } + name.push_str(rest); + } else if directive_like { + return Err(format!( + "{file}:{start}: unknown directive `#{}` \ + (known: #path, #select, #tolerant, #SKIP; \ + a case name needs a space after `#`)", + rest.split_whitespace().next().unwrap_or(rest) + )); + } else { + if !name.is_empty() { + name.push(' '); + } + name.push_str(rest); + } + } + body = &body[1..]; + } + if name.is_empty() { + name = format!(""); + } + let (input, fixed) = match body.iter().position(|l| l.trim_end() == "----") { + Some(sep) => (join(&body[..sep]), Some(join(&body[sep + 1..]))), + None => (join(body), None), + }; + if input.trim().is_empty() { + return Err(format!("{file}:{start}: case has no source")); + } + Ok(Case { name, line: start, skip, tolerant, path, select, input, fixed }) +} + +/// Rejoins lines into a source string with a trailing newline (empty stays empty). +fn join(lines: &[&str]) -> String { + let mut out = String::new(); + for line in lines { + out.push_str(line); + out.push('\n'); + } + out +} + +/// The `(line, col, rule)` findings the markers in `input` ask for. +fn expectations(input: &str) -> Result, String> { + let mut out = Vec::new(); + let mut code_line = 0u32; + for (i, text) in input.lines().enumerate() { + let Some(rest) = text.trim().strip_prefix("//^") else { + code_line = i as u32 + 1; + continue; + }; + let rest = rest.trim(); + let (col, rule) = rest.split_once(char::is_whitespace).ok_or_else(|| { + format!("marker on line {} must be `//^ `: `//^ {rest}`", i + 1) + })?; + let col: u32 = col + .parse() + .map_err(|_| format!("marker on line {}: `{col}` is not a column number", i + 1))?; + if code_line == 0 { + return Err(format!("marker on line {} has no code line above it", i + 1)); + } + out.push(Expect { line: code_line, col, rule: rule.trim().to_string() }); + } + Ok(out) +} + +/// Runs one case; `Err` is the complete, readable failure report. +fn check_case(file: &str, case: &Case) -> Result<(), String> { + let at = format!("{file}:{} [{}]", case.line, case.name); + let rules = select_rules(&case.select, &[]).map_err(|e| format!("{at}: bad #select: {e}"))?; + let expected = expectations(&case.input).map_err(|e| format!("{at}: {e}"))?; + for expect in &expected { + if rule_by_name(&expect.rule).is_none() { + return Err(format!( + "{at}: marker names a rule that does not exist: `{}` — a renamed or \ + removed rule must take its markers with it", + expect.rule + )); + } + if !rules.iter().any(|r| r.name() == expect.rule) { + return Err(format!( + "{at}: marker expects `{}`, which this case does not enable — add it to #select", + expect.rule + )); + } + } + + let path = case.path.clone().map(PathBuf::from); + let violations = run(&case.input, path.clone(), &rules); + + // "One parse, two tools", held over every case: a context built from + // pre-parsed products must find exactly what one built from the source + // does — rule, message, span and fix alike (the Debug form carries all). + let parsed = ParsedSource::parse(&case.input); + let via_products = lint(&parsed.context(path.clone()), &rules); + if format!("{violations:?}") != format!("{via_products:?}") { + return Err(format!( + "{at}: linting from pre-parsed products found something different from \ + linting the source — the one-parse contract broke" + )); + } + + let index = LineIndex::new(&case.input); + let mut got: Vec<(u32, u32, String)> = violations + .iter() + .map(|v| { + let (line, col) = index.line_col(v.span.start); + (line, col, v.rule.to_string()) + }) + .collect(); + let mut want: Vec<(u32, u32, String)> = + expected.iter().map(|e| (e.line, e.col, e.rule.clone())).collect(); + want.sort(); + got.sort(); + if want != got { + return Err(mismatch_report(&at, case, &want, &got, &violations, &index)); + } + + match &case.fixed { + Some(expected_fixed) => check_fix(&at, case, &rules, path, expected_fixed), + None => Ok(()), + } +} + +/// Renders the two-direction exact-match failure: what was marked but not +/// reported, what was reported but not marked, and the numbered source. +fn mismatch_report( + at: &str, + case: &Case, + want: &[(u32, u32, String)], + got: &[(u32, u32, String)], + violations: &[vlog_linter::Violation], + index: &LineIndex, +) -> String { + let mut unexpected = got.to_vec(); + let mut missing = Vec::new(); + for w in want { + match unexpected.iter().position(|g| g == w) { + Some(i) => { + unexpected.remove(i); + } + None => missing.push(w.clone()), + } + } + let mut out = format!("{at}: findings do not match the markers\n"); + if !missing.is_empty() { + out.push_str(" missing (marked, not reported):\n"); + for (line, col, rule) in &missing { + out.push_str(&format!(" {line}:{col} {rule}\n")); + } + } + if !unexpected.is_empty() { + out.push_str(" unexpected (reported, not marked):\n"); + for (line, col, rule) in &unexpected { + let message = violations + .iter() + .find(|v| { + let (l, c) = index.line_col(v.span.start); + (l, c, v.rule) == (*line, *col, rule.as_str()) + }) + .map(|v| v.message.as_str()) + .unwrap_or(""); + out.push_str(&format!(" {line}:{col} {rule} — {message}\n")); + } + } + out.push_str(" source:\n"); + for (i, text) in case.input.lines().enumerate() { + out.push_str(&format!(" {:>3} | {text}\n", i + 1)); + } + out +} + +/// The fix half of a case: the CLI's fix→re-lint loop must land exactly on +/// the expected text, leave nothing Safe-fixable behind, and never turn a +/// formatter-accepted input into a formatter-refused output. +fn check_fix( + at: &str, + case: &Case, + rules: &[&'static dyn Rule], + path: Option, + expected_fixed: &str, +) -> Result<(), String> { + let mut fixed = case.input.clone(); + for round in 0.. { + if round >= 10 { + return Err(format!("{at}: fixing did not settle within 10 rounds")); + } + let found = run(&fixed, path.clone(), rules); + let out = apply_fixes(&fixed, &found, false); + if out.applied == 0 { + break; + } + fixed = out.output; + } + if fixed != expected_fixed { + return Err(format!( + "{at}: fixed output differs from expected\n{}", + diff(expected_fixed, &fixed) + )); + } + + // Clean for the fixed rules: at the fixpoint, no enabled rule may still + // offer a Safe fix — a violation without a fix (or with an Unsafe one) + // may legitimately survive. + let index = LineIndex::new(&fixed); + let still_fixable: Vec = run(&fixed, path.clone(), rules) + .iter() + .filter(|v| v.fix.as_ref().is_some_and(|f| f.applicability == Applicability::Safe)) + .map(|v| { + let (line, col) = index.line_col(v.span.start); + format!(" {line}:{col} {} — {}", v.rule, v.message) + }) + .collect(); + if !still_fixable.is_empty() { + return Err(format!( + "{at}: the fixed output still has Safe-fixable findings:\n{}", + still_fixable.join("\n") + )); + } + + // Cross-tool guarantee: a fix must never produce something the formatter + // refuses — unless the input was refused too (the tolerant population the + // linter accepts and the formatter never will; nothing is promised there). + // That population is opt-in per case: `#tolerant` skips the formatter + // checks, and must be removed the moment the input starts formatting. + let config = Config::default(); + match (case.tolerant, format_source(&case.input, &config)) { + (true, Ok(_)) => Err(format!( + "{at}: marked #tolerant but the input formats — remove the #tolerant marker" + )), + (true, Err(_)) => Ok(()), + (false, Err(e)) => Err(format!( + "{at}: the formatter refuses this fix case's input ({e}) — mark it #tolerant \ + if that is intended" + )), + (false, Ok(_)) => { + let once = format_source(&fixed, &config).map_err(|e| { + format!("{at}: the formatter accepts the input but refuses the fixed output: {e}") + })?; + match format_source(&once, &config) { + Ok(twice) if twice == once => Ok(()), + Ok(twice) => Err(format!( + "{at}: formatting the fixed output does not converge\n{}", + diff(&once, &twice) + )), + Err(e) => Err(format!("{at}: reformatting the formatted fixed output failed: {e}")), + } + } + } +} + +/// Renders expected vs actual as a line-oriented diff. +fn diff(expected: &str, got: &str) -> String { + let (e, g): (Vec<_>, Vec<_>) = (expected.lines().collect(), got.lines().collect()); + let mut out = String::new(); + for i in 0..e.len().max(g.len()) { + match (e.get(i), g.get(i)) { + (Some(a), Some(b)) if a == b => out.push_str(&format!(" {a}\n")), + (a, b) => { + if let Some(a) = a { + out.push_str(&format!(" - {a}\n")); + } + if let Some(b) = b { + out.push_str(&format!(" + {b}\n")); + } + } + } + } + out +} + +/// The suite's judgment of one case: `None` is a pass. A `#SKIP` case must +/// fail; the moment it passes, demand the marker's removal so the case +/// becomes a live regression test. +fn verdict(file: &str, case: &Case) -> Option { + let result = check_case(file, case); + if case.skip { + match result { + Ok(()) => Some(format!( + "{file}:{} [{}]: marked #SKIP but now passes — remove the #SKIP marker", + case.line, case.name + )), + Err(_) => None, + } + } else { + result.err() + } +} + +#[test] +fn lint_case_tables() { + let mut files: Vec = std::fs::read_dir(cases_dir()) + .expect("cases dir") + .map(|e| e.expect("dir entry").path()) + .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("lint")) + .collect(); + files.sort(); + assert!(!files.is_empty(), "no .lint files found"); + + let mut failures = Vec::new(); + let mut total = 0usize; + for path in &files { + let text = std::fs::read_to_string(path).expect("read cases file"); + let file = path.file_name().unwrap().to_string_lossy().to_string(); + let cases = match parse_cases(&file, &text) { + Ok(c) => c, + Err(e) => { + failures.push(e); + continue; + } + }; + for case in cases { + if !case.skip { + total += 1; + } + if let Some(failure) = verdict(&file, &case) { + failures.push(failure); + } + } + } + assert!(total > 0, "no cases found"); + assert!( + failures.is_empty(), + "{} of {total} cases failed:\n\n{}", + failures.len(), + failures.join("\n") + ); +} + +// ------------------------------------------------- the harness polices itself +// +// Each test feeds the runner a deliberately wrong scratch case and asserts the +// failure report is the readable one the README shows — the harness's own +// failure modes are pinned the same way the rules' are. + +/// Parses scratch text as one case of a file called `scratch.lint`. +fn scratch(text: &str) -> Case { + let mut cases = parse_cases("scratch.lint", text).expect("scratch case parses"); + assert_eq!(cases.len(), 1, "scratch text must hold exactly one case"); + cases.remove(0) +} + +#[test] +fn a_correct_case_passes() { + let case = scratch("# ok\nmodule m;\n\twire a;\n//^ 1 no-tabs\nendmodule\n"); + assert_eq!(check_case("scratch.lint", &case), Ok(())); +} + +#[test] +fn a_wrong_column_fails_in_both_directions() { + let case = scratch("# wrong col\nmodule m;\n\twire a;\n//^ 2 no-tabs\nendmodule\n"); + let report = check_case("scratch.lint", &case).expect_err("must fail"); + assert!(report.contains("missing (marked, not reported):\n 2:2 no-tabs"), "{report}"); + assert!( + report.contains("unexpected (reported, not marked):\n 2:1 no-tabs — tab character"), + "{report}" + ); + assert!(report.contains("scratch.lint:1 [wrong col]"), "{report}"); + assert!(report.contains(" 1 | module m;"), "the source must be shown\n{report}"); +} + +#[test] +fn an_unmarked_finding_is_unexpected() { + let case = scratch("# unmarked\nmodule m;\n\twire a;\nendmodule\n"); + let report = check_case("scratch.lint", &case).expect_err("must fail"); + assert!(report.contains("unexpected (reported, not marked):"), "{report}"); + assert!(!report.contains("missing (marked, not reported):"), "{report}"); +} + +#[test] +fn a_marker_naming_a_dead_rule_is_a_case_error() { + let case = scratch("# stale\nmodule m;\n\twire a;\n//^ 1 no-tab\nendmodule\n"); + let report = check_case("scratch.lint", &case).expect_err("must fail"); + assert!(report.contains("marker names a rule that does not exist: `no-tab`"), "{report}"); +} + +#[test] +fn a_marker_for_an_unselected_rule_is_a_case_error() { + let case = scratch("# off\nmodule FooBar;\n//^ 8 module-name-style\nendmodule\n"); + let report = check_case("scratch.lint", &case).expect_err("must fail"); + assert!(report.contains("which this case does not enable"), "{report}"); +} + +#[test] +fn a_marker_without_a_column_is_a_case_error() { + let case = scratch("# bad marker\nmodule m;\n//^ no-tabs\nendmodule\n"); + let report = check_case("scratch.lint", &case).expect_err("must fail"); + assert!(report.contains("must be `//^ `"), "{report}"); +} + +#[test] +fn a_marker_above_all_code_is_a_case_error() { + let case = scratch("# floating\n//^ 1 no-tabs\nmodule m;\nendmodule\n"); + let report = check_case("scratch.lint", &case).expect_err("must fail"); + assert!(report.contains("has no code line above it"), "{report}"); +} + +#[test] +fn a_typoed_directive_is_a_case_error_not_a_name() { + // QA finding, lead-fixed: `#patth rtl/m.v` used to be absorbed into the + // case name, silently weakening what a #path-dependent case pins. + let err = match parse_cases("scratch.lint", "#patth rtl/m.v\nmodule m;\nendmodule\n") { + Ok(_) => panic!("a typo'd directive must fail the file"), + Err(e) => e, + }; + assert!(err.contains("unknown directive `#patth`"), "{err}"); + assert!(err.contains("a case name needs a space after `#`"), "{err}"); +} + +#[test] +fn an_unknown_select_is_a_case_error() { + let case = scratch("# bad select\n#select no-such-rule\nmodule m;\nendmodule\n"); + let report = check_case("scratch.lint", &case).expect_err("must fail"); + assert!(report.contains("bad #select: unknown rule: no-such-rule"), "{report}"); +} + +#[test] +fn a_wrong_fixed_output_shows_a_diff() { + let case = scratch( + "# wrong fix\nmodule m;\n\twire a;\n//^ 1 no-tabs\nendmodule\n----\nmodule m;\n wire a;\n//^ 1 no-tabs\nendmodule\n", + ); + let report = check_case("scratch.lint", &case).expect_err("must fail"); + assert!(report.contains("fixed output differs from expected"), "{report}"); + assert!(report.contains(" - wire a;"), "{report}"); + assert!(report.contains(" + wire a;"), "{report}"); +} + +#[test] +fn a_fix_case_the_formatter_refuses_must_say_tolerant() { + // `@@@` parses only tolerantly: the linter still fixes the tab, and the + // formatter refuses the file — the cross-tool guarantee has no ground to + // stand on, which the case must own up to with `#tolerant`. + let body = "module m;\n\t@@@ x\n//^ 1 no-tabs\nendmodule\n----\nmodule m;\n @@@ x\n//^ 1 no-tabs\nendmodule\n"; + let unmarked = scratch(&format!("# refused\n{body}")); + let report = check_case("scratch.lint", &unmarked).expect_err("must fail"); + assert!(report.contains("mark it #tolerant if that is intended"), "{report}"); + + let marked = scratch(&format!("# refused\n#tolerant\n{body}")); + assert_eq!(check_case("scratch.lint", &marked), Ok(())); +} + +#[test] +fn a_tolerant_marker_on_a_formattable_input_demands_its_removal() { + let case = scratch( + "# fine\n#tolerant\nmodule m;\n\twire a;\n//^ 1 no-tabs\nendmodule\n----\nmodule m;\n wire a;\n//^ 1 no-tabs\nendmodule\n", + ); + let report = check_case("scratch.lint", &case).expect_err("must fail"); + assert!(report.contains("remove the #tolerant marker"), "{report}"); +} + +#[test] +fn a_skip_case_that_passes_demands_its_marker_removed() { + let case = scratch("#SKIP now fine\nmodule m;\n\twire a;\n//^ 1 no-tabs\nendmodule\n"); + let failure = verdict("scratch.lint", &case).expect("a passing #SKIP case must fail"); + assert!(failure.contains("marked #SKIP but now passes"), "{failure}"); + + let case = scratch("#SKIP still bad\nmodule m;\n\twire a;\n//^ 2 no-tabs\nendmodule\n"); + assert_eq!(verdict("scratch.lint", &case), None, "a failing #SKIP case is not a failure"); +} diff --git a/crates/vlog_linter/tests/rules.rs b/crates/vlog_linter/tests/rules.rs deleted file mode 100644 index 0119cb0..0000000 --- a/crates/vlog_linter/tests/rules.rs +++ /dev/null @@ -1,523 +0,0 @@ -//! Rule tests in Verible's `RunLintTestCases` style: the expected findings -//! are written into the source itself, and the match is **exact** — an -//! unexpected finding fails the test just as a missing one does. -//! -//! A line whose trimmed text is `//~ ` asserts one finding of that -//! rule on the nearest preceding non-marker line. Marker lines are ordinary -//! comments to the linter, so the source stays valid Verilog. -//! -//! Every rule gets the same four cases: it fires, it stays quiet, a waiver -//! silences it, and a waiver that silences nothing is itself reported. - -use std::path::PathBuf; - -use vlog_linter::{default_rules, run, select_rules}; - -/// Asserts that linting `src` (as `path`) finds exactly what its markers say. -#[track_caller] -fn assert_lint(path: Option<&str>, src: &str) { - assert_lint_with(&default_rules(), path, src) -} - -/// The same, for a rule that a plain `vfmt check` does not run. -#[track_caller] -fn assert_lint_selecting(rule: &str, path: Option<&str>, src: &str) { - let rules = select_rules(&[rule.to_string(), "unused-waiver".to_string()], &[]).unwrap(); - assert_lint_with(&rules, path, src) -} - -#[track_caller] -fn assert_lint_with(rules: &[&'static dyn vlog_linter::Rule], path: Option<&str>, src: &str) { - let violations = run(src, path.map(PathBuf::from), rules); - let index = vlog_parser::LineIndex::new(src); - - // "One parse, two tools" property, checked over every rule test input: - // a context built from pre-parsed products must find exactly what one - // built from the source does — rule, message, span and fix alike (the - // Debug form carries all four). - let parsed = vlog_linter::ParsedSource::parse(src); - let via_products = vlog_linter::lint(&parsed.context(path.map(PathBuf::from)), rules); - assert_eq!( - format!("{violations:?}"), - format!("{via_products:?}"), - "products in must equal source in\nsource:\n{src}" - ); - - let mut actual: Vec<(u32, String)> = - violations.iter().map(|v| (index.line_col(v.span.start).0, v.rule.to_string())).collect(); - let mut expected = expectations(src); - actual.sort(); - expected.sort(); - - assert_eq!( - expected, actual, - "\nexpected (line, rule) findings on the left, got the right\nsource:\n{src}\nmessages: {:#?}", - violations.iter().map(|v| format!("{}: {}", v.rule, v.message)).collect::>() - ); -} - -/// The `(line, rule)` pairs the markers in `src` ask for. -fn expectations(src: &str) -> Vec<(u32, String)> { - let mut out = Vec::new(); - let mut code_line = 0u32; - for (i, text) in src.lines().enumerate() { - match text.trim().strip_prefix("//~") { - Some(rule) => out.push((code_line, rule.trim().to_string())), - None => code_line = i as u32 + 1, - } - } - out -} - -// ---------------------------------------------------------------- harness - -#[test] -fn the_harness_notices_a_missing_marker() { - let src = "module m;\n\twire a;\nendmodule\n"; - let violations = run(src, None, &default_rules()); - assert_eq!(violations.len(), 1, "fixture must violate exactly one rule"); - assert!(expectations(src).is_empty(), "and the unmarked source must expect none"); -} - -#[test] -fn a_rule_off_by_default_says_nothing_until_selected() { - let src = "module FooBar;\nendmodule\n"; - assert!(run(src, None, &default_rules()).is_empty()); - assert_lint_selecting( - "module-name-style", - None, - "module FooBar;\n//~ module-name-style\nendmodule\n", - ); -} - -// ---------------------------------------------------------------- no-tabs - -#[test] -fn no_tabs_fires() { - assert_lint(None, "module m;\n\twire a;\n//~ no-tabs\nendmodule\n"); -} - -#[test] -fn no_tabs_is_quiet_on_spaces() { - assert_lint(None, "module m;\n wire a;\nendmodule\n"); -} - -#[test] -fn no_tabs_is_waived() { - assert_lint(None, "module m;\n// vfmt: waive no-tabs\n\twire a;\nendmodule\n"); - assert_lint(None, "module m;\n\twire a; // vfmt: waive no-tabs\nendmodule\n"); -} - -#[test] -fn no_tabs_waiver_that_waives_nothing_is_reported() { - assert_lint( - None, - "module m;\n wire a; // vfmt: waive no-tabs\n//~ unused-waiver\nendmodule\n", - ); -} - -// ------------------------------------------------- no-trailing-whitespace - -#[test] -fn no_trailing_whitespace_fires() { - assert_lint(None, "module m;\n wire a; \n//~ no-trailing-whitespace\nendmodule\n"); -} - -#[test] -fn no_trailing_whitespace_is_quiet_on_a_clean_line() { - assert_lint(None, "module m;\n wire a;\nendmodule\n"); -} - -#[test] -fn no_trailing_whitespace_is_waived() { - assert_lint(None, "module m;\n// vfmt: waive no-trailing-whitespace\n wire a; \nendmodule\n"); -} - -#[test] -fn no_trailing_whitespace_waiver_that_waives_nothing_is_reported() { - assert_lint( - None, - "module m;\n wire a; // vfmt: waive no-trailing-whitespace\n//~ unused-waiver\nendmodule\n", - ); -} - -// ----------------------------------------------------- case-missing-default - -#[test] -fn case_missing_default_fires() { - assert_lint( - None, - "module m;\n always_comb begin\n case (s)\n//~ case-missing-default\n 0: x = 1;\n endcase\n end\nendmodule\n", - ); -} - -#[test] -fn case_missing_default_is_quiet_with_a_default() { - assert_lint( - None, - "module m;\n always_comb begin\n case (s)\n 0: x = 1;\n default: x = 0;\n endcase\n end\nendmodule\n", - ); -} - -#[test] -fn case_missing_default_is_waived() { - assert_lint( - None, - "module m;\n always_comb begin\n // vfmt: waive case-missing-default\n case (s)\n 0: x = 1;\n endcase\n end\nendmodule\n", - ); -} - -#[test] -fn case_missing_default_waiver_that_waives_nothing_is_reported() { - assert_lint( - None, - "module m;\n always_comb begin\n case (s)\n 0: x = 1;\n default: x = 0;\n endcase // vfmt: waive case-missing-default\n//~ unused-waiver\n end\nendmodule\n", - ); -} - -// -------------------------------------------------- always-ff-non-blocking - -#[test] -fn always_ff_non_blocking_fires() { - assert_lint( - None, - "module m;\n always_ff @(posedge clk) q = d;\n//~ always-ff-non-blocking\nendmodule\n", - ); -} - -#[test] -fn always_ff_non_blocking_is_quiet_on_nonblocking() { - assert_lint(None, "module m;\n always_ff @(posedge clk) q <= d;\nendmodule\n"); -} - -#[test] -fn always_ff_non_blocking_is_waived() { - assert_lint( - None, - "module m;\n always_ff @(posedge clk) q = d; // vfmt: waive always-ff-non-blocking\nendmodule\n", - ); -} - -#[test] -fn always_ff_non_blocking_waiver_that_waives_nothing_is_reported() { - assert_lint( - None, - "module m;\n always_ff @(posedge clk) q <= d; // vfmt: waive always-ff-non-blocking\n//~ unused-waiver\nendmodule\n", - ); -} - -// ---------------------------------------------------- always-comb-blocking - -#[test] -fn always_comb_blocking_fires() { - assert_lint(None, "module m;\n always_comb x <= y;\n//~ always-comb-blocking\nendmodule\n"); -} - -#[test] -fn always_comb_blocking_is_quiet_on_blocking() { - assert_lint(None, "module m;\n always_comb x = y;\nendmodule\n"); -} - -#[test] -fn always_comb_blocking_is_waived() { - assert_lint( - None, - "module m;\n// verilog_lint: waive always-comb-blocking\n always_comb x <= y;\nendmodule\n", - ); -} - -#[test] -fn always_comb_blocking_waiver_that_waives_nothing_is_reported() { - assert_lint( - None, - "module m;\n always_comb x = y; // vfmt: waive always-comb-blocking\n//~ unused-waiver\nendmodule\n", - ); -} - -// -------------------------------------- explicit-parameter-storage-type - -#[test] -fn explicit_parameter_storage_type_fires() { - assert_lint( - None, - "module m;\n parameter WIDTH = 8;\n//~ explicit-parameter-storage-type\nendmodule\n", - ); -} - -#[test] -fn explicit_parameter_storage_type_is_quiet_when_typed() { - assert_lint(None, "module m;\n parameter int WIDTH = 8;\nendmodule\n"); -} - -#[test] -fn explicit_parameter_storage_type_is_waived() { - assert_lint( - None, - "module m;\n parameter WIDTH = 8; // vfmt: waive explicit-parameter-storage-type\nendmodule\n", - ); -} - -#[test] -fn explicit_parameter_storage_type_waiver_that_waives_nothing_is_reported() { - assert_lint( - None, - "module m;\n parameter int WIDTH = 8; // vfmt: waive explicit-parameter-storage-type\n//~ unused-waiver\nendmodule\n", - ); -} - -// -------------------------------------------------------- module-filename - -#[test] -fn module_filename_fires() { - assert_lint(Some("rtl/bar.sv"), "module foo;\n//~ module-filename\nendmodule\n"); -} - -#[test] -fn module_filename_is_quiet_when_it_matches_or_has_no_path() { - assert_lint(Some("rtl/foo.sv"), "module foo;\nendmodule\n"); - assert_lint(None, "module foo;\nendmodule\n"); -} - -#[test] -fn module_filename_is_waived() { - assert_lint(Some("rtl/bar.sv"), "module foo; // vfmt: waive module-filename\nendmodule\n"); -} - -#[test] -fn module_filename_waiver_that_waives_nothing_is_reported() { - assert_lint( - Some("rtl/foo.sv"), - "module foo; // vfmt: waive module-filename\n//~ unused-waiver\nendmodule\n", - ); -} - -// ------------------------------------------------------------- mixed file - -#[test] -fn several_rules_on_one_file_report_independently() { - assert_lint( - Some("rtl/top.sv"), - "module foo #(parameter W = 1) ();\n\ -//~ module-filename\n\ -//~ explicit-parameter-storage-type\n\ -\talways_comb x <= 1;\n\ -//~ no-tabs\n\ -//~ always-comb-blocking\n\ -endmodule\n", - ); -} - -// ------------------------------------------------------ module-name-style - -#[test] -fn module_name_style_fires() { - assert_lint_selecting( - "module-name-style", - None, - "module FooBar;\n//~ module-name-style\nendmodule\n", - ); -} - -#[test] -fn module_name_style_is_quiet_on_lower_snake_case() { - assert_lint_selecting("module-name-style", None, "module foo_bar;\nendmodule\n"); -} - -#[test] -fn module_name_style_is_waived() { - assert_lint_selecting( - "module-name-style", - None, - "module FooBar; // vfmt: waive module-name-style\nendmodule\n", - ); -} - -#[test] -fn module_name_style_waiver_that_waives_nothing_is_reported() { - assert_lint_selecting( - "module-name-style", - None, - "module foo_bar; // vfmt: waive module-name-style\n//~ unused-waiver\nendmodule\n", - ); -} - -// --------------------------------------------------- parameter-name-style - -#[test] -fn parameter_name_style_fires() { - assert_lint( - None, - "module m;\n parameter int addr_width = 8;\n//~ parameter-name-style\nendmodule\n", - ); -} - -#[test] -fn parameter_name_style_accepts_both_presets() { - assert_lint( - None, - "module m #(parameter int AddrWidth = 8) ();\n localparam int ADDR_W = 4;\nendmodule\n", - ); -} - -#[test] -fn parameter_name_style_is_waived() { - assert_lint( - None, - "module m;\n parameter int addr_width = 8; // vfmt: waive parameter-name-style\nendmodule\n", - ); -} - -#[test] -fn parameter_name_style_waiver_that_waives_nothing_is_reported() { - assert_lint( - None, - "module m;\n parameter int AddrWidth = 8; // vfmt: waive parameter-name-style\n//~ unused-waiver\nendmodule\n", - ); -} - -// -------------------------------------------------------- enum-name-style - -#[test] -fn enum_name_style_fires() { - assert_lint( - None, - "package p;\n typedef enum logic { A, B } state;\n//~ enum-name-style\nendpackage\n", - ); -} - -#[test] -fn enum_name_style_is_quiet_on_a_suffixed_name() { - assert_lint(None, "package p;\n typedef enum logic { A, B } state_e;\nendpackage\n"); -} - -#[test] -fn enum_name_style_is_waived() { - assert_lint( - None, - "package p;\n// verilog_lint: waive enum-name-style\n typedef enum logic { A } state;\nendpackage\n", - ); -} - -#[test] -fn enum_name_style_waiver_that_waives_nothing_is_reported() { - assert_lint( - None, - "package p;\n typedef enum logic { A } state_e; // vfmt: waive enum-name-style\n//~ unused-waiver\nendpackage\n", - ); -} - -// ------------------------------------------------ struct-union-name-style - -#[test] -fn struct_union_name_style_fires() { - assert_lint( - None, - "package p;\n typedef struct packed { logic a; } addr;\n//~ struct-union-name-style\nendpackage\n", - ); -} - -#[test] -fn struct_union_name_style_is_quiet_on_a_suffixed_name() { - assert_lint(None, "package p;\n typedef union packed { logic a; } addr_t;\nendpackage\n"); -} - -#[test] -fn struct_union_name_style_is_waived() { - assert_lint( - None, - "package p;\n typedef struct packed { logic a; } addr; // vfmt: waive struct-union-name-style\nendpackage\n", - ); -} - -#[test] -fn struct_union_name_style_waiver_that_waives_nothing_is_reported() { - assert_lint( - None, - "package p;\n typedef struct packed { logic a; } addr_t; // vfmt: waive struct-union-name-style\n//~ unused-waiver\nendpackage\n", - ); -} - -// --------------------------------------------------------- wire-reg-mixup - -#[test] -fn wire_reg_mixup_fires() { - assert_lint(Some("rtl/m.sv"), "module m;\n reg q;\n//~ wire-reg-mixup\nendmodule\n"); -} - -#[test] -fn wire_reg_mixup_is_quiet_on_logic_and_on_verilog_files() { - assert_lint(Some("rtl/m.sv"), "module m;\n logic q;\n wire w;\nendmodule\n"); - assert_lint(Some("rtl/m.v"), "module m;\n reg q;\nendmodule\n"); - assert_lint(None, "module m;\n reg q;\nendmodule\n"); -} - -#[test] -fn wire_reg_mixup_is_waived() { - assert_lint(Some("rtl/m.sv"), "module m;\n reg q; // vfmt: waive wire-reg-mixup\nendmodule\n"); -} - -#[test] -fn wire_reg_mixup_waiver_that_waives_nothing_is_reported() { - assert_lint( - Some("rtl/m.sv"), - "module m;\n logic q; // vfmt: waive wire-reg-mixup\n//~ unused-waiver\nendmodule\n", - ); -} - -// ------------------------------------------------------ class-body reach - -#[test] -fn case_missing_default_reaches_a_class_method() { - assert_lint( - None, - "class c;\n\ - function void f(int x);\n\ - case (x)\n\ -//~ case-missing-default\n\ - 1: a = 1;\n\ - endcase\n\ - endfunction\n\ -endclass\n", - ); -} - -#[test] -fn explicit_parameter_storage_type_reaches_a_class_body_and_header() { - assert_lint( - None, - "class c #(parameter A = 1);\n\ -//~ explicit-parameter-storage-type\n\ - localparam B = 2;\n\ -//~ explicit-parameter-storage-type\n\ -endclass\n", - ); -} - -#[test] -fn a_class_inside_a_module_is_reached_too() { - assert_lint( - Some("rtl/m.sv"), - "module m;\n\ - class c;\n\ - localparam B = 2;\n\ -//~ explicit-parameter-storage-type\n\ - endclass\n\ -endmodule\n", - ); -} - -#[test] -fn the_always_rules_reach_a_class_body_too() { - // SystemVerilog forbids an `always` block inside a class, so this shape is - // not real-world code — but the tolerant parser accepts it and the walk is - // uniform, which is the property being pinned: no rule stops at `endclass`. - assert_lint( - None, - "class c;\n\ - always_comb x <= y;\n\ -//~ always-comb-blocking\n\ - always_ff @(posedge clk) q = d;\n\ -//~ always-ff-non-blocking\n\ -endclass\n", - ); -} diff --git a/docs/features/lint-harness/README.md b/docs/features/lint-harness/README.md new file mode 100644 index 0000000..e73cba0 --- /dev/null +++ b/docs/features/lint-harness/README.md @@ -0,0 +1,549 @@ +# lint-harness + +## Goal + +Give the linter the testing backbone Verible's rules have: TODO §5's +`LintTestCase`/`RunLintTestCases` port (test cases embed their expected +findings positionally in the source, matched **exactly** in both directions) +and its `RunApplyFixCases` equivalent (every autofix rule gets +`(input, fixed output)` pairs, with the fixed output itself lint-clean for the +fixed rules and never something the formatter would refuse). One file-driven +harness — `crates/vlog_linter/tests/lint_cases.rs` over +`crates/vlog_linter/tests/cases/*.lint` — replaces the per-rule Rust +boilerplate `tests/rules.rs` had accumulated: adding a rule's coverage is now +a data file, zero Rust. + +## Assumptions + +- **Marker lines are ordinary comments to the linter.** A `//^ ` + line is left in the source when linting, so line numbers in a failure + report are the case's own and the source stays valid Verilog. The linter + never interprets `//^` (verified: no rule or waiver grammar matches it). +- **Markers carry the CLI's coordinates.** `` is the 1-based column + `vfmt check` prints (`LineIndex::line_col` of the violation's span start), + so a marker can be written by copying a diagnostic. A caret positioned + *under* the span was rejected deliberately: tabs in the offending line are + themselves test content, so visual caret alignment lies, and a `//`-prefixed + caret line cannot point at columns 1–2 at all (where `no-tabs` fires most). +- **The default tab width (2) is what fix cases are written against** — + `LintContext::new`'s default, same as the CLI's default `--indent`. +- **A fix case runs the CLI's loop, not one pass**: apply Safe fixes → + re-lint, up to 10 rounds, and the fixpoint must equal the expected text. + One pass would under-describe `--fix` (a line ending in a tab takes two + rounds by design, and one .lint case pins exactly that). +- **"Lint-clean for the fixed rules" means: at the fixpoint, no enabled rule + still offers a Safe fix.** Violations without a fix (or with an Unsafe one) + may survive — they are findings, not failures. +- **Fences are out of the harness's scope.** `--fix` declining to edit inside + `// vfmt: off` is `crates/vfmt/src/lint.rs`'s behavior, not + `vlog_linter`'s; it stays tested by the CLI tests in + `crates/vfmt/tests/cli.rs`. +- **Unsafe fixes are untested here because none exist.** When the first rule + ships one, the fix loop needs an opt-in header (a `#unsafe-fixes` analog of + `--unsafe-fixes`) — noted so it is a case-format extension, not a redesign. + +## Handshakes + +**Consumed** + +- `vlog_linter`'s public API only: `run`, `lint`, `apply_fixes`, + `select_rules`, `rule_by_name`, `ParsedSource`, `Rule`, `Applicability`, + `Violation`. Nothing in `src/` was touched; the API needed no additions. +- `vlog_parser::LineIndex` for marker coordinates (the same conversion the + CLI prints with). +- `vlog_formatter::{format_source, Config}` — **new dev-dependency** of + `vlog_linter`, tests only, for the cross-tool guarantee. The library's + dependency list is unchanged: `cargo tree -p vlog_linter -e normal` is + still `vlog_parser` + std. (A plain `cargo tree -p vlog_linter` now shows + `vlog_formatter` under `[dev-dependencies]` — that is the harness, not the + crate.) No new external dependency; `vlog_formatter` is a workspace crate. + +**Promised** + +- The `.lint` case format documented below, and the discipline that a marker + naming a rule that no longer exists fails the suite — so a rule rename or + removal must take its markers with it (rule names are stable API; this is + the enforcement on the test side). +- Every rule keeps violating/clean/waived/unused-waiver coverage in the new + format; both fixable rules keep fix round-trips. + +## The .lint case format + +Files live in `crates/vlog_linter/tests/cases/*.lint`, one per rule (plus +`waivers.lint`, `class_bodies.lint`, `mixed.lint`). The framing is the house +`.cases` pattern: cases separated by `====` lines, `#` header lines naming +the case. Four headers are special: + +``` +#SKIP known-bad case: must still fail; passing demands the marker's removal +#path rtl/foo.sv lint the source as if read from this path (module-filename, wire-reg-mixup) +#select a,b vfmt check --select semantics: replaces the default rule set +#tolerant fix case whose input the formatter refuses; must be true (see below) +``` + +The body is Verilog source, linted verbatim. A violation expectation is a +marker line after the offending line: + +``` +module m; + wire a; +//^ 1 no-tabs +endmodule +``` + +`//^ ` asserts one finding of that rule at that 1-based +column on the nearest preceding non-marker line; markers stack for several +findings on one line. **`//^` is reserved throughout a `.lint` file** — any +trimmed line starting with it is parsed as a marker (block comments +included), and a malformed one fails the file loudly rather than passing +as content (QA finding 2, lead-documented). Likewise a `#word` header with +no space after the `#` must be a known directive (`#path`, `#select`, +`#tolerant`, `#SKIP`) or the file errors — a case *name* needs a space +after the `#` (QA finding 1, lead-fixed with a self-policing test). The +match is exact in both directions — a marked finding that is not reported +fails, and a reported finding that is not marked fails — and the failure +names both: + +``` +no_tabs.lint:1 [wrong col]: findings do not match the markers + missing (marked, not reported): + 2:2 no-tabs + unexpected (reported, not marked): + 2:1 no-tabs — tab character; indent with spaces + source: + 1 | module m; + 2 | wire a; + 3 | //^ 2 no-tabs + 4 | endmodule +``` + +(That report is real, captured from the harness; the self-policing test +`a_wrong_column_fails_in_both_directions` pins its shape.) + +Case-file errors — distinct from case failures, because they mean the *test* +is wrong: a marker naming a rule that does not exist ("a renamed or removed +rule must take its markers with it"), a marker for a rule the case does not +enable ("add it to #select"), a marker with no column, a marker above all +code, an unknown `#select` name, a case with no source. + +### Fix cases + +A `----` line splits a case into `(input, expected fixed output)`: + +``` +# fix: a tab that is also trailing whitespace takes two rounds +module m; + wire a; +//^ 1 no-tabs +//^ 9 no-trailing-whitespace +endmodule +---- +module m; + wire a; +//^ 1 no-tabs +//^ 9 no-trailing-whitespace +endmodule +``` + +(`` above stands in for the invisible trailing tab byte the real case +file carries — trailing whitespace and tabs in `.lint` files are content.) + +The markers still describe the *input* (a fix case is a lint case too), and +marker lines pass through the fix untouched, so they appear verbatim in the +expected output. The harness then asserts three things: + +1. **The fixpoint equals the expected text** — Safe fixes applied in the + CLI's fix→re-lint loop (cap 10 rounds), diffed line by line on mismatch. +2. **Clean for the fixed rules** — no enabled rule still offers a Safe fix + on the output. +3. **The cross-tool guarantee** — `vlog_formatter::format_source` must + accept the fixed output and format it to a fixed point + (`format(format(out)) == format(out)`; the formatter's own runtime + verification also runs inside every `format_source` call). The exception + is a fix case whose **input** the formatter already refuses — the + tolerant population only the linter sees. Such a case must say so with + `#tolerant`, which skips the formatter checks; an unmarked refused input + is a case error, and a `#tolerant` marker on an input that formats + demands its own removal, exactly like `#SKIP`. Nothing in the population + is silent. + +All 5 shipped fix cases run the full check — every fix input and every fixed +output is formatter-accepted and converges (proven by the `#tolerant` +discipline itself: a silently-skipped case is impossible). + +### The harness polices itself + +`tests/lint_cases.rs` carries 12 self-policing tests that feed the runner +deliberately wrong scratch cases and pin the failure reports: wrong column +(both directions named), unmarked finding, stale marker (dead rule), marker +for an unselected rule, marker without a column, marker above all code, +unknown `#select`, wrong fixed output (line diff shown), a passing `#SKIP` +case, a refused fix input without `#tolerant`, a `#tolerant` marker on a +formattable input, and one correct case that must pass. + +## Status / TODO + +- [x] `.lint` format: `====`/`#`/`//^ `/`----`, `#path`, + `#select`, `#SKIP`, `#tolerant`. +- [x] Exact two-direction matching with the readable report above. +- [x] Stale-marker detection (dead rule = case error), unselected-rule + markers, marker syntax errors. +- [x] Fix cases: CLI fix loop, clean-for-fixed-rules, cross-tool formatter + guarantee with the explicit `#tolerant` population. +- [x] One-parse property (`ParsedSource` products == source) asserted over + every case, absorbed from the old `assert_lint_with`. +- [x] Migration: all 55 `tests/rules.rs` tests → 76 `.lint` cases; + `rules.rs` deleted. Every rule has violating/clean/waived/ + unused-waiver coverage in the new format; both fixable rules have fix + round-trips (5 fix cases). +- [x] 12 self-policing tests. +- [x] TODO §5: both harness items checked. +- [ ] `#unsafe-fixes` header — waits for the first rule with an Unsafe fix. +- [ ] Component-level tests, error-case tests, fuzzing — the *other* §5 + items, untouched here. + +## Migration stats, honestly + +| | before | after | +|---|---|---| +| `vlog_linter` integration test fns | 55 (`tests/rules.rs`) | 13 (1 table + 12 self-policing) | +| data-driven cases | 0 | 76 (5 of them fix round-trips) | +| Rust test boilerplate LOC | 523 (`rules.rs`) | 547 (`lint_cases.rs`, the harness itself) | +| case data LOC | 0 (inline in Rust strings) | 501 (`cases/*.lint`, 14 files) | +| `cargo test -p vlog_linter` | 119 + 55 + 1 | 119 + 13 + 1 | +| `cargo test --workspace` | 827 | 785 | + +Read fairly: the Rust LOC did not shrink — it moved from per-rule repetition +(four near-identical functions per rule, escaped `\n\t` strings, no columns +checked) into a one-time harness that per-rule coverage no longer touches. +What each *case* costs went from ~8 lines of Rust with escapes to ~5 lines +of plain Verilog; what each case *checks* grew (columns now exact, both +directions, plus the one-parse property everywhere and the fix/cross-tool +checks on fix cases). The 42-test drop in the raw count is 55 functions +replaced by 13, while assertion coverage went up: the old suite checked 55 +(line, rule) shapes, the new one checks 76 cases × (line, col, rule) exact +in both directions. The 119 unit tests in `src/` (registry, waiver +derivation, fix-engine internals, naming predicates) are untouched — those +are API tests, not case tests, per the migration rule. + +## Work log + +### 2026-08-20 — dev + +- Read the Verible pattern (TODO §5), the house `.cases` harness + (`crates/vlog_formatter/tests/cases.rs`), and the existing + `tests/rules.rs` style before designing. Kept the `.cases` framing + (`====`, `#` headers, `#SKIP` discipline, collected failures, line + diffs) so there is one house pattern, not two. +- **Marker design decision**: `//^ ` with an explicit 1-based + column, not a positioned caret. Two reasons, both from "the formatter does + not run on these files": tabs in offending lines are content, so a + visually-aligned caret lies under any tab width; and a `//`-prefixed line + can never point at columns 1–2, where `no-tabs` — the highest-volume rule — + fires. The column is the one `vfmt check` prints, so writing a marker is + copying the diagnostic. +- **Columns were verified by the harness, not trusted**: all 76 cases' + hand-computed columns passed on the first full run (the one failure in + that run was a self-policing test's own assertion, fixed), which is also + the first live demonstration that the exact-match reports are usable — the + mismatch report in this README is captured from that run. +- **`#tolerant` discipline added mid-round**: the first cut silently skipped + the formatter checks when the input was refused, which made "the + cross-tool guarantee ran" unverifiable from a green suite. Now the + tolerant population is explicit, checked in both directions (`#SKIP` + semantics), and provably empty today: all 5 fix cases run the full + formatter check. +- One-parse property kept: the old `assert_lint_with` compared + source-parsed and product-parsed lint results on every test; `check_case` + does the same on every case. +- Migration: deleted `tests/rules.rs` (55 tests, 523 LOC) after porting all + of it — quartets for all 12 real rules and `unused-waiver`, waiver range + semantics, class-body reach (including the documented not-legal-SV + always-in-class walk-uniformity case, its caveat carried into the case + name), the mixed-file case, and the off-by-default `module-name-style` + select behavior. Nothing from `src/` unit tests was moved or deleted. +- New dev-dependency `vlog_formatter` (workspace crate, tests only) with the + justification comment in `Cargo.toml`; the library dependency list is + unchanged, which QA can re-verify with `cargo tree -p vlog_linter -e + normal`. +- **Gates**: `cargo test --workspace` 785 passed / 0 failed (baseline 827; + the delta is exactly −55 migrated + 13 new, accounted above); + `cargo test -p vlog_linter` 119 + 13 + 1; `cargo clippy --all-targets + --workspace` silent; `cargo fmt -p vlog_linter --check` clean (fmt scoped + because the tree carries other agents' uncommitted churn). Corpus + untouched — no `src/` change anywhere, so corpus numbers cannot have + moved. +- **TODO.md §5**: checked the inline-marker harness item and the + `RunApplyFixCases` item, with `→` notes pointing here. +- Scope kept: files touched are `crates/vlog_linter/tests/**`, + `crates/vlog_linter/Cargo.toml` (dev-dependencies only), this README, and + `TODO.md` — plus the mechanical one-line `Cargo.lock` consequence of the + dev-dependency (no external crate; the lock line names the workspace's own + `vlog_formatter`). + +## QA log + +### 2026-08-20 — QA + +Verdict: **pass**, no blocking findings. Every claim in the Work log and the +Migration-stats table reproduced. Four minor findings below, one of them a +real (low-severity) hole in header parsing. + +**Gates re-run from a clean tree** + +| gate | result | +|---|---| +| `cargo test --workspace` | 785 passed / 0 failed | +| `cargo test --workspace` at `HEAD` (54b0ca3, throwaway `git worktree`) | **827** passed / 0 failed — the claimed baseline, measured not assumed | +| `cargo test -p vlog_linter` | 119 (unit) + 13 (lint_cases) + 1 (doc) | +| `cargo clippy --all-targets --workspace` | silent | +| `cargo fmt --all --check` | clean (whole workspace, not just the crate) | +| determinism | two full `cargo test --workspace` runs, 785 test lines each, `diff` identical once timings are stripped | +| `cargo tree -p vlog_linter -e normal` | `vlog_parser` only; the dev-dep chain (`vlog_formatter → vlog_parser`) adds no external crate and no cycle (`vlog_formatter` does not depend on `vlog_linter`) | +| corpus | `git status` over the whole tree shows **no** `crates/*/src/**` change anywhere, so corpus numbers cannot have moved; `corpus/` and `tools/` untouched. (The TSV is generated on demand, not committed, so there is nothing to md5.) | + +Counts re-derived from the files, all matching the table: 76 cases across 14 +`.lint` files (`====` count + 1 per file), 5 fix cases (`----`), 501 LOC of +case data, 547 LOC of harness, 523 LOC in the deleted `rules.rs` with 55 +`#[test]` fns. + +**Claim 1 — markers carry `vfmt check`'s coordinates.** Verified by copying +five case bodies to disk and running the real CLI. Every marker column is the +diagnostic's column, verbatim: + +- `mixed.lint` as `rtl/top.sv` → `1:8 module-filename`, `1:24 + explicit-parameter-storage-type`, `4:1 no-tabs`, `4:14 + always-comb-blocking` — the four markers exactly. +- `no_trailing_whitespace.lint:1` → `2:10`; `class_bodies.lint` param case → + `1:21` and `3:14`; `no_tabs.lint` mid-line case → col `7`; + `waivers.lint` malformed-waiver case → `2:3 unused-waiver`. + +The copy-the-diagnostic property holds. The caret-rejection reasoning also +holds *empirically*, not just rhetorically — see the attacks below. + +**Claim 2 — fix cases.** The loop is CLI-equivalent: `crates/vfmt/src/lint.rs` +has `MAX_FIX_ROUNDS = 10` and the same fix→re-lint shape; the harness allows +rounds 0..=9 (10 applications, same as the CLI) and *errors* on an 11th +instead of silently stopping, which is the right strictness for a test. The +two documented divergences are both in Assumptions and both correct: no fence +filtering (`fixable_outside_fences` is the CLI's job) and `false` for +unsafe fixes (none exist). + +The two-round case was traced step by step (temporary scratch test, deleted): + +``` +round 0: findings=[2:1 no-tabs Safe, 2:9 no-trailing-whitespace Safe] applied=1 + -> "module m;\n wire a; \n…" +round 1: findings=[2:10 no-trailing-whitespace Safe] applied=1 + -> "module m;\n wire a;\n…" +round 2: findings=[] applied=0 +``` + +Exactly as documented: the two Safe fixes overlap on the trailing tab, so +round 0 lands only `no-tabs` (which expands *both* tabs on the line), and the +now-plain trailing run goes in round 1. The input markers `1` and `9` are the +input's true columns. + +`#tolerant` is provably empty — `grep '^#tolerant\|^#SKIP' tests/cases/` +returns nothing — and the cross-tool check is provably *reached* by all five +fix cases, not silently skipped. Proof by sabotage: replacing +`format_source(&fixed, …)` with a call on a formatter-refused literal made +**exactly 5 cases** fail with "accepts the input but refuses the fixed +output", naming all five fix cases. Reverted byte-identical (md5 +`9032f79cc6ab6ed834ff8ba5d62bc579`). + +**Claim 3 — self-policing is non-vacuous.** Not just read and run; broken on +purpose to check the tests actually catch anything. + +- `if want != got` → `if false`: `a_wrong_column_fails_in_both_directions`, + `an_unmarked_finding_is_unexpected` and + `a_skip_case_that_passes_demands_its_marker_removed` all went red at once. +- `(true, Ok(_)) => Err(…)` → `Ok(())`: + `a_tolerant_marker_on_a_formattable_input_demands_its_removal` went red. +- Both reverted and md5-verified back to `9032f79cc6ab6ed834ff8ba5d62bc579`. + +The **stale-marker promise was tested for real**, not only through the +scratch test: temporarily renaming `no_tabs.rs`'s `NAME` to `"no-hard-tabs"` +turned 13 cases red, 9 of them with +`marker names a rule that does not exist: 'no-tabs' — a renamed or removed +rule must take its markers with it`. Rule file reverted, md5 +`3b2dce6a1a0f3b64395f1ac4a0862697`, workspace back to 785 green. + +Sabotaging one *shipped* case instead of the harness (`no_tabs.lint`'s +mid-line marker `7` → `8`) produced the report the README advertises, naming +both directions — `missing 2:8 no-tabs` / `unexpected 2:7 no-tabs — tab +character; indent with spaces` — plus the numbered source. Reverted, md5 +verified. + +**Claim 4 — migration honesty.** `git diff HEAD -- crates/vlog_linter/src/` +is empty and `git status` lists no `src/` path: the 119 unit tests are +untouched. All 13 rules have the quartet — every rule has ≥1 violating +marker and ≥1 waiver-mention case, and each rule file carries an explicit +"quiet" case (`always_rules` 2, `case_missing_default` 2, `module_filename` +2, `no_tabs` 2, `wire_reg_mixup` 3, one each elsewhere; `unused-waiver`'s +"clean" cases are the two ignored/disabled-waiver cases in `waivers.lint`, +its "waived" case is *an unused waiver can itself be waived*). + +I mapped all 55 deleted test fns onto the new cases one by one. **Nothing +asserted before is unasserted now.** Sample of five, in detail: + +| deleted test | ported to | anything lost? | +|---|---|---| +| `module_filename_is_quiet_when_it_matches_or_has_no_path` (2 asserts) | `module_filename.lint` cases 2 and 3 | no — both split out | +| `no_tabs_is_waived` (2 asserts) | `no_tabs.lint` "waived on the same line" + "waived from the line above" | no | +| `wire_reg_mixup_is_quiet_on_logic_and_on_verilog_files` (3 asserts) | `wire_reg_mixup.lint` cases 2, 3, 4 | no | +| `a_rule_off_by_default_says_nothing_until_selected` (raw `run` + selecting) | `module_name_style.lint` cases 1 and 2 | no — the off-by-default half survives as the no-`#select` case | +| `the_always_rules_reach_a_class_body_too` (with its not-legal-SV caveat) | `class_bodies.lint` case 4, caveat carried into the case name | no | + +Coverage is strictly **up**, not merely preserved: 12 cases are new content +(`no_tabs` multi-tab / mid-line / string-literal, `case_missing_default`'s +`unique case`, and all 9 of `waivers.lint`), plus columns, both-direction +matching, and the fix/cross-tool checks. Note `waivers.lint` *duplicates* +`src/lib.rs`'s waiver unit tests at case level rather than replacing them — +those unit tests are still there, so this is additive. + +Small precision on the stats table (not corrected in place, since "55" there +also correctly names the test-function count): the old suite made **58** +assertion sites, not 55 — `grep` counts 60 `assert_lint*(` occurrences, two +of which are the helper bodies calling `assert_lint_with`. 58 old +`(line, rule)` shapes → 76 new `(line, col, rule)` cases. The argument holds +with the corrected number. + +**Claim 5 — the dev-dependency. My ruling: compliant, keep it.** +CLAUDE.md's rule is "standard library first; adding a dependency requires a +written justification in the feature README". Both the letter and the spirit +are met. The letter: the justification exists twice, in `Cargo.toml` and in +Handshakes. The spirit — the rule exists to police supply-chain surface, +build weight and the crate's public contract — is untouched: `vlog_formatter` +is a workspace-internal path crate, dev-only, pulling in zero external code +(`vlog_formatter → vlog_parser`, nothing else), with no cycle, and +`cargo tree -e normal` proves the library's contract is byte-for-byte what it +was. A workspace-internal dev-dep is a *test-wiring* decision, not a +dependency decision, and I do not think it should be held to the same bar as +an external runtime dep. The one alternative worth naming for the lead: +the cross-tool assertion could have lived in `crates/vfmt`, which already +depends on both — but that would have split the case format across two +crates to avoid a dependency that costs nothing. The dev chose correctly. + +**Claim 6 — gates.** All in the table above. + +### Findings + +1. *(minor, real)* **A typo'd or unknown `#` header is silently absorbed into + the case name instead of being rejected.** `split_case` + (`tests/lint_cases.rs:100-116`) recognizes `#path `, `#select `, + `#tolerant`, `#SKIP`; everything else becomes name text. Reproduced: a + scratch case headed `#patth rtl/m.v` over `module m;\n reg q;\nendmodule` + passes green — but for the wrong reason (no path at all, rather than a + `.v` path), silently weakening exactly the property + `wire_reg_mixup.lint` case 3 exists to pin. `#unsafe-fixes` and + `#tolerantt` are likewise accepted in silence. Most typo directions fail + loudly (a lost `#SKIP`/`#tolerant`/`#select` makes the case go red), so + this is not a false-green risk in the shipped set — I re-verified all 14 + files pass with their real headers. It is a maintenance hazard and it + contradicts the feature's own "nothing in the population is silent" + stance. Cheap discriminator, if the lead wants it fixed: every real + directive is written with no space after `#` and every case name with one, + so `#word` with no following space could be required to be a known + directive. Flagged, not implemented — that is a format decision, not a + QA typo fix. +2. *(minor, documentation)* **`//^` is reserved and the format spec does not + say so.** Any line whose *trimmed* text starts with `//^` is consumed as a + marker and can never be case content — including one inside a `/* */` + block (the harness is line-based, not lexical). Both attacks fail loudly + (`//^ decorative banner` → "`decorative` is not a column number"; the + block-comment one → "missing (marked, not reported)"), so nothing is + silently mis-attributed, but the README's "The .lint case format" section + should state the exclusivity in one line. +3. *(minor, documentation)* **`.lint` files are CRLF-transparent, which means + `\r` can never reach the linter.** A CRLF-encoded case file parses and + passes (verified), because `str::lines()` strips the `\r` before `join()` + rebuilds the source with `\n`. Consequence worth recording in Assumptions: + CRLF behaviour of the text rules (e.g. that `\r` is *not* trailing + whitespace, per `trim_end_matches([' ', '\t'])`) is not expressible as a + case. Not a regression — `rules.rs` could not express it either. +4. *(cosmetic)* Two asymmetries in header enforcement, so the Handshakes + wording is not over-read: `#SKIP` and `#tolerant` are enforced in both + directions (verified), but `#select` only rejects unknown names and + markers for unselected rules — an over-broad `#select` is silent — and + `#path` has no enforcement at all. `class_bodies.lint` case 3's + `#path rtl/m.sv` is in fact inert (no `reg`, and `m` matches `m.sv`); it + is there for realism, which is fine, but nothing would catch it going + stale. Also `#SKIP` is matched with `starts_with("SKIP")`, so a case + *named* "SKIPping blank lines" would be treated as skipped. + +Two latent notes, neither reachable today: `diff()` is `.lines()`-based, so a +fixpoint that differed from the expected text *only* in its trailing newline +would be reported with an empty diff body — unreachable because `join()` +normalizes both sides and no fix deletes a line terminator (an expected +output with an extra blank line *is* caught, rendering as a bare `-` line, +verified). And `split_case`'s header loop would eat a case whose first source +line begins with an unindented `#` (a bare delay statement) — no realistic +case starts that way. + +### Adversarial cases written and run (all deleted; tree restored) + +Six expressibility attacks in a scratch `tests/cases/qa_attack.lint`, **all +passing**, which is the real vindication of the explicit-column marker over a +positioned caret: + +- `no-tabs` at **column 1** and at **column 2** (` \twire a;`) — the zone a + `//`-prefixed caret line provably cannot reach. +- `no-trailing-whitespace` at **column 1** (a whitespace-only line). +- Two findings on one line at different columns (`8` + `24`). +- The same two markers written in **reverse order** — the harness sorts both + sides, so ordering is irrelevant and unsorted findings cannot fool it. +- **Two different rules at the identical `line:col`** (a tab-only line fires + `no-tabs` *and* `no-trailing-whitespace` at 2:1). Both matched. + +Four failure attacks, all failing loudly with the advertised report: a marker +for a **waived** finding (classified `missing (marked, not reported)` — the +marker is the side with no counterpart, which reads correctly); a **duplicate +marker** with one finding (multiset semantics survive the sort); a +non-marker `//^` comment; a `//^` inside a block comment. Plus the CRLF file, +the trailing-blank-line fix case, and the three typo'd-header cases described +in the findings. + +Everything created during QA was removed and verified: `qa_attack.lint` and +the scratch test file deleted, `no_tabs.lint`, `lint_cases.rs` and +`src/rules/no_tabs.rs` restored byte-identical by md5, the baseline +`git worktree` removed, `git status` back to the dev's exact working set, and +`cargo test --workspace` green at 785. + +## Review + +**2026-08-20 — lead. Verdict: accepted and committed. The owner's final +sequence item lands: writing a lint rule's tests is now copying vfmt's +own diagnostics into a data file, and the harness polices itself.** + +Points reviewed and accepted: + +1. **Copy-the-diagnostic markers over positioned carets** — the tab + argument is exactly right (a visual caret lies where tabs are + content, and can't reach columns 1-2 where no-tabs lives), and QA + vindicated it by expressing markers at both caret-impossible + columns and at identical positions for two rules. +2. **The cross-tool guarantee on fix cases** (fixed output must be + lint-clean AND formatter-convergent) is the harness's real value: + QA's sabotage of the format_source call turned exactly 5 cases red, + proving all fix cases reach it. The `#tolerant` escape being empty + today but two-way enforced is the #SKIP discipline applied forward. +3. **Migration with a coverage audit, not a coverage claim**: all 55 + deleted functions mapped individually onto cases, coverage strictly + up (58 old line-rule shapes → 76 line+col+rule cases; QA's + corrected 58 stands alongside the dev's correct 55-function count), + 119 src unit tests untouched. +4. **The dev-dependency ruling adopted**: a workspace-internal, + test-only path dependency moves neither supply-chain surface nor + the library contract (cargo tree -e normal unchanged); the + alternative — splitting the case format across crates to dodge a + free dependency — would have been worse. QA's independent ruling + concurred. +5. **Lead fixes on acceptance**: QA finding 1 (typo'd `#word` headers + silently becoming case names) fixed with the offered discriminator + plus a self-policing test; finding 2 (`//^` reserved) now stated in + the format spec. Findings 3-4 (CRLF transparency, the #select/#path + enforcement asymmetries) stand as recorded, with the `#SKIP` + starts_with quirk inherited knowingly from the .cases precedent. + +With this, the owner's 2-3-4-5-7 sequence is complete.