From 050634b6ad44ddefe938b4e636cc9f925bbc5b2d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:19:05 -0800 Subject: [PATCH] xtask: test-lint skips declared-only items and unapplied should_panic - Functions and macros declared inside a test no longer count as its assertions or calls; a call to one still counts as a helper call. - `should_panic` exempts a test only as an applied attribute: `#[should_panic]`, or inside `#[cfg_attr(test, ...)]`. - `only-weak` strips parentheses around the whole condition, so `assert!((x.is_ok()))` is classified like `assert!(x.is_ok())`. - `#[ cfg(test)]` and attributes with comments between `#`, `[` and `cfg` mark test code like the compact form. --- xtask/src/test_lint.rs | 114 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 104 insertions(+), 10 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index bfa4f4728c..8609ace2f5 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1009,7 +1009,9 @@ fn test_regions(path: &str, m: &[u8], tests: &[TestFn]) -> Vec<(usize, usize)> { let mut out: Vec<(usize, usize)> = tests.iter().map(|t| (t.attr, t.close)).collect(); for at in words(m, b"cfg", 0, m.len()) { let open = skip_ws(m, at + "cfg".len()); - if !m[..at].ends_with(b"#[") || m.get(open) != Some(&b'(') { + // Whitespace and comments (masked to spaces) may separate `#`, `[` and `cfg`. + let outer_attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + if !outer_attr || m.get(open) != Some(&b'(') { continue; } let Some(close) = matching(m, open) else { continue }; @@ -1079,8 +1081,8 @@ fn checking<'a>(defs: impl Iterator + Clone) -> HashSet } } -/// The `fn` or `macro_rules!` at `at`. -fn definition(m: &[u8], at: usize) -> Option { +/// The name, kind (`true` for a macro) and body braces of the `fn` or `macro_rules!` at `at`. +fn item_at(m: &[u8], at: usize) -> Option<(&[u8], bool, usize, usize)> { let is_macro = m[at..].starts_with(b"macro_rules"); let mut start = skip_ws(m, at + if is_macro { "macro_rules".len() } else { 2 }); if is_macro { @@ -1094,8 +1096,13 @@ fn definition(m: &[u8], at: usize) -> Option { if m[open] != b'{' { return None; } - let close = matching(m, open)?; - let name = String::from_utf8_lossy(&m[start..end]).into_owned(); + Some((&m[start..end], is_macro, open, matching(m, open)?)) +} + +/// The `fn` or `macro_rules!` at `at`. +fn definition(m: &[u8], at: usize) -> Option { + let (name, is_macro, open, close) = item_at(m, at)?; + let name = String::from_utf8_lossy(name).into_owned(); let called = calls(m, open, close).into_iter().filter(|(_, method)| !method).map(|(n, _)| n).collect(); Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) } @@ -1107,6 +1114,9 @@ struct File<'a> { path: &'a str, src: &'a [u8], m: Vec, + /// [`File::m`] with the functions and macros declared inside each test blanked: declaring + /// one does not run its body ([`executed`]). + exec: Vec, lines: Lines, tests: Vec, /// The test code ([`test_regions`]). @@ -1148,7 +1158,8 @@ pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { let m = mask(src); let tests = tests_in(&m); let regions = test_regions(path, &m, &tests); - let file = File { path, src: src.as_bytes(), m, lines: Lines::new(src), tests, regions }; + let exec = executed(&m, &tests); + let file = File { path, src: src.as_bytes(), m, exec, lines: Lines::new(src), tests, regions }; let mut hits: Vec = file.tests.iter().flat_map(|t| test_hits(&file, t, ctx)).collect(); hits.extend(ignore_hits(&file)); hits.extend(sleep_hits(&file)); @@ -1162,6 +1173,20 @@ pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { hits } +/// `m` with each `fn` and `macro_rules!` declared inside a test's body replaced by spaces, from +/// its keyword to its closing brace. A call to one stays, so it can still count as a helper call. +fn executed(m: &[u8], tests: &[TestFn]) -> Vec { + let mut out = m.to_vec(); + for t in tests { + for at in words(m, b"fn", t.open, t.close).into_iter().chain(words(m, b"macro_rules", t.open, t.close)) { + if let Some((_, _, _, close)) = item_at(m, at).filter(|&(_, _, _, close)| close < t.close) { + blank(&mut out, at, close + 1); + } + } + } + out +} + /// `(line, rule)` of each exemption comment that names a rule and a reason. /// A marker counts only inside a comment: masked (`m`) there, and kept when only literals are /// masked. @@ -1191,7 +1216,7 @@ struct View<'a> { } fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { - let m = &file.m; + let m = &file.exec; let asserts: Vec = macro_calls(m, t.open, t.close).into_iter().filter(|c| is_assert_macro(&c.name)).collect(); let none = HashSet::new(); let helpers = ctx.helpers.get(&crate_of(file.path)).unwrap_or(&none); @@ -1199,7 +1224,7 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { .iter() .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)); let checks = checks_itself(m, t.open, t.close); - let should_panic = contains(&m[t.attr..t.fn_at], b"should_panic"); + let should_panic = should_panic_attr(m, t.attr, t.fn_at); let v = View { file, t, asserts, delegates, checks, should_panic }; let mut hits = all_unguarded(&v); hits.extend(self_compare(&v)); @@ -1209,6 +1234,27 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { hits } +/// Whether the attributes in `m[from..to]` include an applied `should_panic`: `#[should_panic]`, +/// `#[should_panic(…)]`, or one inside `#[cfg_attr(test, …)]`. Another `cfg_attr` predicate may +/// not hold, so it does not count. +fn should_panic_attr(m: &[u8], from: usize, to: usize) -> bool { + let attached = words(m, b"should_panic", from, to).into_iter().any(|at| { + let before = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + before && matches!(m.get(skip_ws(m, at + "should_panic".len())), Some(b']' | b'(')) + }); + attached + || words(m, b"cfg_attr", from, to).into_iter().any(|at| { + let open = skip_ws(m, at + "cfg_attr".len()); + let Some(close) = matching(m, open).filter(|&c| m[open] == b'(' && c < to) else { return false }; + let args = split_args(m, open + 1, close); + let name = |&(f, t): &(usize, usize)| { + let a = norm(&m[f..t]); + a == "should_panic" || a.starts_with("should_panic(") + }; + args.first().is_some_and(|&(f, t)| norm(&m[f..t]) == "test") && args.iter().skip(1).any(name) + }) +} + impl View<'_> { fn hit(&self, at: usize, rule: Rule, note: String) -> Hit { self.file.hit(at, rule, &self.t.name, note) @@ -1223,7 +1269,7 @@ impl View<'_> { } fn body(&self) -> &[u8] { - &self.file.m[self.t.open..self.t.close] + &self.file.exec[self.t.open..self.t.close] } /// The masked body with assertion failure-message arguments replaced by spaces. @@ -2149,8 +2195,9 @@ fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> /// Whether an assertion's (masked, whitespace-free) condition only says that there is a value. fn is_weak(cond: &str) -> bool { + let cond = unparenthesized(cond); let (negated, expr) = match cond.strip_prefix('!') { - Some(rest) => (true, rest), + Some(rest) => (true, unparenthesized(rest)), None => (false, cond), }; let plain = |rest: &str| !["&&", "||", "==", "!=", "<", ">"].iter().any(|op| rest.contains(op)); @@ -2161,6 +2208,14 @@ fn is_weak(cond: &str) -> bool { suffix(".is_ok()") || suffix(".is_some()") || suffix(".len()>0") || suffix(".len()!=0") || suffix(".len()>=1") } +/// `expr` without the balanced parentheses around all of it (`((a.is_ok()))` gives `a.is_ok()`). +fn unparenthesized(mut expr: &str) -> &str { + while expr.starts_with('(') && matching(expr.as_bytes(), 0) == Some(expr.len() - 1) { + expr = &expr[1..expr.len() - 1]; + } + expr +} + fn only_weak(v: &View) -> Option { let all_weak = v.asserts.iter().all(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && is_weak(&v.first_arg(a))); // Failure messages run only after an assertion has failed, so a check there does not count. @@ -3223,6 +3278,41 @@ mod tests { assert_eq!(hits(refusal), [], "is_err is not on the plan's list"); let compound = "#[test]\nfn t() {\n assert!(a.is_some() && a == Some(2));\n}\n"; assert_eq!(hits(compound), []); + for cond in ["(parse(\"x\").is_ok())", "((parse(\"x\").is_ok()))", "!(list().is_empty())", "(!list().is_empty())"] { + let src = format!("#[test]\nfn t() {{\n assert!({cond});\n}}\n"); + assert_eq!(hits(&src), [(2, "only-weak")], "{cond}"); + } + let grouped = "#[test]\nfn t() {\n assert!((a.is_some()) && (a == Some(2)));\n}\n"; + assert_eq!(hits(grouped), [], "parentheses around one side of a comparison stay"); + } + + #[test] + fn functions_declared_in_a_test_count_only_when_called() { + let unused = "#[test]\nfn t() {\n fn unused() {\n assert_eq!(1, 1);\n }\n assert!(parse(\"x\").is_ok());\n}\n"; + assert_eq!(hits(unused), [(2, "only-weak")], "a declared function's assertion does not run"); + let macro_only = "#[test]\nfn t() {\n macro_rules! check {\n () => { assert_eq!(1, 1) };\n }\n f();\n}\n"; + assert_eq!(hits(macro_only), [(2, "no-assertion")], "a declared macro's assertion does not run"); + let called = unused.replace(" assert!(parse", " unused();\n assert!(parse"); + let files = [("crates/x/src/tests.rs".to_owned(), called.clone())]; + let with_helpers = Ctx { helpers: asserting_helpers(&files), ..ctx() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &called, &with_helpers), [], "a call to it checks"); + } + + #[test] + fn should_panic_counts_only_when_applied() { + let weak = "#[test]\nfn t() {\n assert!(parse(\"x\").is_ok());\n}\n"; + for attr in [ + "#[should_panic]", + "#[ should_panic(expected = \"x\") ]", + "#[cfg_attr(test, should_panic)]", + "#[cfg_attr( test , should_panic(expected = \"x\"))]", + ] { + assert_eq!(hits(&format!("{attr}\n{weak}")), [], "{attr}"); + } + for attr in ["#[cfg_attr(any(), should_panic)]", "#[cfg_attr(windows, should_panic)]", "#[doc = \"should_panic\"]", "#[allow(should_panic)]"] + { + assert_eq!(hits(&format!("{attr}\n{weak}")), [(3, "only-weak")], "{attr}"); + } } #[test] @@ -3554,6 +3644,10 @@ mod tests { let gated = format!("#[cfg({gate})]\nmod tests {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [(3, "sleep")], "{gate} holds only in tests"); } + for attr in ["#[ cfg(all(test, unix))]", "#[/* test-only */cfg(test)]", "# [cfg (test)]"] { + let gated = format!("{attr}\nmod tests {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); + assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [(3, "sleep")], "{attr}"); + } for gate in ["any(test, feature = \"x\")", "not(test)", "all(unix, not(test))", "feature = \"test\""] { let gated = format!("#[cfg({gate})]\nmod helpers {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [], "{gate} also holds outside tests");