//! 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 `lucisv 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, `lucisv 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"); }