From 0bdbb241520d83839cbfb97fe3961d835b29a314 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:46:07 -0800 Subject: [PATCH 01/11] CI: run vectorcraft-engine's integration tests on shard 4 In each of the last 20 successful pull request runs the slowest shard was a ui-egui part or shard 3 (8 of the 20), which built and ran every vectorcraft-engine test, while shard 4 finished in about half the time. Shard 4 already builds the engine library for the app crates, so it now runs the engine's 936 integration tests (`--test '*'`), and shard 3 keeps the 9,471 library tests and the doctests. `Group::Targets` gives a shard a list of crates per test-target selection, and each list is its own cargo command, with its feature check and its `ci warm` build. A crate either runs every target on one shard, or its library and binary tests on one shard and its integration tests on another. shard-members in ci.yml is unchanged: shard 4 runs whenever the engine is selected, because the app crates on its line depend on it, and a test checks that dependency. --- xtask/src/main.rs | 114 ++++++++++--------- xtask/src/shards.rs | 266 +++++++++++++++++++++++++++++++++++++------- 2 files changed, 285 insertions(+), 95 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 1c9af7db00..3ada901300 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -271,23 +271,21 @@ fn has_nextest() -> bool { /// The workspace's unit and integration tests, without examples (clippy still checks those). /// nextest runs each test in its own process, in parallel across all test binaries. fn cmd_test() -> Result<(), String> { - test_packages(&["--workspace".to_owned()], "--workspace", None) + test_packages(&["--workspace".to_owned()], "--workspace", shards::Targets::All, None) } -/// The test targets that [`test_packages`] runs and `ci warm` builds. -const TARGETS: [&str; 3] = ["--lib", "--bins", "--tests"]; - -/// [`cmd_test`] for the packages `select` picks (`--workspace` or `-p` ids), shown as `shown`; -/// with `part`, only that part's share of their tests (xtask/src/shards.rs), which needs nextest. -/// A part runs its counted share, then its pinned tests, each with nextest's default thread count. -/// Every run finishes before the first error is returned. -fn test_packages(select: &[String], shown: &str, part: Option) -> Result<(), String> { +/// [`cmd_test`] for the `targets` of the packages `select` picks (`--workspace` or `-p` ids), +/// shown as `shown`; with `part`, only that part's share of their tests (xtask/src/shards.rs), +/// which needs nextest. A part runs its counted share, then its pinned tests, each with +/// nextest's default thread count. Every run finishes before the first error is returned. +fn test_packages(select: &[String], shown: &str, targets: shards::Targets, part: Option) -> Result<(), String> { + let (listed, targets) = (targets.shown(), targets.args()); if let Some(part) = part { if !has_nextest() { return Err(format!("cargo nextest run {shown}: a shard that runs part of a crate's tests needs cargo-nextest")); } let mut c = cargo(); - c.args(["nextest", "list", "--color", "never", "--message-format", "json"]).args(select).args(TARGETS); + c.args(["nextest", "list", "--color", "never", "--message-format", "json"]).args(select).args(targets); let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("cargo nextest list {shown}: failed to spawn: {e}"))?; if !out.status.success() { return Err(format!("cargo nextest list {shown}: exited with {}", out.status)); @@ -301,9 +299,9 @@ fn test_packages(select: &[String], shown: &str, part: Option) -> } let command = |args: Vec| { let mut c = cargo(); - c.args(["nextest", "run"]).args(select).args(TARGETS).args(&args); + c.args(["nextest", "run"]).args(select).args(targets).args(&args); let quoted = args.iter().map(|a| if a.contains(' ') { format!("'{a}'") } else { a.clone() }).collect::>().join(" "); - (c, format!("cargo nextest run {shown} --lib --bins --tests {quoted}")) + (c, format!("cargo nextest run {shown} {listed} {quoted}")) }; let mut result = Ok(()); for args in part.runs() { @@ -314,12 +312,12 @@ fn test_packages(select: &[String], shown: &str, part: Option) -> } let mut c = cargo(); if has_nextest() { - c.args(["nextest", "run"]).args(select).args(TARGETS); - run(c, &format!("cargo nextest run {shown} --lib --bins --tests")) + c.args(["nextest", "run"]).args(select).args(targets); + run(c, &format!("cargo nextest run {shown} {listed}")) } else { eprintln!("note: cargo-nextest is not installed; running cargo test (cargo install cargo-nextest for faster runs)"); - c.arg("test").args(select).args(TARGETS); - run(c, &format!("cargo test {shown} --lib --bins --tests")) + c.arg("test").args(select).args(targets); + run(c, &format!("cargo test {shown} {listed}")) } } @@ -375,22 +373,33 @@ fn cmd_ci_shard() -> Result<(), String> { let checked = shards::run()?; let mut steps: Vec = Vec::new(); match &checked[shard - 1] { - shards::Shard::Tests(crates, part) => { - let names = shards::names(crates); + shards::Shard::Tests(runs, part) => { let share = part.map(|p| format!(" (part {} of {})", p.index, p.split.parts())).unwrap_or_default(); - eprintln!("ci shard {shard}/{count}: the tests of {names}{share}"); - let select = shards::select(crates); - let shown = crates.iter().map(|m| format!("-p {}", m.name)).collect::>().join(" "); + eprintln!("ci shard {shard}/{count}: the tests of {}{share}", shards::describe(runs)); + let shown = |crates: &[shards::Member]| crates.iter().map(|m| format!("-p {}", m.name)).collect::>().join(" "); let part = *part; - let (s, w) = (select.clone(), shown.clone()); - steps.push(("test", Box::new(move || test_packages(&s, &w, part)))); + let tests: Vec<(Vec, String, shards::Targets)> = + runs.iter().map(|r| (shards::select(&r.crates), shown(&r.crates), r.targets)).collect(); + // Each run finishes before the first error is returned. + steps.push(( + "test", + Box::new(move || { + let mut result = Ok(()); + for (s, w, t) in &tests { + result = result.and(test_packages(s, w, *t, part)); + } + result + }), + )); // The doctests and the i18n report run once, on a split's first part. let first = part.is_none_or(|p| p.is_first()); if first { - let c = crates.clone(); + let c = shards::unit_crates(runs); steps.push(("doctests", Box::new(move || doctest_packages(&c)))); } - if first && crates.iter().any(|m| m.name == "vectorcraft-ui-egui") { + let all = runs.iter().find(|r| r.targets == shards::Targets::All && r.crates.iter().any(|m| m.name == "vectorcraft-ui-egui")); + if let Some(r) = all.filter(|_| first) { + let (select, shown) = (shards::select(&r.crates), shown(&r.crates)); steps.push(("i18n-report", Box::new(move || i18n_report_packages(&select, &shown)))); } } @@ -402,13 +411,11 @@ fn cmd_ci_shard() -> Result<(), String> { run_steps(&steps) } -/// `cargo xtask ci warm`: for each test shard, builds its crates' library, binary and integration -/// tests without running them, then builds what the checks shard builds, so one dependency-cache -/// entry holds the dependencies of every shard with the features that shard builds them with (cargo -/// resolves features over the packages each command selects). The test builds select the same -/// targets as the test shards ([`TARGETS`]), so the cache also holds the test executables the -/// shards run, and cargo does not warn (`cargo::unused_dependencies`) about a dev-dependency that -/// only an integration test uses. +/// `cargo xtask ci warm`: for each run of each test shard, builds the test targets it runs without +/// running them, then builds what the checks shard builds, so one dependency-cache entry holds the +/// dependencies of every shard with the features that shard builds them with (cargo resolves +/// features over the packages each command selects). The test builds select the same crates and +/// targets as the test shards' runs, so the cache also holds the test executables the shards run. /// /// In a leg that saves the cache, every build records its units in `CRAFT_CACHE_UNITS` /// (xtask/src/cache_units.rs), xtask's own build included. @@ -418,17 +425,19 @@ fn cmd_ci_warm() -> Result<(), String> { let mut steps: Vec = Vec::new(); for shard in checked { // A split's later parts build the same tests as its first. - if let shards::Shard::Tests(crates, part) = shard { + if let shards::Shard::Tests(runs, part) = shard { if part.is_some_and(|p| !p.is_first()) { continue; } - steps.push(( - "build tests", - Box::new(move || { - let (c, what) = warm_tests(&crates); - cache_units::run(c, &what) - }), - )); + for r in runs { + steps.push(( + "build tests", + Box::new(move || { + let (c, what) = warm_tests(&r); + cache_units::run(c, &what) + }), + )); + } } } steps.push(( @@ -457,11 +466,11 @@ fn cmd_ci_warm() -> Result<(), String> { run_steps(&steps) } -/// The command `ci warm` builds one test shard's tests with, and its description. -fn warm_tests(crates: &[shards::Member]) -> (Command, String) { +/// The command `ci warm` builds the tests of one run of a test shard with, and its description. +fn warm_tests(r: &shards::Run) -> (Command, String) { let mut c = cargo(); - c.arg("test").args(shards::select(crates)).args(TARGETS).arg("--no-run"); - (c, format!("cargo test {} --no-run ({})", TARGETS.join(" "), shards::names(crates))) + c.arg("test").args(shards::select(&r.crates)).args(r.targets.args()).arg("--no-run"); + (c, format!("cargo test {} --no-run ({})", r.targets.shown(), shards::names(&r.crates))) } /// Runs `steps` in turn, stopping at the first that fails; the summary names the steps that passed @@ -613,13 +622,14 @@ mod tests { #[test] fn warm_builds_the_test_targets_the_shards_run() { - let crates = [shards::Member { name: "a".into(), id: "path+file:///w/a#0.1.0".into(), version: "0.1.0".into(), doctests: true }]; - let (c, what) = warm_tests(&crates); - let args: Vec = c.get_args().map(|a| a.to_string_lossy().into_owned()).collect(); - assert_eq!(args, ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--tests", "--no-run"]); - for target in TARGETS { - assert!(args.iter().any(|a| a == target), "ci warm does not build {target}"); - } - assert_eq!(what, "cargo test --lib --bins --tests --no-run (a)"); + let a = shards::Member { name: "a".into(), id: "path+file:///w/a#0.1.0".into(), version: "0.1.0".into(), doctests: true }; + let args = |r: &shards::Run| warm_tests(r).0.get_args().map(|a| a.to_string_lossy().into_owned()).collect::>(); + let all = shards::Run::all(vec![a.clone()]); + assert_eq!(args(&all), ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--tests", "--no-run"]); + assert_eq!(warm_tests(&all).1, "cargo test --lib --bins --tests --no-run (a)"); + let units = shards::Run { targets: shards::Targets::Units, crates: vec![a.clone()] }; + assert_eq!(args(&units), ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--no-run"]); + let integration = shards::Run { targets: shards::Targets::Integration, crates: vec![a] }; + assert_eq!(args(&integration), ["test", "-p", "path+file:///w/a#0.1.0", "--test", "*", "--no-run"]); } } diff --git a/xtask/src/shards.rs b/xtask/src/shards.rs index 261a27191e..072e55f280 100644 --- a/xtask/src/shards.rs +++ b/xtask/src/shards.rs @@ -17,6 +17,11 @@ //! with the pinned tests filtered out, so each of them runs once). The doctests and the i18n //! report run on part 1. A part runs its counted share and then its pinned tests, each with //! nextest's default thread count, and runs both even when the first fails. +//! +//! A [`Group::Targets`] shard can run a crate's library and binary tests ([`Targets::Units`]) while +//! another shard runs its integration tests ([`Targets::Integration`]), so a shard that already +//! builds that crate's library takes those tests without building the library's test harness. Each +//! list of a shard is its own cargo command, and its doctests run with its library tests. use std::collections::{BTreeMap, BTreeSet}; @@ -25,16 +30,49 @@ use serde_json::Value; /// What one shard runs. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Group { - /// The tests of these workspace crates (package names). - Crates(&'static [&'static str]), /// Part `k` (1-based) of a split's tests. Parts 1 to n of a split are consecutive shards. Part(&'static Split, usize), + /// The given test targets of each list of workspace crates (package names). A crate whose + /// [`Targets::Units`] run on one shard has its [`Targets::Integration`] run on another. + Targets(&'static [(Targets, &'static [&'static str])]), /// The tests of every workspace member no other group names. Rest, /// The `cargo xtask ci` steps that are not tests. Checks, } +/// The test targets a shard builds and runs for a crate. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Targets { + /// The library, binary and integration tests. + All, + /// The library and binary tests. + Units, + /// The integration tests (`tests/`). + Integration, +} + +impl Targets { + /// The target selection `cargo test` and `cargo nextest run` take. + pub fn args(self) -> &'static [&'static str] { + match self { + Targets::All => &["--lib", "--bins", "--tests"], + Targets::Units => &["--lib", "--bins"], + // `--tests` would also take the library's and binaries' test harnesses (every target with `test = true`). + Targets::Integration => &["--test", "*"], + } + } + + /// [`Targets::args`] as a shell would take them, for messages. + pub fn shown(self) -> &'static str { + match self { + Targets::All => "--lib --bins --tests", + Targets::Units => "--lib --bins", + Targets::Integration => "--test '*'", + } + } +} + /// Crates whose tests run on several shards, one [`Group::Part`] each. #[derive(Debug, PartialEq, Eq)] pub struct Split { @@ -71,12 +109,16 @@ pub static UI_EGUI: Split = Split { }; /// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length, and its -/// `shard-members` names each shard's crates. +/// `shard-members` names each shard's crates. vectorcraft-engine's integration tests run on +/// shard 4, which already builds the engine library for the app crates. pub const GROUPS: &[Group] = &[ Group::Part(&UI_EGUI, 1), Group::Part(&UI_EGUI, 2), - Group::Crates(&["vectorcraft-engine"]), - Group::Crates(&["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"]), + Group::Targets(&[(Targets::Units, &["vectorcraft-engine"])]), + Group::Targets(&[ + (Targets::All, &["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"]), + (Targets::Integration, &["vectorcraft-engine"]), + ]), Group::Rest, Group::Checks, ]; @@ -98,10 +140,29 @@ pub struct Member { /// What one shard runs, with its crates resolved; a shard of a [`Split`] carries its part. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Shard { - Tests(Vec, Option), + Tests(Vec, Option), Checks, } +/// One test run of a shard: the given targets of these crates. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Run { + pub targets: Targets, + pub crates: Vec, +} + +impl Run { + /// A run of every test target of `crates`. + pub fn all(crates: Vec) -> Run { + Run { targets: Targets::All, crates } + } +} + +/// The crates of `runs` whose library is tested there, which run their doctests on that shard. +pub fn unit_crates(runs: &[Run]) -> Vec { + runs.iter().filter(|r| r.targets != Targets::Integration).flat_map(|r| r.crates.iter().cloned()).collect() +} + /// Part `index` (1-based) of `split`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Part { @@ -192,14 +253,15 @@ pub fn with_doctests(crates: &[Member]) -> Vec { } /// Each group of `groups` with its crates: a named crate must be a workspace member and named -/// once, there must be exactly one [`Group::Rest`], and no test shard may be empty. A split's -/// parts 1 to n must be consecutive shards, with at least two parts, and no test pinned twice. +/// once, or with its [`Targets::Units`] on one shard and its [`Targets::Integration`] on another; +/// there must be exactly one [`Group::Rest`], and no test shard may be empty. A split's parts 1 +/// to n must be consecutive shards, with at least two parts, and no test pinned twice. pub fn assign(groups: &[Group], members: &[Member]) -> Result, String> { const WHERE: &str = "xtask/src/shards.rs › GROUPS"; - let mut named: BTreeMap<&str, usize> = BTreeMap::new(); + let mut named: BTreeMap<&str, Vec<(usize, Targets)>> = BTreeMap::new(); for (i, g) in groups.iter().enumerate() { - let names = match g { - Group::Crates(names) => *names, + let lists: Vec<(Targets, &[&str])> = match g { + Group::Targets(lists) => lists.to_vec(), Group::Part(split, k) => { let n = split.parts(); if n < 2 { @@ -222,22 +284,39 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result, String return Err(format!("`{name}` is pinned to two parts of shard {}'s split ({WHERE})", i + 1)); } } - split.crates + vec![(Targets::All, split.crates)] } Group::Rest | Group::Checks => continue, }; - if names.is_empty() { + if lists.iter().all(|(_, names)| names.is_empty()) { return Err(format!("shard {} names no crates ({WHERE})", i + 1)); } - for name in names { - if !members.iter().any(|m| m.name == *name) { - return Err(format!("shard {} names `{name}`, which is not a workspace member ({WHERE})", i + 1)); - } - if let Some(first) = named.insert(name, i) { - return Err(format!("`{name}` is in shard {} and shard {} ({WHERE})", first + 1, i + 1)); + for (targets, names) in lists { + for name in names { + if !members.iter().any(|m| m.name == *name) { + return Err(format!("shard {} names `{name}`, which is not a workspace member ({WHERE})", i + 1)); + } + let entries = named.entry(name).or_default(); + // The one allowed second entry: the other half of a crate split into units and integration tests. + let halves = + |a: Targets, b: Targets| matches!((a, b), (Targets::Units, Targets::Integration) | (Targets::Integration, Targets::Units)); + match entries.as_slice() { + [] => {} + [(first, t)] if halves(*t, targets) && *first != i => {} + [(first, _), ..] => return Err(format!("`{name}` is in shard {} and shard {} ({WHERE})", first + 1, i + 1)), + } + entries.push((i, targets)); } } } + for (name, entries) in &named { + if let [(i, t)] = entries.as_slice() + && *t != Targets::All + { + let other = if *t == Targets::Units { "integration" } else { "library and binary" }; + return Err(format!("shard {} runs part of `{name}`'s tests, and no shard runs its {other} tests ({WHERE})", i + 1)); + } + } let rests = groups.iter().filter(|g| **g == Group::Rest).count(); if rests != 1 { return Err(format!("{rests} shards take the remaining crates, not 1 ({WHERE})")); @@ -247,14 +326,23 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result, String .iter() .enumerate() .map(|(i, g)| match g { - Group::Crates(names) => Ok(Shard::Tests(pick(&|m| names.contains(&m.name.as_str())), None)), - Group::Part(split, index) => Ok(Shard::Tests(pick(&|m| split.crates.contains(&m.name.as_str())), Some(Part { split, index: *index }))), + Group::Targets(lists) => Ok(Shard::Tests( + lists + .iter() + .filter(|(_, names)| !names.is_empty()) + .map(|(targets, names)| Run { targets: *targets, crates: pick(&|m| names.contains(&m.name.as_str())) }) + .collect(), + None, + )), + Group::Part(split, index) => { + Ok(Shard::Tests(vec![Run::all(pick(&|m| split.crates.contains(&m.name.as_str())))], Some(Part { split, index: *index }))) + } Group::Rest => { let rest = pick(&|m| !named.contains_key(m.name.as_str())); if rest.is_empty() { return Err(format!("shard {} takes the remaining crates, and there are none ({WHERE})", i + 1)); } - Ok(Shard::Tests(rest, None)) + Ok(Shard::Tests(vec![Run::all(rest)], None)) } Group::Checks => Ok(Shard::Checks), }) @@ -325,6 +413,17 @@ pub fn names(crates: &[Member]) -> String { crates.iter().map(|m| m.name.as_str()).collect::>().join(", ") } +/// The crates of `runs` for messages, each run's targets after its crates unless it runs all of them. +pub fn describe(runs: &[Run]) -> String { + runs.iter() + .map(|r| match r.targets { + Targets::All => names(&r.crates), + t => format!("{} ({})", names(&r.crates), t.shown()), + }) + .collect::>() + .join(", ") +} + /// The shards of this workspace, after the checks in [`assign`] and [`feature_differences`]. pub fn check() -> Result, String> { let members = members(&crate::metadata()?)?; @@ -332,9 +431,12 @@ pub fn check() -> Result, String> { let workspace = tree_features(&tree(&["--workspace".to_owned()])?, &members); let mut differences = Vec::new(); for (i, shard) in shards.iter().enumerate() { - if let Shard::Tests(crates, _) = shard { - let alone = tree_features(&tree(&select(crates))?, &members); - differences.extend(feature_differences(i + 1, crates, &workspace, &alone)); + // Each run is its own cargo command, so cargo resolves features over that run's crates. + if let Shard::Tests(runs, _) = shard { + for r in runs { + let alone = tree_features(&tree(&select(&r.crates))?, &members); + differences.extend(feature_differences(i + 1, &r.crates, &workspace, &alone)); + } } } if !differences.is_empty() { @@ -354,9 +456,9 @@ pub fn run() -> Result, String> { let shards = check()?; for (i, shard) in shards.iter().enumerate() { match shard { - Shard::Tests(crates, part) => { + Shard::Tests(runs, part) => { let share = part.map(|p| format!(", part {} of {}", p.index, p.split.parts())).unwrap_or_default(); - println!("shard {}/{}: tests of {} crate(s): {}{share}", i + 1, shards.len(), crates.len(), names(crates)) + println!("shard {}/{}: tests of {}{share}", i + 1, shards.len(), describe(runs)) } Shard::Checks => println!("shard {}/{}: the other ci steps", i + 1, shards.len()), } @@ -392,17 +494,18 @@ mod tests { fn crates(shard: &Shard) -> Vec<&str> { match shard { - Shard::Tests(c, _) => c.iter().map(|m| m.name.as_str()).collect(), + Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| m.name.as_str())).collect(), Shard::Checks => Vec::new(), } } - /// The crates of each shard that runs a crate's tests from the start: a part after the first + /// Each crate a shard tests from the start, with the targets it runs: a part after the first /// runs a share of the same tests, so it is counted with part 1. - fn owners(shard: &Shard) -> Vec<&str> { + fn owners(shard: &Shard) -> Vec<(&str, Targets)> { match shard { Shard::Tests(_, Some(p)) if !p.is_first() => Vec::new(), - _ => crates(shard), + Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| (m.name.as_str(), r.targets))).collect(), + Shard::Checks => Vec::new(), } } @@ -451,12 +554,12 @@ mod tests { let ws = [m("a"), m("b")]; let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap(); assert_eq!(shards.iter().map(crates).collect::>(), [vec!["a"], vec!["a"], vec!["b"], vec![]]); - assert_eq!(shards[1], Shard::Tests(vec![m("a")], Some(Part { split: &SPLIT, index: 2 }))); + assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("a")])], Some(Part { split: &SPLIT, index: 2 }))); let apart = assign(&[Group::Part(&SPLIT, 1), Group::Rest, Group::Part(&SPLIT, 2)], &ws).unwrap_err(); assert!(apart.contains("not shards 1 to 2 in a row"), "{apart}"); let missing = assign(&[Group::Part(&SPLIT, 2), Group::Rest], &ws).unwrap_err(); assert!(missing.contains("shard 1 is part 2"), "{missing}"); - let twice = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Crates(&["a"]), Group::Rest], &ws).unwrap_err(); + let twice = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), ALL_A, Group::Rest], &ws).unwrap_err(); assert!(twice.contains("`a` is in shard 1 and shard 3"), "{twice}"); const ONE: Split = Split { crates: &["a"], pinned: &[&[]] }; assert!(assign(&[Group::Part(&ONE, 1), Group::Rest], &ws).unwrap_err().contains("not 2 or more")); @@ -519,26 +622,61 @@ mod tests { #[test] fn the_rest_shard_takes_every_crate_no_group_names() { let ws = [m("a"), m("b"), m("c"), m("d")]; - let shards = assign(&[Group::Crates(&["c"]), Group::Rest, Group::Checks], &ws).unwrap(); + let shards = assign(&[Group::Targets(&[(Targets::All, &["c"])]), Group::Rest, Group::Checks], &ws).unwrap(); assert_eq!(shards.iter().map(crates).collect::>(), [vec!["c"], vec!["a", "b", "d"], vec![]]); assert_eq!(shards[2], Shard::Checks); } + /// Every test target of `a`. + const ALL_A: Group = Group::Targets(&[(Targets::All, &["a"])]); + const UNITS: (Targets, &[&str]) = (Targets::Units, &["a"]); + const INTEGRATION: (Targets, &[&str]) = (Targets::Integration, &["a"]); + + #[test] + fn a_crate_s_units_and_integration_tests_run_on_two_shards() { + let ws = [m("a"), m("b"), m("c")]; + let shards = + assign(&[Group::Targets(&[UNITS]), Group::Targets(&[(Targets::All, &["b"]), INTEGRATION]), Group::Rest, Group::Checks], &ws).unwrap(); + assert_eq!(shards[0], Shard::Tests(vec![Run { targets: Targets::Units, crates: vec![m("a")] }], None)); + assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("b")]), Run { targets: Targets::Integration, crates: vec![m("a")] }], None)); + assert_eq!(crates(&shards[2]), ["c"]); + assert_eq!( + unit_crates(match &shards[1] { + Shard::Tests(r, _) => r, + Shard::Checks => panic!("shard 2 is a test shard"), + }), + [m("b")] + ); + let half = assign(&[Group::Targets(&[UNITS]), Group::Rest], &ws).unwrap_err(); + assert!(half.contains("no shard runs its integration tests"), "{half}"); + let other_half = assign(&[Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err(); + assert!(other_half.contains("no shard runs its library and binary tests"), "{other_half}"); + let with_all = assign(&[ALL_A, Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err(); + assert!(with_all.contains("`a` is in shard 1 and shard 2"), "{with_all}"); + let same_shard = assign(&[Group::Targets(&[UNITS, INTEGRATION]), Group::Rest], &ws).unwrap_err(); + assert!(same_shard.contains("`a` is in shard 1 and shard 1"), "{same_shard}"); + let units_twice = assign(&[Group::Targets(&[UNITS]), Group::Targets(&[UNITS]), Group::Rest], &ws).unwrap_err(); + assert!(units_twice.contains("`a` is in shard 1 and shard 2"), "{units_twice}"); + let third = + assign(&[Group::Targets(&[UNITS]), Group::Targets(&[INTEGRATION]), Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err(); + assert!(third.contains("`a` is in shard 1 and shard 3"), "{third}"); + } + #[test] fn a_crate_named_twice_or_unknown_fails() { let ws = [m("a"), m("b")]; - let twice = assign(&[Group::Crates(&["a"]), Group::Crates(&["a"]), Group::Rest], &ws).unwrap_err(); + let twice = assign(&[ALL_A, ALL_A, Group::Rest], &ws).unwrap_err(); assert!(twice.contains("`a` is in shard 1 and shard 2"), "{twice}"); - let unknown = assign(&[Group::Crates(&["z"]), Group::Rest], &ws).unwrap_err(); + let unknown = assign(&[Group::Targets(&[(Targets::All, &["z"])]), Group::Rest], &ws).unwrap_err(); assert!(unknown.contains("`z`, which is not a workspace member"), "{unknown}"); } #[test] fn empty_groups_and_a_missing_or_second_rest_fail() { let ws = [m("a"), m("b")]; - assert!(assign(&[Group::Crates(&[]), Group::Rest], &ws).unwrap_err().contains("names no crates")); - assert!(assign(&[Group::Crates(&["a", "b"]), Group::Rest], &ws).unwrap_err().contains("there are none")); - assert!(assign(&[Group::Crates(&["a"])], &ws).unwrap_err().contains("0 shards take the remaining crates")); + assert!(assign(&[Group::Targets(&[(Targets::All, &[])]), Group::Rest], &ws).unwrap_err().contains("names no crates")); + assert!(assign(&[Group::Targets(&[(Targets::All, &["a", "b"])]), Group::Rest], &ws).unwrap_err().contains("there are none")); + assert!(assign(&[ALL_A], &ws).unwrap_err().contains("0 shards take the remaining crates")); assert!(assign(&[Group::Rest, Group::Rest], &ws).unwrap_err().contains("2 shards take the remaining crates")); } @@ -546,11 +684,22 @@ mod tests { fn every_workspace_member_is_tested_on_exactly_one_shard() { let ws = members(&crate::metadata().unwrap()).unwrap(); let shards = assign(GROUPS, &ws).unwrap(); - let mut tested: Vec<&str> = shards.iter().flat_map(owners).collect(); - tested.sort_unstable(); + let mut tested: BTreeMap<&str, Vec> = BTreeMap::new(); + for (name, targets) in shards.iter().flat_map(owners) { + tested.entry(name).or_default().push(targets); + } + for targets in tested.values_mut() { + targets.sort_unstable(); + } let mut all: Vec<&str> = ws.iter().map(|m| m.name.as_str()).collect(); all.sort_unstable(); - assert_eq!(tested, all); + assert_eq!(tested.keys().copied().collect::>(), all); + for (name, targets) in &tested { + assert!( + *targets == [Targets::All] || *targets == [Targets::Units, Targets::Integration], + "`{name}` runs {targets:?}, not each test target once" + ); + } assert_eq!(shards.iter().filter(|s| **s == Shard::Checks).count(), 1); } @@ -602,13 +751,44 @@ geom v0.1.0 (/w/geom)| let expected: Vec = GROUPS .iter() .map(|g| match g { - Group::Crates(crates) => crates.join(" "), Group::Part(split, _) => split.crates.join(" "), + // The selection names each crate on one line only, so a shard that runs a crate's + // integration tests leaves it off its line and relies on a crate there that + // depends on it (checked below). + Group::Targets(lists) => { + lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect::>().join(" ") + } Group::Rest => "(rest)".to_owned(), Group::Checks => "(always)".to_owned(), }) .collect(); assert_eq!(shard_members(include_str!("../../.github/workflows/ci.yml")), expected, "shard-members in .github/workflows/ci.yml"); + let meta = crate::metadata().unwrap(); + let deps: BTreeMap<&str, Vec<&str>> = meta["packages"] + .as_array() + .unwrap() + .iter() + .map(|p| (p["name"].as_str().unwrap(), p["dependencies"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap()).collect())) + .collect(); + let reaches = |from: &str, to: &str| { + let (mut seen, mut stack) = (BTreeSet::new(), vec![from]); + while let Some(c) = stack.pop() { + if c == to { + return true; + } + if seen.insert(c) { + stack.extend(deps.get(c).into_iter().flatten().copied()); + } + } + false + }; + for g in GROUPS { + let Group::Targets(lists) = g else { continue }; + let named: Vec<&str> = lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect(); + for crate_ in lists.iter().filter(|(t, _)| *t == Targets::Integration).flat_map(|(_, c)| c.iter().copied()) { + assert!(named.iter().any(|n| reaches(n, crate_)), "no crate on the shard of `{crate_}`'s integration tests depends on it"); + } + } assert_eq!(shard_members(" shard-members: |\n a b\n (rest)\n next: 1\n"), ["a b", "(rest)"]); assert!(shard_members("test-shards: 6\n").is_empty()); } From 77e37176e2eb6bf844adf5e8da2e52cb31276e80 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:40:34 -0800 Subject: [PATCH 02/11] xtask: test-lint no longer reports helper, diagnostic and fixed-size false alarms no-assertion: - A call in a top-level test reaches the helper its own file defines. A non-asserting helper of the same name in another file of the crate no longer hides it (several_handles.rs `near` beside affinity_features.rs). Names the file also calls with a path, and definitions below the file's top level, keep the crate's verdict. - An `#[ignore = "reason"]` test that prints is a diagnostic and needs no assertion. - An asserting function passed by name as a value (`keeping_color_settings(the_body)`) counts as the test's check, also through a helper that passes it, unless a local binding or parameter shadows the name. all-unguarded: - A parenthesized range of literals or constants, `(0..3).all(...)`. - A receiver whose source an earlier `assert_eq!` compares with a non-empty literal: a local collected from the receiver, or a call on the same local the receiver was made from, when nothing changes the source in between. - A call to a function of the file that lists a constant table and filters it only on parameters that are not references. On the whole tree, `cargo xtask test-lint --all` reports 96 no-assertion hits instead of 157 and 375 all-unguarded hits instead of 419. --- xtask/src/test_lint.rs | 528 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 505 insertions(+), 23 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 5384b51e4c..a7d06b4602 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -16,8 +16,12 @@ //! be `const`s of the file) followed only by methods that keep an item (`map`, `iter`, `rev`, //! `collect` …), or filled by a `push` or `insert` on every pass of a loop over one, unless later //! code may shrink or replace them; and fields the file declares only as arrays of a positive -//! length. `.windows(k)` and `.chunks_exact(k)` need `k` items. Empty arrays still count. A change -//! anywhere in the test counts as a change to the hit; +//! length. `.windows(k)` and `.chunks_exact(k)` need `k` items. Empty arrays still count. Also +//! left out: a parenthesized range of literals or constants (`(0..3).all(…)`); a receiver whose +//! source an earlier equality assertion compares with a non-empty literal (a local bound from the +//! receiver, or a call on the same local as the receiver's binding); and a call to a function of +//! the file that lists a constant table and filters it only on parameters that are not +//! references. A change anywhere in the test counts as a change to the hit; //! * `only-weak`: every assertion is `is_ok()`, `is_some()`, `!is_empty()` or `len() > 0`, and the //! test calls no asserting helper; //! * `self-compare`: `assert_eq!(x, x)` or `assert_ne!(x, x)` on the same expression, when that @@ -26,7 +30,9 @@ //! * `exit-status-only`: a test that runs a process and checks only its exit status, reading no //! output, with a status check in any condition or compared operand of a standard assertion; //! * `no-assertion`: no assertion macro, `panic!`, `unwrap_err`, `expect_err` or asserting helper, -//! and no `#[should_panic]`; +//! and no `#[should_panic]`. An asserting helper passed by name as a value +//! (`keeping_settings(the_body)`) counts, and so does an `#[ignore = "…"]` test that prints. A +//! top-level test's call reaches the helper of its own file when the file defines one of that name; //! * `early-return`: a silent bare `return` before the end of the test whose guard tests a value //! from the code under test. Left out: a return after an assertion in its block, one whose //! statement or line has a comment or a printed note saying why, and guards on files, fonts, @@ -1134,35 +1140,92 @@ fn in_regions(regions: &[(usize, usize)], pos: usize) -> bool { type Def = (String, bool, Vec); /// For each crate of `files` ([`crate_of`]), the names of the functions and macros in its test -/// code, or in `crates/testkit`'s, that assert, panic or call one that does. +/// code, or in `crates/testkit`'s, that assert, panic or call one that does. Each file of `files` +/// also gets an entry under its path ([`helpers_for`]): a call in a top-level test reaches the function of +/// that name the file defines only when all its definitions are at the file's top level and +/// the file does not call that name with a path. Other names keep the crate's verdict. pub fn asserting_helpers(files: &[(String, String)]) -> HashMap> { let mut defs: HashMap> = HashMap::new(); + // Each file's path, its definitions, and the names its own definitions decide. + let mut by_file: Vec<(&str, Vec, HashSet)> = vec![]; for (path, src) in files { let m = mask(src); let regions = test_regions(path, &m, &tests_in(&m)); - let crate_defs = defs.entry(crate_of(path)).or_default(); - for at in words(&m, b"fn", 0, m.len()).into_iter().chain(words(&m, b"macro_rules", 0, m.len())) { - if in_regions(®ions, at) { - crate_defs.extend(definition(&m, at)); - } - } + let depths = brace_depths(&m); + let mut nested = HashSet::new(); + let own: Vec = words(&m, b"fn", 0, m.len()) + .into_iter() + .chain(words(&m, b"macro_rules", 0, m.len())) + .filter(|&at| in_regions(®ions, at)) + .filter_map(|at| { + let def = definition(&m, at)?; + if depths[at] != 0 { + nested.insert(def.0.clone()); + } + Some(def) + }) + .collect(); + // A call with a path (`other::near(…)`) may reach another module's function, and calls + // keep only the last name, so a name the file also calls with a path keeps the crate's + // verdict. A definition below the file's top level also keeps the crate's verdict. + let names = own.iter().map(|d| d.0.clone()).filter(|n| !nested.contains(n) && !called_with_path(&m, n)).collect(); + defs.entry(crate_of(path)).or_default().extend(own.iter().cloned()); + by_file.push((path, own, names)); } let testkit = defs.get(TESTKIT).cloned().unwrap_or_default(); - defs.iter().map(|(krate, own)| (krate.clone(), checking(own.iter().chain(if krate == TESTKIT { &[][..] } else { &testkit[..] })))).collect() + let mut out: HashMap> = defs + .iter() + .map(|(krate, own)| (krate.clone(), checking(HashSet::new(), own.iter().chain(if krate == TESTKIT { &[][..] } else { &testkit[..] })))) + .collect(); + for (path, own, names) in by_file { + if names.is_empty() { + continue; + } + let base = out.get(&crate_of(path)).map(|set| set.difference(&names).cloned().collect()).unwrap_or_default(); + out.insert(path.to_owned(), checking(base, own.iter().filter(|d| names.contains(&d.0)))); + } + out +} + +/// Whether the masked file names `name` (a function, or `name!` for a macro) after a `::` path. +fn called_with_path(m: &[u8], name: &str) -> bool { + let name = name.trim_end_matches('!'); + words(m, name.as_bytes(), 0, m.len()).into_iter().any(|at| m[..at].trim_ascii_end().ends_with(b"::")) +} + +/// The asserting helpers a test in the file at `path` can reach: for a top-level test, the file's +/// own entry of [`asserting_helpers`] if present; otherwise, its crate's. +fn helpers_for<'a>(ctx: &'a Ctx, path: &str, top_level: bool) -> Option<&'a HashSet> { + if top_level { ctx.helpers.get(path).or_else(|| ctx.helpers.get(&crate_of(path))) } else { ctx.helpers.get(&crate_of(path)) } +} + +/// The brace depth before each byte of masked text. +fn brace_depths(m: &[u8]) -> Vec { + let mut depth = 0usize; + m.iter() + .map(|&c| { + let before = depth; + match c { + b'{' => depth += 1, + b'}' => depth = depth.saturating_sub(1), + _ => {} + } + before + }) + .collect() } /// The crate whose test helpers every crate can call. const TESTKIT: &str = "crates/testkit"; -/// The names among `defs` that check something, directly or through another of `defs`. Calls do -/// not say which of several functions with one name they reach, so a name counts only when every -/// definition with that name checks. -fn checking<'a>(defs: impl Iterator + Clone) -> HashSet { +/// `known` and the names among `defs` that check something, directly or through another of +/// `defs` or a name of `known`. Calls do not say which of several functions with one name they +/// reach, so a name counts only when every definition with that name checks. +fn checking<'a>(mut known: HashSet, defs: impl Iterator + Clone) -> HashSet { let mut by_name: HashMap<&str, Vec<&Def>> = HashMap::new(); for d in defs { by_name.entry(d.0.as_str()).or_default().push(d); } - let mut known: HashSet = HashSet::new(); loop { let checks = |d: &Def| d.1 || d.2.iter().any(|c| known.contains(c)); let more: Vec = by_name @@ -1199,7 +1262,12 @@ fn item_at(m: &[u8], at: usize) -> Option<(&[u8], bool, usize, usize)> { 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(); + let called = calls(m, open, close) + .into_iter() + .filter(|(_, method)| !method) + .map(|(n, _)| n) + .chain(passed_names(m, open, close).into_iter().filter(|name| !shadows_helper(m, at, open, close, name.as_bytes()))) + .collect(); Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) } @@ -1210,6 +1278,8 @@ struct File<'a> { path: &'a str, src: &'a [u8], m: Vec, + /// The brace depth before each byte of [`File::m`] ([`brace_depths`]). + depths: Vec, /// [`File::m`] with the functions and macros declared inside each test blanked: declaring /// one does not run its body ([`executed`]). exec: Vec, @@ -1252,10 +1322,11 @@ impl File<'_> { /// Every hit in one file, exemptions applied. pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { let m = mask(src); + let depths = brace_depths(&m); let tests = tests_in(&m); let regions = test_regions(path, &m, &tests); let exec = executed(&m, &tests); - let file = File { path, src: src.as_bytes(), m, exec, lines: Lines::new(src), tests, regions }; + let file = File { path, src: src.as_bytes(), m, depths, 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)); @@ -1309,19 +1380,106 @@ struct View<'a> { delegates: bool, checks: bool, should_panic: bool, + /// An ignored test with a reason that prints what it measures ([`ignored_with_reason`], + /// [`prints`]): a diagnostic run by hand, which has nothing to assert. + diagnostic: bool, +} + +/// Whether a test's body passes an asserting helper by name as a value, an argument or a tuple +/// element (`keeping_settings(the_test_body)`, `[("case", case_body), …]`), excluding local bindings +/// and parameters that shadow helper names. +fn passes_helper(m: &[u8], t: &TestFn, helpers: &HashSet) -> bool { + passed_names(m, t.open, t.close).into_iter().any(|name| { + name != t.name && !COMMON.contains(&name.as_str()) && helpers.contains(&name) && !shadows_helper(m, t.fn_at, t.open, t.close, name.as_bytes()) + }) +} + +/// Whether a local binding or parameter between `at` and `close` shadows the helper `name`. +fn shadows_helper(m: &[u8], at: usize, open: usize, close: usize, name: &[u8]) -> bool { + let_binds(&m[open + 1..close], name) || binds_parameter(&m[at..close], name) +} + +/// The bare identifiers passed as arguments or tuple elements in the body between `open` and `close`. +fn passed_names(m: &[u8], open: usize, close: usize) -> Vec { + let mut names = Vec::new(); + let mut at = open + 1; + while at < close { + if !is_ident(m[at]) || (at > 0 && (is_ident(m[at - 1]) || m[at - 1] == b'.')) { + at += 1; + continue; + } + let end = at + m[at..close].iter().take_while(|&&c| is_ident(c)).count(); + let before = m[..at].trim_ascii_end().last().copied(); + let after = m.get(skip_ws(m, end)).copied(); + if matches!(before, Some(b'(' | b',')) && matches!(after, Some(b')' | b',')) { + names.push(String::from_utf8_lossy(&m[at..end]).into_owned()); + } + at = end; + } + names +} + +/// Whether a function or closure in `body` takes a parameter that binds `name`. +fn binds_parameter(body: &[u8], name: &[u8]) -> bool { + let binds = |from, to| { + split_args(body, from, to).into_iter().any(|(start, end)| { + let pattern = &body[start..end]; + let end = pattern.iter().position(|&c| c == b':').unwrap_or(pattern.len()); + !words(pattern, name, 0, end).is_empty() + }) + }; + if words(body, b"fn", 0, body.len()).into_iter().any(|at| { + let Some(open) = body[at + 2..].iter().position(|&c| c == b'(').map(|p| at + 2 + p) else { return false }; + matching(body, open).is_some_and(|close| binds(open + 1, close)) + }) { + return true; + } + let mut at = 0; + while at < body.len() { + let head = body[..at].trim_ascii_end(); + let opens = head.last().is_some_and(|c| matches!(c, b'=' | b'(' | b',' | b'{' | b';')) + || [b"move".as_slice(), b"return", b"=>"].iter().any(|word| head.ends_with(word)); + if body[at] == b'|' && opens { + let Some(close) = body[at + 1..].iter().position(|&c| c == b'|').map(|p| at + 1 + p) else { return false }; + if binds(at + 1, close) { + return true; + } + at = close; + } + at += 1; + } + false +} + +/// Whether the attributes in `file.m[from..to]` include `#[ignore = "…"]` with a non-blank reason. +fn ignored_with_reason(file: &File, from: usize, to: usize) -> bool { + let m = &file.m; + words(m, b"ignore", from, to).into_iter().any(|at| { + let j = skip_ws(m, at + "ignore".len()); + m[..at].ends_with(b"#[") + && m.get(j) == Some(&b'=') + && ignore_reason(&file.src[skip_ws(m, j + 1)..]).is_some_and(|body| body.iter().any(|c| !c.is_ascii_whitespace())) + }) +} + +/// Whether the masked text prints: `println!`, `eprintln!`, `print!` or `eprint!`. +fn prints(m: &[u8], from: usize, to: usize) -> bool { + macro_calls(m, from, to).iter().any(|c| matches!(c.name.as_str(), "println" | "eprintln" | "print" | "eprint")) } fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { 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); + let helpers = helpers_for(ctx, file.path, file.depths[t.attr] == 0).unwrap_or(&none); let delegates = calls(m, t.open, t.close) .iter() - .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)); + .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)) + || passes_helper(m, t, helpers); let checks = checks_itself(m, t.open, t.close); let should_panic = should_panic_attr(m, t.attr, t.fn_at); - let v = View { file, t, asserts, delegates, checks, should_panic }; + let diagnostic = ignored_with_reason(file, t.attr, t.fn_at) && prints(m, t.open, t.close); + let v = View { file, t, asserts, delegates, checks, should_panic, diagnostic }; let mut hits = all_unguarded(&v); hits.extend(self_compare(&v)); hits.extend(early_returns(&v)); @@ -1811,7 +1969,167 @@ fn positive_all(cond: &str, test_body: &[u8], sizes: &Sizes) -> bool { let body = arg.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(arg, |(_, body)| body); let none_match = not_equal_conjunction(body); let (receiver, need) = receiver_need(&cond[..i], sizes); - !none_match && least_items(receiver, test_body, sizes) < need + // A parenthesized range of literals or constants: `(0..3).all(…)`. + let range = if receiver.starts_with('(') { expr_len(receiver, sizes, "") } else { 0 }; + let known = least_items(receiver, test_body, sizes).max(range); + !none_match && known < need && !(need == 1 && (pinned_source(receiver, test_body, sizes) || fixed_table_call(receiver, test_body, sizes))) + }) +} + +/// Whether an earlier equality assertion compares what `receiver` is made from with a non-empty +/// literal: a plain local whose binding reads `receiver` (`let got = r.items()….collect(); +/// assert_eq!(got, [a, b])` before `r.items().iter().all(…)`), or a call on the same plain local +/// as the call `receiver` is bound to (`let gaps = gaps(&word); assert_eq!(ids(&word), [a, b, c])`). +fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { + let r = array_receiver(receiver); + let init = |name: &str, at: usize| let_init(body, name, at).and_then(|(init, _)| init); + // For a receiver bound to `f(&x)`: `x`, and where the binding of `x` it reads ends. + let source = if plain_local(r) { + let_init(body, r, body.len()).and_then(|(init, bound)| { + let (text, _) = init?; + let s = single_local_arg(&text)?.to_owned(); + if binds(&body[bound..], s.as_bytes()) { + return None; + } + let at = let_init(body, &s, bound).map_or(0, |(_, at)| statement_end(body, at)); + Some((s, at)) + }) + } else { + None + }; + macro_calls(body, 0, body.len()).into_iter().any(|a| { + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) || a.args.len() < 2 { + return false; + } + let (left, right) = (norm(&body[a.args[0].0..a.args[0].1]), norm(&body[a.args[1].0..a.args[1].1])); + [(&left, &right), (&right, &left)].into_iter().any(|(pinned, literal)| { + if literal_len(literal, sizes) == 0 { + return false; + } + // The binding keeps the receiver's items (`r.items().iter().map(…).collect()`), and + // nothing changes the receiver's source from the binding on. + let read = !plain_local(r) + && plain_local(pinned) + && init(pinned, a.at) + .is_some_and(|(text, at)| keeping_base(&text, true) == r && !touched_after(body, root_local(r), statement_end(body, at), r)); + read || source.as_ref().is_some_and(|(s, at)| single_local_arg(pinned) == Some(s.as_str()) && !touched_after(body, s, *at, r)) + }) + }) +} + +/// The local a receiver path starts from: `r` of `r.items()`. +fn root_local(expr: &str) -> &str { + let end = expr.bytes().take_while(|&c| is_ident(c)).count(); + &expr[..end] +} + +/// Whether code after `from` uses `name` other than through a read-only use of `receiver`, a shared borrow +/// `&name`, or a getter named `len`, `is_empty` or ending in `_count`. Other uses, including +/// assertion arguments, may change what it holds. +fn touched_after(body: &[u8], name: &str, from: usize, receiver: &str) -> bool { + if !plain_local(name) { + return true; + } + words(body, name.as_bytes(), from, body.len()).into_iter().any(|at| { + let rest = norm(&body[at..statement_end(body, at)]); + let head = body[..at].trim_ascii_end(); + let shared = head.ends_with(b"&") && !head.ends_with(b"&&"); + let getter = rest + .strip_prefix(name) + .and_then(|r| r.strip_prefix('.')) + .and_then(|r| r.split_once('(')) + .is_some_and(|(method, _)| plain_local(method) && (matches!(method, "len" | "is_empty") || method.ends_with("_count"))); + let read = rest.strip_prefix(receiver).is_some_and(|tail| { + tail.is_empty() + || tail.starts_with([')', ']', '}', ',']) + || [".iter()", ".len()", ".is_empty()", ".first()", ".last()", ".get(", ".contains("].iter().any(|method| tail.starts_with(method)) + }); + !(read || shared || getter) + }) +} + +/// The plain local of a call with one argument, `f(&x)` or `f(x)`. +fn single_local_arg(call: &str) -> Option<&str> { + let open = call.find('(')?; + let head = &call[..open]; + if head.is_empty() || !head.bytes().all(|c| is_ident(c) || c == b':') || matching(call.as_bytes(), open) != Some(call.len() - 1) { + return None; + } + let arg = &call[open + 1..call.len() - 1]; + let arg = arg.strip_prefix('&').unwrap_or(arg); + plain_local(arg).then_some(arg) +} + +/// Whether `receiver` calls a function of the file whose body lists a constant table +/// (`TABLE.iter()…`, `Kind::ALL.iter()…`) and filters it only on parameters that are not +/// references: which rows it gives depends on the table and plain values, not on the state the +/// test builds. +fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { + let r = array_receiver(receiver); + let Some(open) = r.find('(') else { return false }; + let name = &r[..open]; + if !plain_local(name) + || matching(r.as_bytes(), open) != Some(r.len() - 1) + || let_binds(test_body, name.as_bytes()) + || binds_parameter(test_body, name.as_bytes()) + { + return false; + } + let file = sizes.file; + words(file, name.as_bytes(), 0, file.len()).into_iter().any(|at| { + let head = file[..at].trim_ascii_end(); + if !head.ends_with(b"fn") || (head.len() > 2 && is_ident(head[head.len() - 3])) { + return false; + } + let Some((_, _, body_open, body_close)) = item_at(file, head.len() - 2) else { return false }; + let params_open = skip_ws(file, at + name.len()); + let Some(params_close) = (file.get(params_open) == Some(&b'(')).then(|| matching(file, params_open)).flatten() else { return false }; + let signature = norm(&file[params_close + 1..body_open]); + let return_type = signature.strip_prefix("->").unwrap_or(""); + let refs: Vec = split_args(file, params_open + 1, params_close) + .into_iter() + .filter_map(|(f, t)| norm(&file[f..t]).split_once(':').filter(|(_, ty)| ty.starts_with('&')).map(|(n, _)| n.to_owned())) + .collect(); + let body = norm(&file[body_open + 1..body_close]); + let table_end = body.bytes().take_while(|&c| is_ident(c) || c == b':').count(); + let table = &body[..table_end]; + let screaming = table + .rsplit("::") + .next() + .is_some_and(|last| !last.is_empty() && last.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')); + if !screaming || !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()")) { + return false; + } + // The body is the chain alone, of steps that keep or filter rows; everything up to the end + // of the last `filter`, maps before it included, reads no reference parameter. + let mut at = table_end; + let mut decided = 0; + while at < body.len() { + let Some(rest) = body[at..].strip_prefix('.') else { return false }; + let method_len = rest.bytes().take_while(|&c| is_ident(c)).count(); + let method = &rest[..method_len]; + let mut open = at + 1 + method_len; + let mut target = None; + if method == "collect" && body[open..].starts_with("::<") { + let Some(close) = body[open..].find(">(") else { return false }; + target = Some(&body[open + 3..open + close]); + open += close + 1; + } + let Some(close) = (body.as_bytes().get(open) == Some(&b'(')).then(|| matching(body.as_bytes(), open)).flatten() else { return false }; + match method { + "iter" | "into_iter" | "map" | "copied" | "cloned" | "enumerate" | "rev" => {} + "collect" => { + if !known_collection(target.unwrap_or(if close + 1 == body.len() { return_type } else { "" })) { + return false; + } + } + "filter" => decided = close + 1, + _ => return false, + } + at = close + 1; + } + let decided = &body[..decided]; + refs.iter().all(|p| words(decided.as_bytes(), p.as_bytes(), 0, decided.len()).is_empty()) }) } @@ -1880,6 +2198,23 @@ fn least_items(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { .max(if binds(body, array_receiver(receiver).as_bytes()) { 0 } else { item_len(receiver, sizes) }) } +/// Whether a `let` pattern in masked `body` contains `name` as a whole word. +fn let_binds(body: &[u8], name: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let start = at + 3; + let mut end = start; + while end < body.len() { + if matches!(body[end], b'=' | b';') + || (body[end..].starts_with(b"else") && !is_ident(body[end - 1]) && !body.get(end + 4).copied().is_some_and(is_ident)) + { + break; + } + end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 }; + } + !words(body, name, start, end).is_empty() + }) +} + /// Whether `body` has a `let` binding of `name`. fn binds(body: &[u8], name: &[u8]) -> bool { words(body, b"let", 0, body.len()).into_iter().any(|at| { @@ -2689,7 +3024,7 @@ fn strip_stream_configuration(body: &mut [u8]) { } fn no_assertion(v: &View) -> Option { - if v.checks || v.delegates || v.should_panic { + if v.checks || v.delegates || v.should_panic || v.diagnostic { return None; } Some(v.whole(Rule::NoAssertion, "no assertion and no asserting helper".into())) @@ -5128,6 +5463,153 @@ mod tests { assert_eq!(hits_in("crates/x/tests/it.rs", &both, &Ctx { helpers, ..Ctx::default() }), []); } + #[test] + fn a_files_own_helper_decides_over_one_of_the_same_name_in_another_file() { + let own = "fn near(a: f64) { assert!(a < 1.0); }\n#[test]\nfn t() {\n near(f());\n}\n"; + let other = "fn near(a: f64) -> bool { a < 1.0 }\n#[test]\nfn u() {\n assert!(near(f()));\n}\n"; + let caller = "#[test]\nfn v() {\n near(f());\n}\n"; + let files = [ + ("crates/x/tests/it/own.rs".to_owned(), own.to_owned()), + ("crates/x/tests/it/other.rs".to_owned(), other.to_owned()), + ("crates/x/tests/it/caller.rs".to_owned(), caller.to_owned()), + ]; + let ctx = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/tests/it/own.rs", own, &ctx), [], "the file's own near asserts"); + let qualified = own.replace(" near(f());", " other::near(f());"); + let files = [files[0].clone(), files[1].clone(), ("crates/x/tests/it/q.rs".to_owned(), qualified.clone())]; + let ctx_q = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/q.rs", &qualified, &ctx_q), + [(3, "no-assertion")], + "a call with a path may reach the other file's near" + ); + assert_eq!( + hits_in("crates/x/tests/it/caller.rs", caller, &ctx), + [(2, "no-assertion")], + "a file that defines none cannot tell which it reaches" + ); + let nested = "mod a {\n fn near(a: f64) { assert!(a < 1.0); }\n}\nuse other::*;\n#[test]\nfn t() {\n near(f());\n}\n"; + let files = [("crates/x/tests/it/nested.rs".to_owned(), nested.to_owned()), files[1].clone()]; + let ctx_nested = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/nested.rs", nested, &ctx_nested), + [(6, "no-assertion")], + "a helper inside an inline module does not decide for the file's top-level call" + ); + let inner = + "fn near(a: f64) { assert!(a < 1.0); }\nmod inner {\n use super::other::*;\n #[test]\n fn t() {\n near(f());\n }\n}\n"; + let files = [("crates/x/tests/it/inner.rs".to_owned(), inner.to_owned()), files[1].clone()]; + let ctx_inner = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/inner.rs", inner, &ctx_inner), + [(5, "no-assertion")], + "a test inside an inline module may import the other file's near" + ); + let local = "#[test]\nfn t() {\n fn near(a: f64) { assert!(a < 1.0); }\n assert!(f());\n}\n#[test]\nfn u() {\n near(f());\n}\n"; + let files = [("crates/x/tests/it/local.rs".to_owned(), local.to_owned()), files[1].clone()]; + let ctx_local = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/local.rs", local, &ctx_local), + [(7, "no-assertion")], + "a helper inside a test does not decide for another test's call" + ); + } + + #[test] + fn an_ignored_diagnostic_that_prints_needs_no_assertion() { + let diagnostic = "#[test]\n#[ignore = \"manual timing\"]\nfn t() {\n let n = f();\n eprintln!(\"{n:?}\");\n}\n"; + assert_eq!(hits(diagnostic), []); + assert_eq!(hits(&diagnostic.replace(" eprintln!(\"{n:?}\");\n", "")), [(3, "no-assertion")], "an ignored test that prints nothing"); + assert_eq!(hits(&diagnostic.replace("#[ignore = \"manual timing\"]\n", "")), [(2, "no-assertion")], "a test that runs and only prints"); + } + + #[test] + fn a_test_body_passed_to_a_wrapper_counts_as_its_check() { + let src = "fn keeping(test: fn()) {\n test();\n}\nfn body() {\n assert_eq!(f(), 1);\n}\n#[test]\nfn t() {\n keeping(body);\n}\n"; + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), src.to_owned())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), []); + let wrapper = src.replace(" keeping(body);", " wrapper();") + "fn wrapper() {\n keeping(body);\n}\n"; + let wrapper_ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), wrapper.clone())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &wrapper, &wrapper_ctx), []); + let shadowed_wrapper = wrapper.replace(" keeping(body);", " let body = || {};\n keeping(body);"); + let shadowed_wrapper_ctx = + Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), shadowed_wrapper.clone())]), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/src/tests.rs", &shadowed_wrapper, &shadowed_wrapper_ctx), + [(8, "no-assertion")], + "a local binding in a wrapper shadows the asserting helper" + ); + let shadowed = src.replace(" keeping(body);", " let body = || {};\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &shadowed, &ctx), [(8, "no-assertion")], "a local binding shadows the asserting helper"); + let destructured = src.replace(" keeping(body);", " let (body,) = (|| {},);\n keeping(body);"); + assert_eq!( + hits_in("crates/x/src/tests.rs", &destructured, &ctx), + [(8, "no-assertion")], + "a destructured binding shadows the asserting helper" + ); + let closure = src.replace(" keeping(body);", " keeping(|body| keeping(body));"); + assert_eq!(hits_in("crates/x/src/tests.rs", &closure, &ctx), [(8, "no-assertion")], "a closure parameter shadows the asserting helper"); + let parameter = src.replace("fn t()", "fn t(body: fn())"); + assert_eq!(hits_in("crates/x/src/tests.rs", ¶meter, &ctx), [(8, "no-assertion")], "a function parameter shadows the asserting helper"); + let idle = src.replace("assert_eq!(f(), 1);", "f();"); + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), idle.clone())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &idle, &ctx), [(8, "no-assertion")], "a passed body that checks nothing"); + } + + #[test] + fn all_over_a_literal_range_or_a_pinned_source_is_guarded() { + let range = "#[test]\nfn t() {\n assert!((0..3).all(|i| a[i] == b[i]));\n}\n"; + assert_eq!(hits(range), []); + assert_eq!(hits(&range.replace("(0..3)", "(0..n)")), [(3, "all-unguarded")], "a range whose end the test does not show"); + let pinned = "#[test]\nfn t() {\n let got: Vec = r.items().iter().map(|j| j.n).collect();\n assert_eq!(got, vec![1, 2]);\n assert!(r.items().iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(pinned), []); + assert_eq!(hits(&pinned.replace("vec![1, 2]", "vec![]")), [(5, "all-unguarded")], "pinned to an empty list"); + assert_eq!(hits(&pinned.replace("= r.items()", "= other.items()")), [(5, "all-unguarded")], "a list made from another receiver"); + let shadowed = "#[test]\nfn t() {\n let got = f();\n assert_eq!(got, vec![1]);\n let got: Vec = r.items().iter().map(|j| j.n).collect();\n assert!(r.items().iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(shadowed), [(6, "all-unguarded")], "the pinned binding is not the one made from the receiver"); + let cleared = pinned.replace(" assert!(r.items()", " r.clear();\n assert!(r.items()"); + assert_eq!(hits(&cleared), [(6, "all-unguarded")], "the receiver changed after the assertion"); + let cleared_items = pinned.replace(" assert!(r.items()", " r.items().clear();\n assert!(r.items()"); + assert_eq!(hits(&cleared_items), [(6, "all-unguarded")], "the receiver's items changed after the assertion"); + let early = pinned.replace(" assert_eq!(got", " r.clear();\n assert_eq!(got"); + assert_eq!(hits(&early), [(6, "all-unguarded")], "the receiver changed between the binding and the assertion"); + let taken = pinned.replace(" assert!(r.items()", " assert!(r.take_items().is_some());\n assert!(r.items()"); + assert_eq!(hits(&taken), [(6, "all-unguarded")], "an assertion changes the receiver after the pinning assertion"); + let counted = pinned.replace(" assert!(r.items()", " assert_eq!(r.unhandled_rejection_count(), 2);\n assert!(r.items()"); + assert_eq!(hits(&counted), [], "a count getter preserves the pinned source"); + let chained = pinned.replace(".map(|j| j.n)", ".map(|j| j.n).chain([1])"); + assert_eq!(hits(&chained), [(5, "all-unguarded")], "a list that is not empty without the receiver's items"); + let word = "#[test]\nfn t() {\n let plain = word();\n assert_eq!(ids(&plain), [1, 2, 3]);\n let gaps = gaps(&plain);\n assert!(gaps.iter().all(|g| g.abs() < 1e-6));\n}\n"; + assert_eq!(hits(word), []); + assert_eq!(hits(&word.replace("ids(&plain)", "ids(&other)")), [(6, "all-unguarded")], "a literal about another value"); + let emptied = word.replace(" let gaps = gaps(&plain);\n", " let mut gaps = gaps(&plain);\n gaps.clear();\n"); + assert_eq!(hits(&emptied), [(7, "all-unguarded")], "a receiver that may change after its binding"); + let rebound = word.replace(" assert_eq!(ids(&plain), [1, 2, 3]);\n", "").replace( + " let gaps = gaps(&plain);", + " let gaps = gaps(&plain);\n let plain = other();\n assert_eq!(ids(&plain), [1, 2, 3]);", + ); + assert_eq!(hits(&rebound), [(7, "all-unguarded")], "the assertion reads a later binding of the source"); + } + + #[test] + fn all_over_a_constant_table_filtered_on_plain_values_is_guarded() { + let src = "fn reasons(app: &App, wide: bool) -> Vec> {\n TABLE.iter().filter(|r| r.wide == wide).map(|r| app.reason(r)).collect()\n}\n#[test]\nfn t() {\n let app = App::new();\n assert!(reasons(&app, true).iter().all(|r| r.is_none()));\n}\n"; + assert_eq!(hits(src), []); + let shadowed = src.replace(" assert!", " let reasons = |_: &App, _: bool| Vec::>::new();\n assert!"); + assert_eq!(hits(&shadowed), [(8, "all-unguarded")], "a local binding shadows the file's function"); + let state = src.replace("filter(|r| r.wide == wide)", "filter(|r| app.has(r))"); + assert_eq!(hits(&state), [(7, "all-unguarded")], "a filter on the state the test builds"); + let mapped = src.replace(".filter(|r| r.wide == wide).map(|r| app.reason(r))", ".map(|r| app.reason(r)).filter(|r| r.is_some())"); + assert_eq!(hits(&mapped), [(7, "all-unguarded")], "a filter on values mapped from that state"); + let map_while = src.replace(".filter(|r| r.wide == wide).map(|r| app.reason(r))", ".map_while(|r| app.reason(r))"); + assert_eq!(hits(&map_while), [(7, "all-unguarded")], "another step that drops rows"); + let optional = src + .replace("-> Vec>", "-> Option>>") + .replace(".map(|r| app.reason(r))", ".map(|r| Some(app.reason(r)))") + .replace(".all(|r| r.is_none())", ".all(|r| r.len() == 1)"); + assert_eq!(hits(&optional), [(7, "all-unguarded")], "collecting into an option can discard every row"); + } + #[test] fn a_changed_collection_loses_its_equality_guard() { let src = "#[test]\nfn t() {\n let mut xs = f();\n assert_eq!(xs, vec![1]);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; From 7fcf87a1fa56cf16455b03e0802d9906285503e7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 13:42:55 -0800 Subject: [PATCH 03/11] xtask: test-lint follows every module route and binding scope - never-run: a parent edit now counts for a child file when its module gates differ from the base, so deleting the last unconditional `mod` declaration fails the check; a deleted parent file counts too. - never-run: the base verdicts are computed once per file and matched by test name and line, so `a::smoke` already off does not hide `b::smoke`. - never-run: each load route joins its own declaration and ancestor gates, and the routes join with `any`; `#[cfg_attr(, path = "...")]` loads the other file only under its condition; every line of a multi-line `cfg` counts as a change. - no-assertion: a helper passed as an argument is shadowed only by a binding in scope at that argument, including `for` patterns and closure parameters; a tuple that is dropped or bound to `_` does not count, and a name in a `let` pattern is not a passed value. - census: `if { panic!(...) }` that rejects input is a check. - all-unguarded: a shared borrow passed to a call between the pinning assertion and `.all(...)` may change the items. - all-unguarded: `mut app: &App` parameters are read by their name, and a function with a pattern parameter is not fixed-table evidence. - reads-source: only the literal the path ends in names the file, so `root.join("fixtures.rs").join(name)` is not a Rust source read. - fixture-only: a `match` arm pattern shadows an outer binding inside that arm. - exact-pixel: a rect read passed to a call is the call's input. - Docs: list every report-only rule and the enclosing-gate exception. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 653 ++++++++++++++++++++++++++++++++++------- 2 files changed, 556 insertions(+), 99 deletions(-) diff --git a/docs/development.md b/docs/development.md index c833a400e8..359da987d2 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` keeps out of every CI test build (`never-run`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, and an environment variable that no CI leg sets. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` keeps out of every CI test build (`never-run`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, a loop or `.all(…)` over every entry of a table that checks only presence (`census`), a comparison of a function with a second call of itself (`mirror`), an assertion of a constant or literal the test or crate states (`constant-echo`), an assertion on only the input the test built (`fixture-only`), and a UI test that compares a rect with numbers written out (`exact-pixel`). The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it, with one exception: a change to a `mod` declaration or a `cfg` attribute on it, or the removal of a `mod` declaration, fails `never-run` for a test in an unchanged file below it when the change takes that test out of every CI test build. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 677c84b16f..e31150df25 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -276,6 +276,29 @@ fn gate_changed(gates: Option<&Gates>, changed: &BTreeMap, then: Option<&Gates>, changed: &BTreeMap>>) -> bool { + let preds = |g: Option<&Gates>| g.map(|g| g.preds.clone()).unwrap_or_default(); + gate_changed(now, changed) || preds(now) != preds(then) +} + +/// The `never-run` tests in `src` under the module gates of `ctx`, by test name and `fn` line, so two +/// tests with one name in different modules of the file stay apart. +fn never_run_at(path: &str, src: &str, ctx: &Ctx) -> NeverRunSet { + lint_file(path, src, ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect() +} + +/// The tests in `src` that run in CI under the base's gates and that the current gates turn off. +/// The base verdicts are computed once for the file. +fn newly_off(path: &str, src: &str, ctx: &Ctx, base: &Ctx) -> Vec { + let before = never_run_at(path, src, base); + lint_file(path, src, ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && !before.contains(&(h.test.clone(), h.line))).collect() +} + +type NeverRunSet = HashSet<(String, usize)>; + /// A source file read from the work tree, or `None` when it is missing or larger than [`MAX_FILE`]. fn read_small(root: &Path, path: &str) -> Option { let full = root.join(path); @@ -303,8 +326,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); // Files under the module of a changed file: a `cfg` added to their `mod` declaration can turn // their tests off without a change to them. - let module_dirs: Vec = present - .iter() + // A deleted file counts too: its `mod` declarations were routes to the files below it. + let module_dirs: Vec = changed + .keys() .map(|p| { let (dir, file) = p.rsplit_once('/').unwrap_or(("", p)); if ["mod.rs", "lib.rs", "main.rs"].contains(&file) { format!("{dir}/") } else { format!("{}/", p.trim_end_matches(".rs")) } @@ -319,16 +343,19 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { // The gates the parent declarations gave at the base: a parent edit counts against a child's // test only when the test ran in CI before it. let read_base = |p: &str| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE); - let base_cfgs = module_gates(&gated, &read_base).into_iter().map(|(p, g)| (p, g.preds)).collect(); + let base_gates = module_gates(&gated, &read_base); + let moved = |p: &str| gates_moved(gates.get(p), base_gates.get(p), &changed); + let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - let newly_off = - |path: &str, src: &str, hit: &Hit| !lint_file(path, src, &base_ctx).iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test); let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { - let parent_changed = gate_changed(gates.get(&path), &changed); + let parent_changed = moved(&path); + let mut base_off = None; for hit in lint_file(&path, &src, &ctx) { if touches(&hit, changed.get(&path).and_then(Option::as_ref)) - || (hit.rule == Rule::NeverRun && parent_changed && newly_off(&path, &src, &hit)) + || (hit.rule == Rule::NeverRun + && parent_changed + && !base_off.get_or_insert_with(|| never_run_at(&path, &src, &base_ctx)).contains(&(hit.test.clone(), hit.line))) { counted.push(hit); } else { @@ -336,9 +363,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } } } - for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed)) { + for path in below.iter().filter(|p| moved(p)) { let Some(src) = read_small(root, path) else { continue }; - counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h))); + counted.extend(newly_off(path, &src, &ctx, &base_ctx)); } finish(&counted, older, present.len(), &base) } @@ -1263,7 +1290,9 @@ fn definition(m: &[u8], at: usize) -> Option { .into_iter() .filter(|(_, method)| !method) .map(|(n, _)| n) - .chain(passed_names(m, open, close).into_iter().filter(|name| !shadows_helper(m, at, open, close, name.as_bytes()))) + .chain( + passed_names(m, open, close).into_iter().filter(|(name, pos)| !shadows_helper(m, at, open, close, name.as_bytes(), *pos)).map(|(n, _)| n), + ) .collect(); Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) } @@ -1386,18 +1415,100 @@ struct View<'a> { /// element (`keeping_settings(the_test_body)`, `[("case", case_body), …]`), excluding local bindings /// and parameters that shadow helper names. fn passes_helper(m: &[u8], t: &TestFn, helpers: &HashSet) -> bool { - passed_names(m, t.open, t.close).into_iter().any(|name| { - name != t.name && !COMMON.contains(&name.as_str()) && helpers.contains(&name) && !shadows_helper(m, t.fn_at, t.open, t.close, name.as_bytes()) + passed_names(m, t.open, t.close).into_iter().any(|(name, pos)| { + name != t.name + && !COMMON.contains(&name.as_str()) + && helpers.contains(&name) + && !shadows_helper(m, t.fn_at, t.open, t.close, name.as_bytes(), pos) }) } -/// Whether a local binding or parameter between `at` and `close` shadows the helper `name`. -fn shadows_helper(m: &[u8], at: usize, open: usize, close: usize, name: &[u8]) -> bool { - let_binds(&m[open + 1..close], name) || binds_parameter(&m[at..close], name) +/// Whether a parameter of the function at `at` (body `open..close`), or a local binding in scope at +/// `pos`, shadows the helper `name`. +fn shadows_helper(m: &[u8], at: usize, open: usize, close: usize, name: &[u8], pos: usize) -> bool { + binds_parameter(&m[at..=open], name) || bound_at(&m[open + 1..close], name, pos - (open + 1)) } -/// The bare identifiers passed as arguments or tuple elements in the body between `open` and `close`. -fn passed_names(m: &[u8], open: usize, close: usize) -> Vec { +/// Whether a binding of `name` in `body` is in scope at `pos`: a `let` from the end of its statement +/// to the end of its block (an `if let` or `while let` in its block only), a `for` pattern in the +/// loop body, or a closure parameter in the brackets that hold the closure. +fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool { + let lets = words(body, b"let", 0, pos).into_iter().any(|at| { + let start = at + 3; + let mut end = start; + while end < body.len() { + if matches!(body[end], b'=' | b';') + || (body[end..].starts_with(b"else") && !is_ident(body[end - 1]) && !body.get(end + 4).copied().is_some_and(is_ident)) + { + break; + } + end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 }; + } + if words(body, name, start, end).is_empty() { + return false; + } + let head = body[..at].trim_ascii_end(); + let conditional = + [&b"if"[..], b"while"].into_iter().any(|k| head.ends_with(k) && !head[..head.len() - k.len()].last().copied().is_some_and(is_ident)); + if conditional { + return let_body(body, start).is_some_and(|(open, close)| open < pos && pos < close); + } + statement_end(body, at) < pos && pos < block_close(body, at) + }); + let loops = words(body, b"for", 0, pos).into_iter().any(|at| { + let Some((open, close)) = let_body(body, at + 3) else { return false }; + let Some(&in_at) = words(body, b"in", at + 3, open).first() else { return false }; + open < pos && pos < close && !words(body, name, at + 3, in_at).is_empty() + }); + lets || loops || closure_binds(body, name, pos) +} + +/// Whether a closure before `pos` takes a parameter that binds `name`, and `pos` lies inside the +/// innermost brackets around the closure (`keeping(|body| keeping(body))`). +fn closure_binds(body: &[u8], name: &[u8], pos: usize) -> bool { + let mut at = 0; + while at < pos { + let head = body[..at].trim_ascii_end(); + let opens = head.last().is_some_and(|c| matches!(c, b'=' | b'(' | b',' | b'{' | b';')) + || [b"move".as_slice(), b"return", b"=>"].iter().any(|word| head.ends_with(word)); + if body[at] == b'|' && opens { + let Some(close) = body[at + 1..].iter().position(|&c| c == b'|').map(|p| at + 1 + p) else { return false }; + let binds = split_args(body, at + 1, close).into_iter().any(|(start, end)| { + let pattern = &body[start..end]; + let end = pattern.iter().position(|&c| c == b':').unwrap_or(pattern.len()); + !words(pattern, name, 0, end).is_empty() + }); + if binds && close < pos { + let group = enclosing_open(body, at).and_then(|o| matching(body, o)).unwrap_or(body.len()); + if pos < group { + return true; + } + } + at = close; + } + at += 1; + } + false +} + +/// The innermost unclosed `(`, `[` or `{` before `at`. +fn enclosing_open(m: &[u8], at: usize) -> Option { + let mut depth = 0usize; + for i in (0..at).rev() { + match m[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth == 0 => return Some(i), + b'(' | b'[' | b'{' => depth -= 1, + _ => {} + } + } + None +} + +/// The bare identifiers, with their offsets, passed as arguments or as tuple or array elements in +/// the body between `open` and `close`. An element of a tuple or array counts only where its value +/// is kept: not in a statement of its own (`(body,);`) or a `let _` or `let _name` binding. +fn passed_names(m: &[u8], open: usize, close: usize) -> Vec<(String, usize)> { let mut names = Vec::new(); let mut at = open + 1; while at < close { @@ -1408,14 +1519,38 @@ fn passed_names(m: &[u8], open: usize, close: usize) -> Vec { let end = at + m[at..close].iter().take_while(|&&c| is_ident(c)).count(); let before = m[..at].trim_ascii_end().last().copied(); let after = m.get(skip_ws(m, end)).copied(); - if matches!(before, Some(b'(' | b',')) && matches!(after, Some(b')' | b',')) { - names.push(String::from_utf8_lossy(&m[at..end]).into_owned()); + if matches!(before, Some(b'(' | b',')) && matches!(after, Some(b')' | b',')) && value_kept(m, open, at) { + names.push((String::from_utf8_lossy(&m[at..end]).into_owned(), at)); } at = end; } names } +/// Whether the element at `at` is a call's argument, or sits in a tuple or array whose statement +/// keeps it ([`passed_names`]). +fn value_kept(m: &[u8], open: usize, at: usize) -> bool { + let Some(group) = enclosing_open(m, at).filter(|&g| g > open) else { return false }; + // A name in a `let` or `for` pattern (`let (body,) = …`) binds a value rather than passing one. + let from = m[open + 1..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(open + 1, |p| open + 2 + p); + if words(m, b"let", from, at).last().is_some_and(|&l| !m[l..at].contains(&b'=')) + || words(m, b"for", from, at).last().is_some_and(|&f| words(m, b"in", f, at).is_empty()) + { + return false; + } + let head = m[..group].trim_ascii_end(); + if m[group] != b'{' && head.last().is_some_and(|&c| is_ident(c) || c == b'!' || c == b'>') { + return true; + } + let statement = m[..group].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let statement = m[statement..group + 1].trim_ascii_start(); + if matches!(statement.first(), Some(b'(' | b'[')) { + return false; + } + // `let _ = …` and `let _name = …` drop or ignore the value. + !statement.strip_prefix(b"let").filter(|r| r.first().is_some_and(u8::is_ascii_whitespace)).is_some_and(|r| r.trim_ascii_start().starts_with(b"_")) +} + /// Whether a function or closure in `body` takes a parameter that binds `name`. fn binds_parameter(body: &[u8], name: &[u8]) -> bool { let binds = |from, to| { @@ -1592,6 +1727,7 @@ fn census(v: &View, helpers: &HashSet) -> Vec { let body = &unmessaged[from - v.t.open..to - v.t.open]; helpers_in(from, to).is_empty() && !rejects(body) + && !panic_rejects(body) && !inside.is_empty() && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm(&m[f..t])).collect::>(), var)) }; @@ -1704,6 +1840,41 @@ fn rejects(body: &[u8]) -> bool { contains(&tight, b".unwrap_err()") || contains(&tight, b".expect_err(") } +/// Whether `body` holds an `if { panic!(…) }` that checks more than presence: it works as +/// `assert!(!)`, so `if accepts(c.invalid) { panic!(…) }` checks a rejection, while +/// `if parse(c).is_err() { panic!(…) }` or `if let Err(_) = parse(c) { panic!(…) }` only enforces +/// success. +fn panic_rejects(body: &[u8]) -> bool { + words(body, b"panic", 0, body.len()).into_iter().any(|at| { + if body.get(skip_ws(body, at + 5)) != Some(&b'!') { + return false; + } + let Some(open) = enclosing_open(body, at).filter(|&o| body[o] == b'{') else { return false }; + let Some(&kw) = words(body, b"if", 0, open).last() else { return false }; + let raw = &body[kw + 2..open]; + if raw.iter().any(|c| matches!(c, b';' | b'{' | b'}')) { + return false; + } + let cond = norm(raw); + if let Some(pattern) = cond.strip_prefix("let") { + // `if let Ok(_) = …` and `if let Some(_) = …` panic on success. + return pattern.starts_with("Ok(") || pattern.starts_with("Some("); + } + let negated = if !top_level_at(&cond, "&&").is_empty() || !top_level_at(&cond, "||").is_empty() { + format!("!({cond})") + } else if let Some(rest) = cond.strip_prefix('!') { + rest.to_owned() + } else if let Some(rest) = cond.strip_suffix(".is_err()") { + format!("{rest}.is_ok()") + } else if let Some(rest) = cond.strip_suffix(".is_none()") { + format!("{rest}.is_some()") + } else { + format!("!{cond}") + }; + !weak_predicate(&negated) + }) +} + /// The `{` that opens a `for` loop's body: the first one outside brackets after `from`. fn loop_open(m: &[u8], from: usize, to: usize) -> Option { let mut i = from; @@ -2052,7 +2223,18 @@ fn touched_after(body: &[u8], name: &str, from: usize, receiver: &str) -> bool { words(body, name.as_bytes(), from, body.len()).into_iter().any(|at| { let rest = norm(&body[at..statement_end(body, at)]); let head = body[..at].trim_ascii_end(); - let shared = head.ends_with(b"&") && !head.ends_with(b"&&"); + // A shared borrow reads the value in an assertion or a named binding; passed to a call in a + // statement of its own (`reset(&r);`), it may change what an interior-mutable value holds. + let statement = body[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let raw = body[statement..at].trim_ascii_start(); + let macro_name = &raw[..raw.iter().take_while(|&&c| is_ident(c)).count()]; + let assertion = raw.get(macro_name.len()) == Some(&b'!') + && PLAIN_ASSERTS.iter().any(|p| macro_name.strip_prefix(p.as_bytes()).is_some_and(|r| r.is_empty() || r.starts_with(b"_"))); + let named_let = raw.starts_with(b"let") + && raw.get(3).is_some_and(u8::is_ascii_whitespace) + && !matches!(raw[3..].trim_ascii_start(), [b'_', c, ..] if !is_ident(*c)); + let checked = assertion || named_let; + let shared = head.ends_with(b"&") && !head.ends_with(b"&&") && checked; let getter = rest .strip_prefix(name) .and_then(|r| r.strip_prefix('.')) @@ -2105,10 +2287,21 @@ fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { let Some(params_close) = (file.get(params_open) == Some(&b'(')).then(|| matching(file, params_open)).flatten() else { return false }; let signature = norm(&file[params_close + 1..body_open]); let return_type = signature.strip_prefix("->").unwrap_or(""); - let refs: Vec = split_args(file, params_open + 1, params_close) - .into_iter() - .filter_map(|(f, t)| norm(&file[f..t]).split_once(':').filter(|(_, ty)| ty.starts_with('&')).map(|(n, _)| n.to_owned())) - .collect(); + // The binding name of each reference parameter, `app` of `mut app: &App`; a parameter whose + // pattern is not a plain name leaves the function out. + let mut refs: Vec = vec![]; + for (f, t) in split_args(file, params_open + 1, params_close) { + let param = String::from_utf8_lossy(&file[f..t]); + let Some((pattern, ty)) = param.split_once(':') else { return false }; + let pattern = pattern.trim(); + let pattern = pattern.strip_prefix("mut").filter(|r| r.starts_with(char::is_whitespace)).map_or(pattern, str::trim_start); + if !plain_local(pattern) { + return false; + } + if norm(ty.as_bytes()).starts_with('&') { + refs.push(pattern.to_owned()); + } + } let body = norm(&file[body_open + 1..body_close]); let table_end = body.bytes().take_while(|&c| is_ident(c) || c == b':').count(); let table = &body[..table_end]; @@ -3343,9 +3536,10 @@ fn reads_source_hits(file: &File) -> Vec { let literal = raw.unwrap_or(&arg); let rs = match word { b"ends_with" => literal == "\".rs\"", - // The last path literal in the argument names the file read: `root.join("src/lib.rs")`, - // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. - b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), + // The literal at the end of the path names the file read: `root.join("src/lib.rs")`, + // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")` or + // `root.join("fixtures.rs").join(name)`. + b"read_to_string" => terminal_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { @@ -3359,11 +3553,61 @@ fn reads_source_hits(file: &File) -> Vec { out } -/// The last string literal in a (whitespace-free) expression, quotes included. -fn last_literal(arg: &str) -> Option<&str> { - let close = arg.rfind('"')?; - let open = arg[..close].rfind('"')?; - Some(&arg[open..=close]) +/// The string literal a (whitespace-free) path expression ends in, quotes included: the expression +/// itself, the last argument of its last call (`root.join("src/lib.rs")`, `concat!(…, "/x.rs")`), +/// the template of `format!`, or the receiver of a call without arguments (`"x.rs".to_owned()`). +/// `None` when that part is not a literal (`root.join(name)`). +fn terminal_literal(arg: &str) -> Option<&str> { + let arg = arg.trim_start_matches('&').trim_end_matches(','); + let literal = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')).unwrap_or(arg); + let b = literal.as_bytes(); + if b.len() >= 2 && b[0] == b'"' && b[b.len() - 1] == b'"' { + // One literal only, not `"a"+"b"`: its first closing quote is the last byte. + let mut i = 1; + while i < b.len() - 1 && b[i] != b'"' { + i += if b[i] == b'\\' { 2 } else { 1 }; + } + return (i == b.len() - 1).then_some(literal); + } + let b = arg.as_bytes(); + let (mut depth, mut in_str, mut i) = (0usize, false, 0usize); + let (mut last_open, mut commas) = (None, vec![]); + while i < b.len() { + let c = b[i]; + if in_str { + if c == b'\\' { + i += 1; + } else if c == b'"' { + in_str = false; + } + } else { + match c { + b'"' => in_str = true, + b'(' | b'[' | b'{' => { + if depth == 0 && c == b'(' { + last_open = Some(i); + commas.clear(); + } + depth += 1; + } + b')' | b']' | b'}' => depth = depth.checked_sub(1)?, + b',' if depth == 1 => commas.push(i), + _ => {} + } + } + i += 1; + } + let open = last_open.filter(|_| depth == 0 && b.last() == Some(&b')'))?; + let close = b.len() - 1; + let starts = std::iter::once(open + 1).chain(commas.iter().map(|c| c + 1)); + let ends = commas.iter().copied().chain([close]); + let pieces: Vec<&str> = starts.zip(ends).map(|(s, e)| &arg[s..e]).filter(|p| !p.is_empty()).collect(); + let head = &arg[..open]; + let Some(&last) = pieces.last() else { + let method = head.trim_end_matches(|c: char| c.is_ascii_alphanumeric() || c == '_'); + return method.strip_suffix('.').and_then(terminal_literal); + }; + terminal_literal(if head.ends_with("format!") { pieces[0] } else { last }) } // ---- Mirrors, echoes, never-run tests and exact pixels ---- @@ -3520,13 +3764,56 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option l => found.map(|(init, _)| init), (Some(_), _) => Some(None), (None, _) => found.map(|(init, _)| init), } } +/// Where the pattern starts of the innermost `match` arm that holds `before` and binds `name`. +fn arm_binding(body: &[u8], name: &str, before: usize) -> Option { + words(body, b"match", 0, before) + .into_iter() + .filter_map(|at| { + let (open, close) = let_body(body, at + 5)?; + if !(open < before && before < close) { + return None; + } + // Walk the arms at the top of the match body to the one `before` is in. + let (mut depth, mut start, mut pattern) = (0usize, open + 1, None); + let mut i = open + 1; + while i < before { + match body[i] { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' => depth = depth.saturating_sub(1), + b'}' => { + depth = depth.saturating_sub(1); + // A block arm ends at its `}` when no `,` follows. + if depth == 0 && pattern.is_some() && !matches!(body.get(skip_ws(body, i + 1)), Some(b',' | b'.' | b'?')) { + (start, pattern) = (i + 1, None); + } + } + b'=' if depth == 0 && pattern.is_none() && body.get(i + 1) == Some(&b'>') => { + pattern = Some((start, i)); + i += 1; + } + b',' if depth == 0 && pattern.is_some() => (start, pattern) = (i + 1, None), + _ => {} + } + i += 1; + } + let (from, to) = pattern?; + let text = String::from_utf8_lossy(&body[from..to]); + // The guard reads names; only the pattern binds them. + let pat = text.split_once(" if ").map_or(text.as_ref(), |(p, _)| p); + (!words(pat.as_bytes(), name.as_bytes(), 0, pat.len()).is_empty()).then_some(skip_ws(body, from)) + }) + .max() +} + /// [`reaching_init`] over `let` bindings alone, with the position of the binding that decides it. fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, usize)>, usize)> { let mut found = None; @@ -3770,8 +4057,8 @@ fn pred_text(src: &[u8]) -> String { } /// The predicates of the `cfg` attributes ([`cfg_attrs`]) whose item holds `pos`, each with the -/// offset of its attribute. `m` is the masked text of `src`. -fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { +/// offsets of its attribute's `cfg` and closing `]`. `m` is the masked text of `src`. +fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { let mut out = vec![]; for CfgAttr { pred, at, end, inner } in cfg_attrs(m, src, 0, m.len()) { let span = if inner { @@ -3787,7 +4074,7 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { } }; if span.0 <= pos && pos <= span.1 { - out.push((pred, at)); + out.push((pred, at, end)); } } out @@ -3834,32 +4121,47 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - let loads = match path_attr(&m, src.as_bytes(), item, at) { - Some(rel) => { - // A `#[path]` outside inline modules is relative to the file's directory; inside them, - // to the inline modules' directory under the file's module. - let mut base = dir.to_owned(); - if !want.chain.is_empty() && !mod_rs { - base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); - } - for seg in want.chain { - base = join_path(&base, seg); - } - join_path(&base, &rel) == want.path + // A `#[path]` outside inline modules is relative to the file's directory; inside them, to + // the inline modules' directory under the file's module. + let resolves = |rel: &str| { + let mut base = dir.to_owned(); + if !want.chain.is_empty() && !mod_rs { + base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); } + for seg in want.chain { + base = join_path(&base, seg); + } + join_path(&base, rel) == want.path + }; + let default = match path_attr(&m, src.as_bytes(), item, at) { + Some(rel) => resolves(&rel), None => &m[start..end] == want.name.as_bytes(), }; - if !loads { - continue; - } + // `#[cfg_attr(, path = "…")]` loads the other file only when the condition holds. + let conditional = cfg_path_attr(&m, src.as_bytes(), item, at); + let gate = match &conditional { + Some((cond, rel, _, _)) => match (resolves(rel), default) { + (true, true) => None, + (true, false) => Some(cond.clone()), + (false, true) => Some(format!("not({cond})")), + (false, false) => continue, + }, + None if default => None, + None => continue, + }; // Inner attributes cover the file, and [`cfgs_over`] reads them. let attrs: Vec = cfg_attrs(&m, src.as_bytes(), item, at).into_iter().filter(|a| !a.inner).collect(); + // Every line of an attribute counts, so an edit to the value line of a multi-line `cfg` does. + let span = |from: usize, to: usize| lines.of(from)..=lines.of(to); at_lines.push(lines.of(at)); - at_lines.extend(attrs.iter().map(|a| lines.of(a.at))); - let mut preds: Vec = attrs.into_iter().map(|a| a.pred).collect(); - for (p, a) in cfgs_over(&m, src.as_bytes(), at) { + at_lines.extend(attrs.iter().flat_map(|a| span(a.at, a.end))); + if let Some((_, _, from, to)) = conditional { + at_lines.extend(span(from, to)); + } + let mut preds: Vec = attrs.into_iter().map(|a| a.pred).chain(gate).collect(); + for (p, a, e) in cfgs_over(&m, src.as_bytes(), at) { preds.push(p); - at_lines.push(lines.of(a)); + at_lines.extend(span(a, e)); } each.push(preds); } @@ -3885,6 +4187,27 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { }) } +/// The condition and path of a `#[cfg_attr(, path = "…")]` attribute in `m[from..to]`, +/// with the offsets of its `cfg_attr` and closing `]`. +fn cfg_path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option<(String, String, usize, usize)> { + words(m, b"cfg_attr", from, to).into_iter().find_map(|at| { + let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + let open = skip_ws(m, at + "cfg_attr".len()); + let close = (attr && m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten()?; + let end = skip_ws(m, close + 1); + if m.get(end) != Some(&b']') { + return None; + } + let text = pred_text(&src[open + 1..close]); + let cuts = top_level_at(&text, ","); + let &first = cuts.first()?; + let starts = cuts.iter().map(|c| c + 1); + let ends = cuts[1..].iter().copied().chain([text.len()]); + let rel = starts.zip(ends).find_map(|(s, e)| text.get(s..e)?.strip_prefix("path=\"")?.strip_suffix('"').map(str::to_owned))?; + Some((text[..first].to_owned(), rel, at, end)) + }) +} + /// `rel` joined to the directory `base`, with `.` and `..` resolved. fn join_path(base: &str, rel: &str) -> String { let mut parts: Vec<&str> = base.split('/').filter(|s| !s.is_empty()).collect(); @@ -3937,57 +4260,66 @@ struct Gates { fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap { let mut out = HashMap::new(); for path in paths { - let (mut gates, mut at) = (Gates::default(), path.clone()); - 'up: for _ in 0..16 { - let Some((name, mut candidates)) = module_parent(&at) else { break }; - let name = name.to_owned(); - let file = at.rsplit_once('/').map_or(at.as_str(), |(_, f)| f); - let Some(mut module_dir) = (if file == "mod.rs" { - at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) - } else { - at.rsplit_once('/').map(|(d, _)| d.to_owned()) - }) else { - break; - }; - let mut chain: Vec = vec![]; - for _ in 0..4 { - let want = Loaded { path: &at, name: &name, chain: &chain }; - // Every file that loads the module is another way in (a library and a binary root - // can both load it): its tests are off only when every one of them leaves them out. - let found: Vec<_> = - candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))).collect(); - if let Some(parent) = found.first().map(|(p, _)| p.clone()) { - if let [(_, (preds, _))] = found.as_slice() { - gates.preds.extend(preds.iter().cloned()); - } else { - let each: Vec = found.iter().map(|(_, (p, _))| format!("all({})", p.join(","))).collect(); - gates.preds.push(format!("any({})", each.join(","))); - } - gates.sources.extend(found.into_iter().map(|(p, (_, lines))| (p, lines))); - at = parent; - continue 'up; - } - let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break 'up }; - let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break 'up }; - chain.insert(0, seg); - candidates = next; - module_dir = up; - } - break; - } - if !gates.preds.is_empty() { - out.insert(path.clone(), gates); + let mut sources = vec![]; + let preds = route_preds(path, read, &mut sources, 0); + if !preds.is_empty() { + out.insert(path.clone(), Gates { preds, sources }); } } out } +/// The predicates under which the module file `at` is loaded. Every file that loads it is another +/// way in (a library and a binary root can both load it): each route joins the gates of its own +/// declaration with those of the file that holds it, and the routes join into one `any(all(…), …)`, +/// so its tests are off only when every route leaves them out. The lines of each declaration go to +/// `sources`. +fn route_preds(at: &str, read: &dyn Fn(&str) -> Option, sources: &mut Vec<(String, Vec)>, depth: usize) -> Vec { + if depth >= 16 { + return vec![]; + } + let Some((name, mut candidates)) = module_parent(at) else { return vec![] }; + let file = at.rsplit_once('/').map_or(at, |(_, f)| f); + let Some(mut module_dir) = (if file == "mod.rs" { + at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) + } else { + at.rsplit_once('/').map(|(d, _)| d.to_owned()) + }) else { + return vec![]; + }; + let mut chain: Vec = vec![]; + for _ in 0..4 { + let want = Loaded { path: at, name, chain: &chain }; + let found: Vec<_> = candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))).collect(); + if !found.is_empty() { + let mut routes: Vec> = vec![]; + for (parent, (mut preds, lines)) in found { + sources.push((parent.clone(), lines)); + preds.extend(route_preds(&parent, read, sources, depth + 1)); + routes.push(preds); + } + return match routes.len() { + 1 => routes.pop().unwrap_or_default(), + _ if routes.iter().any(Vec::is_empty) => vec![], + _ => vec![format!("any({})", routes.iter().map(|r| format!("all({})", r.join(","))).collect::>().join(","))], + }; + } + let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { return vec![] }; + let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { return vec![] }; + chain.insert(0, seg); + candidates = next; + module_dir = up; + } + vec![] +} + /// A test that a `cfg` compiles out on every target CI runs tests on. fn never_run(v: &View, ctx: &Ctx) -> Option { let local = cfgs_over(&v.file.m, v.file.src, v.t.fn_at); // A change to an attribute that turns the test off counts as a change to the test. - let attr_lines: Vec = local.iter().map(|&(_, at)| v.file.lines.of(at)).collect(); - let mut preds: Vec = local.into_iter().map(|(p, _)| p).collect(); + // Every line of a multi-line attribute counts. + let attr_lines: Vec = local.iter().flat_map(|&(_, at, end)| v.file.lines.of(at)..=v.file.lines.of(end)).collect(); + let mut preds: Vec = local.into_iter().map(|(p, _, _)| p).collect(); preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); if preds.is_empty() { return None; @@ -4034,15 +4366,25 @@ fn names_rect(op: &str) -> bool { return false; } let b = op.as_bytes(); + // For each open parenthesis, whether it opens a call's arguments rather than a tuple or group. + let mut calls: Vec = vec![]; let mut i = 0; while i < b.len() { + match b[i] { + b'(' => calls.push(i > 0 && (is_ident(b[i - 1]) || b[i - 1] == b'!' || b[i - 1] == b'>')), + b')' => { + calls.pop(); + } + _ => {} + } if !is_ident(b[i]) || (i > 0 && is_ident(b[i - 1])) { i += 1; continue; } let end = i + b[i..].iter().take_while(|&&c| is_ident(c)).count(); let w = &op[i..end]; - if w == "rect" || w.starts_with("rect_") || w.ends_with("_rect") { + // A rect read inside a call's arguments (`bucket(rect.min.x)`) is the call's input, not the operand. + if (w == "rect" || w.starts_with("rect_") || w.ends_with("_rect")) && !calls.contains(&true) { let mut after = end; if b.get(after) == Some(&b'(') { after = matching(b, after).map_or(b.len(), |c| c + 1); @@ -4256,6 +4598,12 @@ mod tests { assert_eq!(census_in(&generic, &with_helpers), [], "a helper called with a turbofish"); let enforced = "#[test]\nfn t() {\n for case in CASES {\n assert!(!case.is_empty());\n let Ok(_) = parse(case) else { panic!(\"parse failed\") };\n }\n}\n"; assert_eq!(census_in(enforced, &ctx()), [(2, "census")], "a panic that only enforces success"); + let panics = "#[test]\nfn t() {\n for c in CASES {\n assert!(c.valid.is_some());\n if accepts(c.invalid) {\n panic!(\"accepted invalid input\");\n }\n }\n}\n"; + assert_eq!(census_in(panics, &ctx()), [], "a panic when invalid input is accepted checks a rejection"); + for enforcing in ["parse(c.valid).is_err()", "!parse(c.valid).is_ok()", "let Err(_) = parse(c.valid)"] { + let src = panics.replace("accepts(c.invalid)", enforcing); + assert_eq!(census_in(&src, &ctx()), [(2, "census")], "{enforcing}: a panic that only enforces success"); + } let mapped = "#[test]\nfn t() {\n assert!(COLORS.iter().map(|c| { verify_entry(c); c }).all(|c| c.is_some()));\n}\n"; assert_eq!(census_in(mapped, &ctx()), [], "a helper in the .all(…) receiver runs for every entry"); assert_eq!(census_in(&mapped.replace("verify_entry(c); ", ""), &ctx()), [(2, "census")]); @@ -5604,6 +5952,20 @@ mod tests { assert_eq!(hits_in("crates/x/src/tests.rs", &closure, &ctx), [(8, "no-assertion")], "a closure parameter shadows the asserting helper"); let parameter = src.replace("fn t()", "fn t(body: fn())"); assert_eq!(hits_in("crates/x/src/tests.rs", ¶meter, &ctx), [(8, "no-assertion")], "a function parameter shadows the asserting helper"); + let later = src.replace(" keeping(body);", " keeping(body);\n {\n let body = || {};\n let _ = body;\n }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &later, &ctx), [], "a binding in a later block does not reach the call"); + let after = src.replace(" keeping(body);", " keeping(body);\n let body = || {};\n let _ = body;"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after, &ctx), [], "a binding after the call"); + let looped = src.replace(" keeping(body);", " for body in [|| {}] {\n keeping(body);\n }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &looped, &ctx), [(8, "no-assertion")], "a loop pattern shadows the helper in the loop body"); + let after_loop = src.replace(" keeping(body);", " for body in [|| {}] {\n let _ = body;\n }\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after_loop, &ctx), [], "the helper after the loop"); + let unused = src.replace(" keeping(body);", " let _unused = (body,);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &unused, &ctx), [(8, "no-assertion")], "a tuple that is never called"); + let dropped = src.replace(" keeping(body);", " (body,);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &dropped, &ctx), [(8, "no-assertion")], "a tuple in a statement of its own"); + let table = src.replace(" keeping(body);", " let cases = [(\"case\", body)];\n run(&cases);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &table, &ctx), [], "a table of named cases"); let idle = src.replace("assert_eq!(f(), 1);", "f();"); let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), idle.clone())]), ..Ctx::default() }; assert_eq!(hits_in("crates/x/src/tests.rs", &idle, &ctx), [(8, "no-assertion")], "a passed body that checks nothing"); @@ -5628,6 +5990,10 @@ mod tests { assert_eq!(hits(&early), [(6, "all-unguarded")], "the receiver changed between the binding and the assertion"); let taken = pinned.replace(" assert!(r.items()", " assert!(r.take_items().is_some());\n assert!(r.items()"); assert_eq!(hits(&taken), [(6, "all-unguarded")], "an assertion changes the receiver after the pinning assertion"); + let reset = pinned.replace(" assert!(r.items()", " reset(&r);\n assert!(r.items()"); + assert_eq!(hits(&reset), [(6, "all-unguarded")], "a shared borrow passed to a call may change interior-mutable items"); + let bound = pinned.replace(" assert!(r.items()", " let n = count(&r);\n assert!(r.items()"); + assert_eq!(hits(&bound), [], "a shared borrow read into a binding"); let counted = pinned.replace(" assert!(r.items()", " assert_eq!(r.unhandled_rejection_count(), 2);\n assert!(r.items()"); assert_eq!(hits(&counted), [], "a count getter preserves the pinned source"); let chained = pinned.replace(".map(|j| j.n)", ".map(|j| j.n).chain([1])"); @@ -5652,6 +6018,10 @@ mod tests { assert_eq!(hits(&shadowed), [(8, "all-unguarded")], "a local binding shadows the file's function"); let state = src.replace("filter(|r| r.wide == wide)", "filter(|r| app.has(r))"); assert_eq!(hits(&state), [(7, "all-unguarded")], "a filter on the state the test builds"); + let mut_ref = src.replace("app: &App", "mut app: &App").replace("filter(|r| r.wide == wide)", "filter(|r| app.has(r))"); + assert_eq!(hits(&mut_ref), [(7, "all-unguarded")], "a filter on a `mut` reference parameter"); + let pattern = src.replace("app: &App, wide: bool", "(app, wide): (&App, bool)").replace("reasons(&app, true)", "reasons((&app, true))"); + assert_eq!(hits(&pattern), [(7, "all-unguarded")], "a parameter pattern that is not a plain name"); let mapped = src.replace(".filter(|r| r.wide == wide).map(|r| app.reason(r))", ".map(|r| app.reason(r)).filter(|r| r.is_some())"); assert_eq!(hits(&mapped), [(7, "all-unguarded")], "a filter on values mapped from that state"); let map_while = src.replace(".filter(|r| r.wide == wide).map(|r| app.reason(r))", ".map_while(|r| app.reason(r))"); @@ -5923,6 +6293,63 @@ mod tests { assert_eq!(declared(twice, &child), Some(vec!["any(all(target_os=\"macos\"),all(target_os=\"linux\"))".to_owned()])); let attr = "#[cfg_attr(unix, cfg(target_os = \"macos\"))]\nmod child;\n"; assert_eq!(declared(attr, &child), Some(vec!["any(not(unix),target_os=\"macos\")".to_owned()])); + let conditional = "#[cfg_attr(unix, path = \"portable.rs\")]\nmod imp;\n"; + assert_eq!(declared(conditional, &imp), Some(vec!["not(unix)".to_owned()]), "unix loads portable.rs instead"); + let portable = Loaded { path: "src/portable.rs", name: "portable", chain: &[] }; + assert_eq!(declared(conditional, &portable), Some(vec!["unix".to_owned()]), "the conditional path"); + assert_eq!(declared("#[path = \"portable.rs\"]\nmod imp;\n", &portable), Some(vec![]), "a plain `#[path]`"); + } + + #[test] + fn deleting_the_last_ci_route_counts_for_the_child_tests() { + let gates_of = |lib: &str, main: &str| { + let files: HashMap<&str, String> = + [("crates/x/src/lib.rs", lib.to_owned()), ("crates/x/src/main.rs", main.to_owned()), ("crates/x/src/child.rs", String::new())] + .into_iter() + .collect(); + module_gates(&["crates/x/src/child.rs".to_owned()], &|p: &str| files.get(p).cloned()).remove("crates/x/src/child.rs") + }; + let mac = "#[cfg(target_os = \"macos\")]\nmod child;\n"; + let main: BTreeMap>> = + [("crates/x/src/main.rs".to_owned(), Some([1].into_iter().collect()))].into_iter().collect(); + let (then, now) = (gates_of(mac, "mod child;\n"), gates_of(mac, "")); + assert!(!gate_changed(now.as_ref(), &main), "no line of the remaining route changed"); + assert!(gates_moved(now.as_ref(), then.as_ref(), &main), "the unconditional route is gone"); + let other: BTreeMap>> = + [("crates/x/src/main.rs".to_owned(), Some([2].into_iter().collect()))].into_iter().collect(); + let (then, now) = (gates_of(mac, "mod child;\nmod other;\n"), gates_of(mac, "mod child;\n")); + assert!(!gates_moved(now.as_ref(), then.as_ref(), &other), "a CI route remains"); + } + + #[test] + fn a_parent_edit_compares_tests_by_name_and_line() { + let path = "crates/x/src/child.rs"; + let src = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn smoke() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn smoke() {\n assert_eq!(f(), 1);\n }\n}\n"; + let now = Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }; + let off: Vec<(usize, String)> = newly_off(path, src, &now, &ctx()).into_iter().map(|h| (h.line, h.test)).collect(); + assert_eq!(off, [(10, "smoke".to_owned())], "b::smoke ran before; a::smoke was already off"); + } + + #[test] + fn each_load_route_keeps_its_own_ancestor_gates() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"platform/mod.rs\"]\nmod platform;\n"), + ("crates/x/src/main.rs", "#[path = \"platform.rs\"]\nmod platform;\n"), + ("crates/x/src/platform/mod.rs", "mod child;\n"), + ("crates/x/src/platform.rs", "mod child;\n"), + ("crates/x/src/platform/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/platform/child.rs".to_owned()], &read); + assert_eq!(gates.get("crates/x/src/platform/child.rs").map(|g| g.preds.clone()), None, "main.rs loads it on every target"); + // Without main.rs's declaration, nothing loads platform.rs. + let mac = + files.iter().map(|(&p, &s)| (p, if p.ends_with("main.rs") || p.ends_with("platform.rs") { "" } else { s })).collect::>(); + let read = |p: &str| mac.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/platform/child.rs".to_owned()], &read); + assert_eq!(gates.get("crates/x/src/platform/child.rs").map(|g| g.preds.clone()), Some(vec!["target_os=\"macos\"".to_owned()])); } #[test] @@ -5949,6 +6376,17 @@ mod tests { assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[2])), "the cfg line"); assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "the declaration line"); assert!(!gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[1])), "another declaration"); + let multi: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "mod plain;\n#[cfg(\n target_os = \"macos\"\n)]\nmod child;\n"), ("crates/x/src/child.rs", "")] + .into_iter() + .collect(); + let read = |p: &str| multi.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read); + assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "the value line of a multi-line cfg"); + let local = "#[cfg(\n target_os = \"macos\"\n)]\nmod mac {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", local, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(touches(hit, Some(&[2].into_iter().collect())), "the value line of a multi-line cfg on the inline module"); } #[test] @@ -5984,6 +6422,8 @@ mod tests { assert_eq!(px("assert_eq!(dock_rect.width(), 120.0);"), [(4, "exact-pixel")], "a name that only starts with doc"); assert_eq!(px("assert_eq!((rect.x0, rect.y0), (200.0, 200.0));"), [], "document corners"); assert_eq!(px("assert_eq!(rgb8(&fill_color(&app, rect)), [255, 255, 255]);"), [], "a rect passed on"); + assert_eq!(px("assert_eq!(bucket(rect.min.x), 3);"), [], "a coordinate passed to a call"); + assert_eq!(px("assert_eq!((rect.min.x, rect.min.y), (1.0, 2.0));"), [(4, "exact-pixel")], "a tuple of coordinates"); let engine = "#[test]\nfn t() {\n assert_eq!(art_rect.width(), 10.0);\n}\n"; assert_eq!(only("exact-pixel", engine), [], "document geometry outside UI code"); } @@ -5998,6 +6438,13 @@ mod tests { assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment"); let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file"); + assert_eq!(only("reads-source", &dir.replace("\"data.json\"", "name")), [], "a file name the test does not spell out"); + assert_eq!(only("reads-source", &dir.replace(".join(\"data.json\")", "")), [(3, "reads-source")], "a literal final join"); + let formatted = + "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{dir}/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", formatted), [(3, "reads-source")], "a format! template"); + let concat = "#[test]\nfn t() {\n let s = fs::read_to_string(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", concat), [(3, "reads-source")], "a concat! of literals"); let split = "#[test]\nfn t() {\n let s = fs::read_to_string(\n \"src/lib.rs\",\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; let found = lint_file("crates/x/src/tests.rs", split, &ctx()); let hit = found.iter().find(|h| h.rule == Rule::ReadsSource).unwrap(); @@ -6021,6 +6468,16 @@ mod tests { assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); } + #[test] + fn a_match_arm_binding_shadows_the_outer_one_in_its_arm() { + let arm = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(n) => assert_eq!(n, 1),\n None => {}\n }\n}\n"; + assert_eq!(only("fixture-only", arm), []); + let block = arm.replace("Some(n) => assert_eq!(n, 1),", "Some(n) => {\n assert_eq!(n, 1);\n }"); + assert_eq!(only("fixture-only", &block), [], "a block arm"); + let after = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(n) => consume(n),\n None => {}\n }\n assert_eq!(n, 0);\n}\n"; + assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the match"); + } + #[test] fn nested_cfg_attr_gates_apply() { let nested = "#[cfg_attr(unix, cfg_attr(test, cfg(target_os = \"macos\")))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; From 06828e647f643374d2c53f43c07061329df9332a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 14:44:51 -0800 Subject: [PATCH 04/11] xtask: test-lint ends closure scopes and drops unsound all-unguarded guards - A closure parameter shadows a name only inside the closure's body, so a helper passed after `let _cb = |body| { ... };` counts again, and a closure parameter no longer resolves to an outer literal for `fixture-only`. - `if (parse(x).is_err()) { panic!(...) }` is read without its parentheses, so it counts as a success check, not a rejection. - An equality assertion guards `.all(...)` only when it compares the same call the receiver is bound to, or a snapshot of the receiver that nothing changes before the assertion. - A function over a constant table guards `.all(...)` only when it keeps every row of a table the file declares with a non-zero length; a filter can drop every row. - `ends_with(".rs")` is a `reads-source` hit only in a file that lists a directory (`read_dir`, `walkdir`, `glob`, `git ls-files`), and a `read_to_string` path follows the last argument only of path builders (`join`, `Path::new`, `PathBuf::from`, `format!`, `concat!`). - `never-run` skips later attributes that hold `;`, such as `#[test_case(1; "one")]`, and joins inline load routes from further up with the file that declares the module directly. - A deleted file keeps its old path in the change map, so the files below a deleted parent are checked. --- xtask/src/test_lint.rs | 293 +++++++++++++++++++++++++++-------------- 1 file changed, 193 insertions(+), 100 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index e31150df25..ddc40bf920 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -539,19 +539,21 @@ fn changed_lines(root: &Path, base: &str) -> Result BTreeMap>> { let mut out: BTreeMap>> = BTreeMap::new(); - let mut current: Option = None; + let (mut current, mut old_path): (Option, Option) = (None, None); // Inside a file's header (from `diff --git` to its first hunk), where `+++ ` names the file. let (mut header, mut new_file) = (false, false); for line in diff.lines() { if line.starts_with("diff --git ") { - (header, new_file) = (true, false); + (header, new_file, old_path) = (true, false, None); } else if header && line.starts_with("new file mode") { new_file = true; + } else if let Some(path) = line.strip_prefix("--- ").filter(|_| header) { + old_path = patch_path(path).and_then(|p| p.strip_prefix("a/").map(str::to_owned)); } else if let Some(path) = line.strip_prefix("+++ ").filter(|_| header) { - current = patch_path(path).and_then(|p| p.strip_prefix("b/").map(str::to_owned)); + current = if path == "/dev/null" { old_path.clone() } else { patch_path(path).and_then(|p| p.strip_prefix("b/").map(str::to_owned)) }; if let Some(p) = ¤t { out.insert(p.clone(), if new_file { None } else { Some(BTreeSet::new()) }); } @@ -1464,31 +1466,57 @@ fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool { } /// Whether a closure before `pos` takes a parameter that binds `name`, and `pos` lies inside the -/// innermost brackets around the closure (`keeping(|body| keeping(body))`). +/// closure's body (`keeping(|body| keeping(body))`). fn closure_binds(body: &[u8], name: &[u8], pos: usize) -> bool { - let mut at = 0; + closure_binding(body, name, pos).is_some() +} + +/// The opening `|` of the innermost closure whose parameters bind `name` and whose body holds `pos`. +fn closure_binding(body: &[u8], name: &[u8], pos: usize) -> Option { + let (mut at, mut found) = (0, None); while at < pos { let head = body[..at].trim_ascii_end(); let opens = head.last().is_some_and(|c| matches!(c, b'=' | b'(' | b',' | b'{' | b';')) || [b"move".as_slice(), b"return", b"=>"].iter().any(|word| head.ends_with(word)); if body[at] == b'|' && opens { - let Some(close) = body[at + 1..].iter().position(|&c| c == b'|').map(|p| at + 1 + p) else { return false }; + let Some(close) = body[at + 1..].iter().position(|&c| c == b'|').map(|p| at + 1 + p) else { return found }; let binds = split_args(body, at + 1, close).into_iter().any(|(start, end)| { let pattern = &body[start..end]; let end = pattern.iter().position(|&c| c == b':').unwrap_or(pattern.len()); !words(pattern, name, 0, end).is_empty() }); - if binds && close < pos { - let group = enclosing_open(body, at).and_then(|o| matching(body, o)).unwrap_or(body.len()); - if pos < group { - return true; - } + if binds && close < pos && pos < closure_end(body, close) { + found = Some(at); } at = close; } at += 1; } - false + found +} + +/// The end of the closure whose parameter list closes at `bar`: past the `}` of a block body, else at +/// the `,` or `;` that ends the expression or the bracket that holds it. +fn closure_end(body: &[u8], bar: usize) -> usize { + let mut i = bar + 1; + while i < body.len() && body[i].is_ascii_whitespace() { + i += 1; + } + if body[i..].starts_with(b"->") { + // A closure with a return type has a block body. + return body[i..].iter().position(|&c| c == b'{').and_then(|p| matching(body, i + p)).map_or(body.len(), |c| c + 1); + } + if body.get(i) == Some(&b'{') { + return matching(body, i).map_or(body.len(), |c| c + 1); + } + while i < body.len() { + match body[i] { + b'(' | b'[' | b'{' => i = matching(body, i).map_or(body.len(), |c| c + 1), + b',' | b';' | b')' | b']' | b'}' => return i, + _ => i += 1, + } + } + body.len() } /// The innermost unclosed `(`, `[` or `{` before `at`. @@ -1855,15 +1883,16 @@ fn panic_rejects(body: &[u8]) -> bool { if raw.iter().any(|c| matches!(c, b';' | b'{' | b'}')) { return false; } - let cond = norm(raw); + let normed = norm(raw); + let cond = unparenthesized(&normed); if let Some(pattern) = cond.strip_prefix("let") { // `if let Ok(_) = …` and `if let Some(_) = …` panic on success. return pattern.starts_with("Ok(") || pattern.starts_with("Some("); } - let negated = if !top_level_at(&cond, "&&").is_empty() || !top_level_at(&cond, "||").is_empty() { + let negated = if !top_level_at(cond, "&&").is_empty() || !top_level_at(cond, "||").is_empty() { format!("!({cond})") } else if let Some(rest) = cond.strip_prefix('!') { - rest.to_owned() + unparenthesized(rest).to_owned() } else if let Some(rest) = cond.strip_suffix(".is_err()") { format!("{rest}.is_ok()") } else if let Some(rest) = cond.strip_suffix(".is_none()") { @@ -2168,12 +2197,12 @@ fn positive_all(cond: &str, test_body: &[u8], sizes: &Sizes) -> bool { /// Whether an earlier equality assertion compares what `receiver` is made from with a non-empty /// literal: a plain local whose binding reads `receiver` (`let got = r.items()….collect(); -/// assert_eq!(got, [a, b])` before `r.items().iter().all(…)`), or a call on the same plain local -/// as the call `receiver` is bound to (`let gaps = gaps(&word); assert_eq!(ids(&word), [a, b, c])`). +/// assert_eq!(got, [a, b])` before `r.items().iter().all(…)`, with `got` unchanged in between), or +/// the same call `receiver` is bound to (`let gaps = gaps(&word); assert_eq!(gaps(&word), [a, b])`). fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { let r = array_receiver(receiver); let init = |name: &str, at: usize| let_init(body, name, at).and_then(|(init, _)| init); - // For a receiver bound to `f(&x)`: `x`, and where the binding of `x` it reads ends. + // For a receiver bound to `f(&x)`: the call `f(&x)`, `x`, and where the binding of `x` it reads ends. let source = if plain_local(r) { let_init(body, r, body.len()).and_then(|(init, bound)| { let (text, _) = init?; @@ -2182,7 +2211,7 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { return None; } let at = let_init(body, &s, bound).map_or(0, |(_, at)| statement_end(body, at)); - Some((s, at)) + Some((norm(text.as_bytes()), s, at)) }) } else { None @@ -2196,13 +2225,20 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { if literal_len(literal, sizes) == 0 { return false; } - // The binding keeps the receiver's items (`r.items().iter().map(…).collect()`), and - // nothing changes the receiver's source from the binding on. + // The binding keeps the receiver's items (`r.items().iter().map(…).collect()`), nothing + // changes the binding before the assertion, and nothing changes the receiver's source + // from the binding on. let read = !plain_local(r) && plain_local(pinned) - && init(pinned, a.at) - .is_some_and(|(text, at)| keeping_base(&text, true) == r && !touched_after(body, root_local(r), statement_end(body, at), r)); - read || source.as_ref().is_some_and(|(s, at)| single_local_arg(pinned) == Some(s.as_str()) && !touched_after(body, s, *at, r)) + && init(pinned, a.at).is_some_and(|(text, at)| { + let bound = statement_end(body, at); + keeping_base(&text, true) == r + && !touched_after(&body[..a.at], pinned, bound, pinned) + && !touched_after(body, root_local(r), bound, r) + }); + // The assertion compares the same call the receiver is bound to (`gaps(&word)`), so its + // literal is what the receiver holds. + read || source.as_ref().is_some_and(|(call, s, at)| pinned == call && !touched_after(body, s, *at, r)) }) }) } @@ -2261,10 +2297,10 @@ fn single_local_arg(call: &str) -> Option<&str> { plain_local(arg).then_some(arg) } -/// Whether `receiver` calls a function of the file whose body lists a constant table -/// (`TABLE.iter()…`, `Kind::ALL.iter()…`) and filters it only on parameters that are not -/// references: which rows it gives depends on the table and plain values, not on the state the -/// test builds. +/// Whether `receiver` calls a function of the file whose body lists every row of a non-empty +/// constant table of the file (`const TABLE: [T; 3]`, `TABLE.iter()…`) without filtering it: the +/// call gives at least one row whatever state the test builds. A filter, even one on plain values, +/// may drop every row, so it leaves the function out. fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { let r = array_receiver(receiver); let Some(open) = r.find('(') else { return false }; @@ -2287,35 +2323,15 @@ fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { let Some(params_close) = (file.get(params_open) == Some(&b'(')).then(|| matching(file, params_open)).flatten() else { return false }; let signature = norm(&file[params_close + 1..body_open]); let return_type = signature.strip_prefix("->").unwrap_or(""); - // The binding name of each reference parameter, `app` of `mut app: &App`; a parameter whose - // pattern is not a plain name leaves the function out. - let mut refs: Vec = vec![]; - for (f, t) in split_args(file, params_open + 1, params_close) { - let param = String::from_utf8_lossy(&file[f..t]); - let Some((pattern, ty)) = param.split_once(':') else { return false }; - let pattern = pattern.trim(); - let pattern = pattern.strip_prefix("mut").filter(|r| r.starts_with(char::is_whitespace)).map_or(pattern, str::trim_start); - if !plain_local(pattern) { - return false; - } - if norm(ty.as_bytes()).starts_with('&') { - refs.push(pattern.to_owned()); - } - } let body = norm(&file[body_open + 1..body_close]); let table_end = body.bytes().take_while(|&c| is_ident(c) || c == b':').count(); let table = &body[..table_end]; - let screaming = table - .rsplit("::") - .next() - .is_some_and(|last| !last.is_empty() && last.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')); - if !screaming || !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()")) { + let screaming = !table.is_empty() && table.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_'); + if !screaming || item_len(table, sizes) == 0 || !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()")) { return false; } - // The body is the chain alone, of steps that keep or filter rows; everything up to the end - // of the last `filter`, maps before it included, reads no reference parameter. + // The body is the chain alone, of steps that keep every row. let mut at = table_end; - let mut decided = 0; while at < body.len() { let Some(rest) = body[at..].strip_prefix('.') else { return false }; let method_len = rest.bytes().take_while(|&c| is_ident(c)).count(); @@ -2335,13 +2351,11 @@ fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { return false; } } - "filter" => decided = close + 1, _ => return false, } at = close + 1; } - let decided = &body[..decided]; - refs.iter().all(|p| words(decided.as_bytes(), p.as_bytes(), 0, decided.len()).is_empty()) + true }) } @@ -3520,6 +3534,9 @@ fn reads_source_hits(file: &File) -> Vec { let m = &file.m; // The source with comments blanked and literals kept: a path in a comment is not read. let code = mask_parts(&String::from_utf8_lossy(file.src), true, false); + // A suffix check keeps Rust files only where the file lists a directory; elsewhere + // `ends_with(".rs")` may test any text, such as a rendered command line. + let walks = ["read_dir", "WalkDir", "walkdir", "ls-files", "glob"].iter().any(|w| !words(&code, w.as_bytes(), 0, code.len()).is_empty()); let mut out = vec![]; let words_and_notes = [ (&b"include_str"[..], "includes a .rs file as text"), @@ -3535,7 +3552,7 @@ fn reads_source_hits(file: &File) -> Vec { let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); let literal = raw.unwrap_or(&arg); let rs = match word { - b"ends_with" => literal == "\".rs\"", + b"ends_with" => walks && literal == "\".rs\"", // The literal at the end of the path names the file read: `root.join("src/lib.rs")`, // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")` or // `root.join("fixtures.rs").join(name)`. @@ -3603,11 +3620,22 @@ fn terminal_literal(arg: &str) -> Option<&str> { let ends = commas.iter().copied().chain([close]); let pieces: Vec<&str> = starts.zip(ends).map(|(s, e)| &arg[s..e]).filter(|p| !p.is_empty()).collect(); let head = &arg[..open]; + let ident = |c: char| c.is_ascii_alphanumeric() || c == '_'; + let callee = head.strip_suffix('!').unwrap_or(head); + let receiver = callee.trim_end_matches(ident); + let name = &callee[receiver.len()..]; let Some(&last) = pieces.last() else { - let method = head.trim_end_matches(|c: char| c.is_ascii_alphanumeric() || c == '_'); - return method.strip_suffix('.').and_then(terminal_literal); + // A conversion keeps the path its receiver names: `"x.rs".to_owned()`. + let converts = ["to_owned", "to_string", "into", "as_ref", "to_path_buf", "as_path", "clone"].contains(&name); + return receiver.strip_suffix('.').filter(|_| converts && !head.ends_with('!')).and_then(terminal_literal); }; - terminal_literal(if head.ends_with("format!") { pieces[0] } else { last }) + // Only calls that build a path from their arguments name the file in them; others, such as + // `"data.json.rs".trim_end_matches(".rs")`, change the text in other ways. + let builds = if head.ends_with('!') { ["format", "concat"].contains(&name) } else { ["join", "new", "from", "with_file_name"].contains(&name) }; + if !builds { + return None; + } + terminal_literal(if name == "format" { pieces[0] } else { last }) } // ---- Mirrors, echoes, never-run tests and exact pixels ---- @@ -3764,8 +3792,9 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option l => found.map(|(init, _)| init), (Some(_), _) => Some(None), @@ -4066,7 +4095,12 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { let enclosing = m[..at].iter().rposition(|&c| c == b'{'); enclosing.and_then(|o| matching(m, o).map(|c| (o, c))).unwrap_or((0, m.len())) } else { - let after = end + 1; + // Later attributes can hold `;` (`#[test_case(1; "one")]`); skip them whole. + let mut after = end + 1; + while m[skip_ws(m, after)..].starts_with(b"#[") { + let Some(close) = matching(m, skip_ws(m, after) + 1) else { break }; + after = close + 1; + } let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; match (m[open], matching(m, open)) { (b'{', Some(close)) => (at, close), @@ -4287,30 +4321,30 @@ fn route_preds(at: &str, read: &dyn Fn(&str) -> Option, sources: &mut Ve }) else { return vec![]; }; + // Routes from every level: a file declaring `mod ;` directly, and files further up that + // declare it inside inline modules (`mod platform { mod child; }`). let mut chain: Vec = vec![]; + let mut routes: Vec> = vec![]; for _ in 0..4 { let want = Loaded { path: at, name, chain: &chain }; let found: Vec<_> = candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))).collect(); - if !found.is_empty() { - let mut routes: Vec> = vec![]; - for (parent, (mut preds, lines)) in found { - sources.push((parent.clone(), lines)); - preds.extend(route_preds(&parent, read, sources, depth + 1)); - routes.push(preds); - } - return match routes.len() { - 1 => routes.pop().unwrap_or_default(), - _ if routes.iter().any(Vec::is_empty) => vec![], - _ => vec![format!("any({})", routes.iter().map(|r| format!("all({})", r.join(","))).collect::>().join(","))], - }; + for (parent, (mut preds, lines)) in found { + sources.push((parent.clone(), lines)); + preds.extend(route_preds(&parent, read, sources, depth + 1)); + routes.push(preds); } - let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { return vec![] }; - let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { return vec![] }; + let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break }; + let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break }; chain.insert(0, seg); candidates = next; module_dir = up; } - vec![] + match routes.len() { + 0 => vec![], + 1 => routes.pop().unwrap_or_default(), + _ if routes.iter().any(Vec::is_empty) => vec![], + _ => vec![format!("any({})", routes.iter().map(|r| format!("all({})", r.join(","))).collect::>().join(","))], + } } /// A test that a `cfg` compiles out on every target CI runs tests on. @@ -4600,7 +4634,15 @@ mod tests { assert_eq!(census_in(enforced, &ctx()), [(2, "census")], "a panic that only enforces success"); let panics = "#[test]\nfn t() {\n for c in CASES {\n assert!(c.valid.is_some());\n if accepts(c.invalid) {\n panic!(\"accepted invalid input\");\n }\n }\n}\n"; assert_eq!(census_in(panics, &ctx()), [], "a panic when invalid input is accepted checks a rejection"); - for enforcing in ["parse(c.valid).is_err()", "!parse(c.valid).is_ok()", "let Err(_) = parse(c.valid)"] { + let rejecting = panics.replace("accepts(c.invalid)", "(parse(c.invalid).is_ok())"); + assert_eq!(census_in(&rejecting, &ctx()), [], "a panic on a parenthesized is_ok checks a rejection"); + for enforcing in [ + "parse(c.valid).is_err()", + "!parse(c.valid).is_ok()", + "let Err(_) = parse(c.valid)", + "(parse(c.valid).is_err())", + "!(parse(c.valid).is_ok())", + ] { let src = panics.replace("accepts(c.invalid)", enforcing); assert_eq!(census_in(&src, &ctx()), [(2, "census")], "{enforcing}: a panic that only enforces success"); } @@ -5671,8 +5713,13 @@ mod tests { fn reading_rust_source_is_reported_outside_the_audits() { let bad = "#[test]\nfn t() {\n let src = include_str!(\"../lib.rs\");\n assert_eq!(src.matches(\"x\").count(), 1);\n}\n"; assert_eq!(hits(bad), [(3, "reads-source")]); - let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(\".rs\")).count();\n assert_eq!(n, 4);\n}\n"; + let walk = + "#[test]\nfn t() {\n let n = fs::read_dir(d).unwrap().map(name).filter(|p| p.ends_with(\".rs\")).count();\n assert_eq!(n, 4);\n}\n"; assert_eq!(hits(walk), [(3, "reads-source")]); + let helper = "fn files() -> Vec {\n fs::read_dir(d).unwrap().map(name).collect()\n}\n#[test]\nfn t() {\n let n = files().into_iter().filter(|p| p.ends_with(\".rs\")).count();\n assert_eq!(n, 4);\n}\n"; + assert_eq!(only("reads-source", helper), [(6, "reads-source")], "a walk in a helper of the file"); + let output = "#[test]\nfn t() {\n assert!(render_command().ends_with(\".rs\"));\n}\n"; + assert_eq!(only("reads-source", output), [], "a suffix check on text in a file that lists no directory"); assert_eq!(hits_in(SOURCE_AUDITS[0], bad, &ctx()), []); let data = "#[test]\nfn t() {\n let s = include_str!(\"fixtures/a.svg\");\n assert_eq!(s.len(), 4);\n}\n"; assert_eq!(hits(data), []); @@ -5706,6 +5753,9 @@ mod tests { assert_eq!(got.len(), 2); assert_eq!(got["crates/x/src/a.rs"], Some([4, 5, 12, 21, 22].into_iter().collect())); assert_eq!(got["crates/x/src/n.rs"], None); + let deleted = "diff --git a/crates/x/src/main.rs b/crates/x/src/main.rs\ndeleted file mode 100644\n--- a/crates/x/src/main.rs\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-mod child;\n-fn main() {}\n"; + let got = parse_diff(deleted); + assert_eq!(got.get("crates/x/src/main.rs"), Some(&Some([1].into_iter().collect())), "a deleted file keeps its old path"); } #[test] @@ -5950,6 +6000,12 @@ mod tests { ); let closure = src.replace(" keeping(body);", " keeping(|body| keeping(body));"); assert_eq!(hits_in("crates/x/src/tests.rs", &closure, &ctx), [(8, "no-assertion")], "a closure parameter shadows the asserting helper"); + let block_closure = src.replace(" keeping(body);", " let _cb = |body: fn()| { drop(body); };\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &block_closure, &ctx), [], "a closure parameter's scope ends with the closure"); + let expr_closure = src.replace(" keeping(body);", " let _cb = |body: fn()| drop(body);\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &expr_closure, &ctx), [], "an expression closure's scope ends at its semicolon"); + let inner = src.replace(" keeping(body);", " let _cb = |body: fn()| { keeping(body); };"); + assert_eq!(hits_in("crates/x/src/tests.rs", &inner, &ctx), [(8, "no-assertion")], "the parameter inside its closure"); let parameter = src.replace("fn t()", "fn t(body: fn())"); assert_eq!(hits_in("crates/x/src/tests.rs", ¶meter, &ctx), [(8, "no-assertion")], "a function parameter shadows the asserting helper"); let later = src.replace(" keeping(body);", " keeping(body);\n {\n let body = || {};\n let _ = body;\n }"); @@ -5998,39 +6054,46 @@ mod tests { assert_eq!(hits(&counted), [], "a count getter preserves the pinned source"); let chained = pinned.replace(".map(|j| j.n)", ".map(|j| j.n).chain([1])"); assert_eq!(hits(&chained), [(5, "all-unguarded")], "a list that is not empty without the receiver's items"); - let word = "#[test]\nfn t() {\n let plain = word();\n assert_eq!(ids(&plain), [1, 2, 3]);\n let gaps = gaps(&plain);\n assert!(gaps.iter().all(|g| g.abs() < 1e-6));\n}\n"; + let reassigned = pinned.replace(" assert_eq!(got", " got = vec![1, 2];\n assert_eq!(got"); + assert_eq!(hits(&reassigned), [(6, "all-unguarded")], "the snapshot was replaced before the assertion"); + let pushed = pinned.replace(" assert_eq!(got", " got.push(1);\n assert_eq!(got"); + assert_eq!(hits(&pushed), [(6, "all-unguarded")], "the snapshot changed before the assertion"); + let read_first = pinned.replace(" assert_eq!(got", " assert!(got.len() < 9);\n assert_eq!(got"); + assert_eq!(hits(&read_first), [], "a read of the snapshot before the assertion"); + let word = "#[test]\nfn t() {\n let plain = word();\n assert_eq!(gaps(&plain), [0.0, 0.0]);\n let gaps = gaps(&plain);\n assert!(gaps.iter().all(|g| g.abs() < 1e-6));\n}\n"; assert_eq!(hits(word), []); - assert_eq!(hits(&word.replace("ids(&plain)", "ids(&other)")), [(6, "all-unguarded")], "a literal about another value"); + assert_eq!(hits(&word.replace("gaps(&plain), [", "gaps(&other), [")), [(6, "all-unguarded")], "a literal about another value"); + assert_eq!(hits(&word.replace("gaps(&plain), [", "ids(&plain), [")), [(6, "all-unguarded")], "a literal about another call on the value"); let emptied = word.replace(" let gaps = gaps(&plain);\n", " let mut gaps = gaps(&plain);\n gaps.clear();\n"); assert_eq!(hits(&emptied), [(7, "all-unguarded")], "a receiver that may change after its binding"); - let rebound = word.replace(" assert_eq!(ids(&plain), [1, 2, 3]);\n", "").replace( + let rebound = word.replace(" assert_eq!(gaps(&plain), [0.0, 0.0]);\n", "").replace( " let gaps = gaps(&plain);", - " let gaps = gaps(&plain);\n let plain = other();\n assert_eq!(ids(&plain), [1, 2, 3]);", + " let gaps = gaps(&plain);\n let plain = other();\n assert_eq!(gaps(&plain), [0.0, 0.0]);", ); assert_eq!(hits(&rebound), [(7, "all-unguarded")], "the assertion reads a later binding of the source"); } #[test] - fn all_over_a_constant_table_filtered_on_plain_values_is_guarded() { - let src = "fn reasons(app: &App, wide: bool) -> Vec> {\n TABLE.iter().filter(|r| r.wide == wide).map(|r| app.reason(r)).collect()\n}\n#[test]\nfn t() {\n let app = App::new();\n assert!(reasons(&app, true).iter().all(|r| r.is_none()));\n}\n"; + fn all_over_every_row_of_a_constant_table_is_guarded() { + let src = "const TABLE: [u8; 2] = [1, 2];\nfn reasons(app: &App, key: u8) -> Vec> {\n TABLE.iter().map(|r| app.reason(r, key)).collect()\n}\n#[test]\nfn t() {\n let app = App::new();\n assert!(reasons(&app, 2).iter().all(|r| r.is_none()));\n}\n"; assert_eq!(hits(src), []); - let shadowed = src.replace(" assert!", " let reasons = |_: &App, _: bool| Vec::>::new();\n assert!"); - assert_eq!(hits(&shadowed), [(8, "all-unguarded")], "a local binding shadows the file's function"); - let state = src.replace("filter(|r| r.wide == wide)", "filter(|r| app.has(r))"); - assert_eq!(hits(&state), [(7, "all-unguarded")], "a filter on the state the test builds"); - let mut_ref = src.replace("app: &App", "mut app: &App").replace("filter(|r| r.wide == wide)", "filter(|r| app.has(r))"); - assert_eq!(hits(&mut_ref), [(7, "all-unguarded")], "a filter on a `mut` reference parameter"); - let pattern = src.replace("app: &App, wide: bool", "(app, wide): (&App, bool)").replace("reasons(&app, true)", "reasons((&app, true))"); - assert_eq!(hits(&pattern), [(7, "all-unguarded")], "a parameter pattern that is not a plain name"); - let mapped = src.replace(".filter(|r| r.wide == wide).map(|r| app.reason(r))", ".map(|r| app.reason(r)).filter(|r| r.is_some())"); - assert_eq!(hits(&mapped), [(7, "all-unguarded")], "a filter on values mapped from that state"); - let map_while = src.replace(".filter(|r| r.wide == wide).map(|r| app.reason(r))", ".map_while(|r| app.reason(r))"); - assert_eq!(hits(&map_while), [(7, "all-unguarded")], "another step that drops rows"); + let shadowed = src.replace(" assert!", " let reasons = |_: &App, _: u8| Vec::>::new();\n assert!"); + assert_eq!(hits(&shadowed), [(9, "all-unguarded")], "a local binding shadows the file's function"); + let keyed = src.replace(".map(|r|", ".filter(|r| **r == key).map(|r|"); + assert_eq!(hits(&keyed), [(8, "all-unguarded")], "a filter on a plain value may drop every row"); + let state = src.replace(".map(|r|", ".filter(|r| app.has(r)).map(|r|"); + assert_eq!(hits(&state), [(8, "all-unguarded")], "a filter on the state the test builds"); + let empty = src.replace("[u8; 2] = [1, 2]", "[u8; 0] = []"); + assert_eq!(hits(&empty), [(8, "all-unguarded")], "an empty table"); + let elsewhere = src.replace("const TABLE: [u8; 2] = [1, 2];\n", ""); + assert_eq!(hits(&elsewhere), [(7, "all-unguarded")], "a table whose length the file does not show"); + let map_while = src.replace(".map(|r| app.reason(r, key))", ".map_while(|r| app.reason(r, key))"); + assert_eq!(hits(&map_while), [(8, "all-unguarded")], "another step that drops rows"); let optional = src .replace("-> Vec>", "-> Option>>") - .replace(".map(|r| app.reason(r))", ".map(|r| Some(app.reason(r)))") + .replace(".map(|r| app.reason(r, key))", ".map(|r| Some(app.reason(r, key)))") .replace(".all(|r| r.is_none())", ".all(|r| r.len() == 1)"); - assert_eq!(hits(&optional), [(7, "all-unguarded")], "collecting into an option can discard every row"); + assert_eq!(hits(&optional), [(8, "all-unguarded")], "collecting into an option can discard every row"); } #[test] @@ -6091,7 +6154,7 @@ mod tests { assert_eq!(hits(&src.replace(".rs", ".svg")), [], "{literal} with a fixture"); assert_eq!(hits_in(SOURCE_AUDITS[0], &src, &ctx()), [], "{literal} in an audit"); } - let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(r#\".rs\"#)).count();\n assert_eq!(n, 4);\n}\n"; + let walk = "#[test]\nfn t() {\n let n = fs::read_dir(d).unwrap().map(name).filter(|p| p.ends_with(r#\".rs\"#)).count();\n assert_eq!(n, 4);\n}\n"; assert_eq!(hits(walk), [(3, "reads-source")]); } @@ -6240,6 +6303,8 @@ mod tests { assert_eq!(hits_in("crates/x/src/tests.rs", win, &ctx()), [(3, "never-run")]); let other = "#[cfg(target_os = \"macos\")]\nfn helper() {}\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(only("never-run", other), [], "a cfg on another item"); + let case = "#[cfg(windows)]\n#[test_case(1; \"one\")]\nfn t(n: usize) {\n assert_eq!(f(n), 2);\n}\n"; + assert_eq!(only("never-run", case), [(3, "never-run")], "a `;` inside a later attribute"); } #[test] @@ -6350,6 +6415,18 @@ mod tests { let read = |p: &str| mac.get(p).map(|s| (*s).to_owned()); let gates = module_gates(&["crates/x/src/platform/child.rs".to_owned()], &read); assert_eq!(gates.get("crates/x/src/platform/child.rs").map(|g| g.preds.clone()), Some(vec!["target_os=\"macos\"".to_owned()])); + // An inline route one level up joins the external one. + let inline: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod platform;\n"), + ("crates/x/src/main.rs", "mod platform {\n mod child;\n}\n"), + ("crates/x/src/platform.rs", "mod child;\n"), + ("crates/x/src/platform/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| inline.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/platform/child.rs".to_owned()], &read); + assert_eq!(gates.get("crates/x/src/platform/child.rs").map(|g| g.preds.clone()), None, "main.rs's inline module loads it on every target"); } #[test] @@ -6440,6 +6517,12 @@ mod tests { assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file"); assert_eq!(only("reads-source", &dir.replace("\"data.json\"", "name")), [], "a file name the test does not spell out"); assert_eq!(only("reads-source", &dir.replace(".join(\"data.json\")", "")), [(3, "reads-source")], "a literal final join"); + let trimmed = data.replace("root.join(\"data.json\")", "\"data.json.rs\".trim_end_matches(\".rs\")"); + assert_eq!(only("reads-source", &trimmed), [], "a call that is not a path builder"); + let owned = data.replace("root.join(\"data.json\")", "\"src/lib.rs\".to_owned()"); + assert_eq!(only("reads-source", &owned), [(3, "reads-source")], "a conversion of a literal path"); + let new = data.replace("root.join(\"data.json\")", "Path::new(\"src/lib.rs\")"); + assert_eq!(only("reads-source", &new), [(3, "reads-source")], "a Path::new of a literal path"); let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{dir}/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", formatted), [(3, "reads-source")], "a format! template"); @@ -6468,6 +6551,16 @@ mod tests { assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); } + #[test] + fn a_closure_parameter_shadows_the_outer_binding_in_its_body() { + let closure = "#[test]\nfn t() {\n let n = 0;\n results().into_iter().for_each(|n| assert_eq!(n, 1));\n}\n"; + assert_eq!(only("fixture-only", closure), []); + let block = closure.replace("|n| assert_eq!(n, 1)", "|n| {\n assert_eq!(n, 1);\n }"); + assert_eq!(only("fixture-only", &block), [], "a block body"); + let after = "#[test]\nfn t() {\n let n = 0;\n results().into_iter().for_each(|n| consume(n));\n assert_eq!(n, 0);\n}\n"; + assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the closure"); + } + #[test] fn a_match_arm_binding_shadows_the_outer_one_in_its_arm() { let arm = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(n) => assert_eq!(n, 1),\n None => {}\n }\n}\n"; From cbd1936ae65ebbb5bbda6720e3280c1b59515587 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 00:45:37 -0800 Subject: [PATCH 05/11] xtask: test-lint no longer reports helper, diagnostic and fixed-size false alarms no-assertion: - A call in a top-level test reaches the helper its own file defines. A non-asserting helper of the same name in another file of the crate no longer hides it. Names the file also calls with a path, and definitions below the file's top level, keep the crate's verdict. - An `#[ignore = "reason"]` test that prints is a diagnostic and needs no assertion. - An asserting function passed by name as a value (`keeping_settings(the_body)`, `run(&[body])`) counts as the test's check, also through a helper that passes it, unless a local binding, loop pattern, match arm or parameter shadows the name in scope, or the value is dropped (`drop(body)`, `let _ = Some(body)`, `(body,);`). all-unguarded: - A parenthesized range of literals or constants, `(0..3).all(...)`. - A receiver whose source an earlier `assert_eq!` compares with a non-empty literal: a local collected from the receiver, or the call the receiver is bound to, when nothing changes the source in between. A shared borrow passed to a call outside an assertion may change it. - A call to a function of the file that lists every row of a non-empty constant table without filtering it; every function of that name in the file has to do so. --- xtask/src/test_lint.rs | 788 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 765 insertions(+), 23 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 449885209f..f6b8a6e2b1 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -16,8 +16,12 @@ //! be `const`s of the file) followed only by methods that keep an item (`map`, `iter`, `rev`, //! `collect` …), or filled by a `push` or `insert` on every pass of a loop over one, unless later //! code may shrink or replace them; and fields the file declares only as arrays of a positive -//! length. `.windows(k)` and `.chunks_exact(k)` need `k` items. Empty arrays still count. A change -//! anywhere in the test counts as a change to the hit; +//! length. `.windows(k)` and `.chunks_exact(k)` need `k` items. Empty arrays still count. Also +//! left out: a parenthesized range of literals or constants (`(0..3).all(…)`); a receiver whose +//! source an earlier equality assertion compares with a non-empty literal (a local bound from the +//! receiver, or the call the receiver is bound to), when nothing changes the source in between; +//! and a call to a function of the file that lists every row of a non-empty constant table +//! without filtering it. A change anywhere in the test counts as a change to the hit; //! * `only-weak`: every assertion is `is_ok()`, `is_some()`, `!is_empty()` or `len() > 0`, and the //! test calls no asserting helper; //! * `self-compare`: `assert_eq!(x, x)` or `assert_ne!(x, x)` on the same expression, when that @@ -26,7 +30,10 @@ //! * `exit-status-only`: a test that runs a process and checks only its exit status, reading no //! output, with a status check in any condition or compared operand of a standard assertion; //! * `no-assertion`: no assertion macro, `panic!`, `unwrap_err`, `expect_err` or asserting helper, -//! and no `#[should_panic]`; +//! and no `#[should_panic]`. An asserting helper passed by name as a value +//! (`keeping_settings(the_body)`) counts, unless a local binding or parameter shadows the name, +//! and so does an `#[ignore = "…"]` test that prints. A top-level test's call reaches the helper +//! of its own file when the file defines one of that name at its top level; //! * `early-return`: a silent bare `return` before the end of the test whose guard tests a value //! from the code under test. Left out: a return after an assertion in its block, one whose //! statement or line has a comment or a printed note saying why, and guards on files, fonts, @@ -1315,35 +1322,92 @@ fn in_regions(regions: &[(usize, usize)], pos: usize) -> bool { type Def = (String, bool, Vec); /// For each crate of `files` ([`crate_of`]), the names of the functions and macros in its test -/// code, or in `crates/testkit`'s, that assert, panic or call one that does. +/// code, or in `crates/testkit`'s, that assert, panic or call one that does. Each file of `files` +/// also gets an entry under its path ([`helpers_for`]): a call in a top-level test reaches the +/// function of that name the file defines only when all its definitions are at the file's top +/// level and the file does not call that name with a path. Other names keep the crate's verdict. pub fn asserting_helpers(files: &[(String, String)]) -> HashMap> { let mut defs: HashMap> = HashMap::new(); + // Each file's path, its definitions, and the names its own definitions decide. + let mut by_file: Vec<(&str, Vec, HashSet)> = vec![]; for (path, src) in files { let m = mask(src); let regions = test_regions(path, &m, &tests_in(&m)); - let crate_defs = defs.entry(crate_of(path)).or_default(); - for at in words(&m, b"fn", 0, m.len()).into_iter().chain(words(&m, b"macro_rules", 0, m.len())) { - if in_regions(®ions, at) { - crate_defs.extend(definition(&m, at)); - } - } + let depths = brace_depths(&m); + let mut nested = HashSet::new(); + let own: Vec = words(&m, b"fn", 0, m.len()) + .into_iter() + .chain(words(&m, b"macro_rules", 0, m.len())) + .filter(|&at| in_regions(®ions, at)) + .filter_map(|at| { + let def = definition(&m, at)?; + if depths[at] != 0 { + nested.insert(def.0.clone()); + } + Some(def) + }) + .collect(); + // A call with a path (`other::near(…)`) may reach another module's function, and calls + // keep only the last name, so a name the file also calls with a path keeps the crate's + // verdict. A definition below the file's top level also keeps the crate's verdict. + let names = own.iter().map(|d| d.0.clone()).filter(|n| !nested.contains(n) && !called_with_path(&m, n)).collect(); + defs.entry(crate_of(path)).or_default().extend(own.iter().cloned()); + by_file.push((path, own, names)); } let testkit = defs.get(TESTKIT).cloned().unwrap_or_default(); - defs.iter().map(|(krate, own)| (krate.clone(), checking(own.iter().chain(if krate == TESTKIT { &[][..] } else { &testkit[..] })))).collect() + let mut out: HashMap> = defs + .iter() + .map(|(krate, own)| (krate.clone(), checking(HashSet::new(), own.iter().chain(if krate == TESTKIT { &[][..] } else { &testkit[..] })))) + .collect(); + for (path, own, names) in by_file { + if names.is_empty() { + continue; + } + let base = out.get(&crate_of(path)).map(|set| set.difference(&names).cloned().collect()).unwrap_or_default(); + out.insert(path.to_owned(), checking(base, own.iter().filter(|d| names.contains(&d.0)))); + } + out +} + +/// Whether the masked file names `name` (a function, or `name!` for a macro) after a `::` path. +fn called_with_path(m: &[u8], name: &str) -> bool { + let name = name.trim_end_matches('!'); + words(m, name.as_bytes(), 0, m.len()).into_iter().any(|at| m[..at].trim_ascii_end().ends_with(b"::")) +} + +/// The asserting helpers a test in the file at `path` can reach: for a top-level test, the file's +/// own entry of [`asserting_helpers`] if present; otherwise, its crate's. +fn helpers_for<'a>(ctx: &'a Ctx, path: &str, top_level: bool) -> Option<&'a HashSet> { + if top_level { ctx.helpers.get(path).or_else(|| ctx.helpers.get(&crate_of(path))) } else { ctx.helpers.get(&crate_of(path)) } +} + +/// The brace depth before each byte of masked text. +fn brace_depths(m: &[u8]) -> Vec { + let mut depth = 0usize; + m.iter() + .map(|&c| { + let before = depth; + match c { + b'{' => depth += 1, + b'}' => depth = depth.saturating_sub(1), + _ => {} + } + before + }) + .collect() } /// The crate whose test helpers every crate can call. const TESTKIT: &str = "crates/testkit"; -/// The names among `defs` that check something, directly or through another of `defs`. Calls do -/// not say which of several functions with one name they reach, so a name counts only when every -/// definition with that name checks. -fn checking<'a>(defs: impl Iterator + Clone) -> HashSet { +/// `known` and the names among `defs` that check something, directly or through another of +/// `defs` or a name of `known`. Calls do not say which of several functions with one name they +/// reach, so a name counts only when every definition with that name checks. +fn checking<'a>(mut known: HashSet, defs: impl Iterator + Clone) -> HashSet { let mut by_name: HashMap<&str, Vec<&Def>> = HashMap::new(); for d in defs { by_name.entry(d.0.as_str()).or_default().push(d); } - let mut known: HashSet = HashSet::new(); loop { let checks = |d: &Def| d.1 || d.2.iter().any(|c| known.contains(c)); let more: Vec = by_name @@ -1380,7 +1444,14 @@ fn item_at(m: &[u8], at: usize) -> Option<(&[u8], bool, usize, usize)> { 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(); + let called = calls(m, open, close) + .into_iter() + .filter(|(_, method)| !method) + .map(|(n, _)| n) + .chain( + passed_names(m, open, close).into_iter().filter(|(name, pos)| !shadows_helper(m, at, open, close, name.as_bytes(), *pos)).map(|(n, _)| n), + ) + .collect(); Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) } @@ -1391,6 +1462,8 @@ struct File<'a> { path: &'a str, src: &'a [u8], m: Vec, + /// The brace depth before each byte of [`File::m`] ([`brace_depths`]). + depths: Vec, /// [`File::m`] with the functions and macros declared inside each test blanked: declaring /// one does not run its body ([`executed`]). exec: Vec, @@ -1435,11 +1508,12 @@ impl File<'_> { /// Every hit in one file, exemptions applied. pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { let m = mask(src); + let depths = brace_depths(&m); let tests = tests_in(&m); let regions = test_regions(path, &m, &tests); let exec = executed(&m, &tests); let cfgs = cfg_spans(&m, src.as_bytes()); - let file = File { path, src: src.as_bytes(), m, exec, lines: Lines::new(src), tests, regions, cfgs }; + let file = File { path, src: src.as_bytes(), m, depths, exec, lines: Lines::new(src), tests, regions, cfgs }; 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)); @@ -1493,19 +1567,24 @@ struct View<'a> { delegates: bool, checks: bool, should_panic: bool, + /// An ignored test with a reason that prints what it measures ([`ignored_with_reason`], + /// [`prints`]): a diagnostic run by hand, which has nothing to assert. + diagnostic: bool, } fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { 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); + let helpers = helpers_for(ctx, file.path, file.depths[t.attr] == 0).unwrap_or(&none); let delegates = calls(m, t.open, t.close) .iter() - .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)); + .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)) + || passes_helper(m, t, helpers); let checks = checks_itself(m, t.open, t.close); let should_panic = should_panic_attr(m, t.attr, t.fn_at); - let v = View { file, t, asserts, delegates, checks, should_panic }; + let diagnostic = ignored_with_reason(file, t.attr, t.fn_at) && prints(m, t.open, t.close); + let v = View { file, t, asserts, delegates, checks, should_panic, diagnostic }; let mut hits = all_unguarded(&v); hits.extend(self_compare(&v)); hits.extend(early_returns(&v)); @@ -1517,6 +1596,183 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { hits } +/// Whether a test's body passes an asserting helper by name as a value, an argument or a tuple +/// element (`keeping_settings(the_test_body)`, `[("case", case_body), …]`), excluding local bindings +/// and parameters that shadow helper names. +fn passes_helper(m: &[u8], t: &TestFn, helpers: &HashSet) -> bool { + passed_names(m, t.open, t.close).into_iter().any(|(name, pos)| { + name != t.name + && !COMMON.contains(&name.as_str()) + && helpers.contains(&name) + && !shadows_helper(m, t.fn_at, t.open, t.close, name.as_bytes(), pos) + }) +} + +/// Whether a parameter of the function at `at` (body `open..close`), or a local binding in scope at +/// `pos`, shadows the helper `name`. +fn shadows_helper(m: &[u8], at: usize, open: usize, close: usize, name: &[u8], pos: usize) -> bool { + binds_parameter(&m[at..=open], name) || bound_at(&m[open + 1..close], name, pos - (open + 1)) +} + +/// Whether a binding of `name` in `body` is in scope at `pos`: a `let` from the end of its statement +/// to the end of its block (an `if let` or `while let` in its block only), a `for` pattern in the +/// loop body, a match-arm pattern inside its arm, or a closure parameter inside the closure's body. +fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool { + let lets = words(body, b"let", 0, pos).into_iter().any(|at| { + let start = at + 3; + let mut end = start; + while end < body.len() { + if matches!(body[end], b'=' | b';') + || (body[end..].starts_with(b"else") && !is_ident(body[end - 1]) && !body.get(end + 4).copied().is_some_and(is_ident)) + { + break; + } + end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 }; + } + if words(body, name, start, end).is_empty() { + return false; + } + let head = body[..at].trim_ascii_end(); + let conditional = + [&b"if"[..], b"while"].into_iter().any(|k| head.ends_with(k) && !head[..head.len() - k.len()].last().copied().is_some_and(is_ident)); + if conditional { + return let_body(body, start).is_some_and(|(_, open, close)| open < pos && pos < close); + } + statement_end(body, at) < pos && pos < block_close(body, at) + }); + let loops = words(body, b"for", 0, pos).into_iter().any(|at| { + let Some((open, close)) = block_after(body, at + 3) else { return false }; + let Some(&in_at) = words(body, b"in", at + 3, open).first() else { return false }; + open < pos && pos < close && !words(body, name, at + 3, in_at).is_empty() + }); + let name = String::from_utf8_lossy(name); + lets || loops || arm_binding(body, &name, pos).is_some() || closure_binding(body, &name, pos).is_some() +} + +/// The innermost unclosed `(`, `[` or `{` before `at`. +fn enclosing_open(m: &[u8], at: usize) -> Option { + let mut depth = 0usize; + for i in (0..at).rev() { + match m[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth == 0 => return Some(i), + b'(' | b'[' | b'{' => depth -= 1, + _ => {} + } + } + None +} + +/// The bare identifiers, with their offsets, passed as arguments or as tuple or array elements in +/// the body between `open` and `close`. An element of a tuple, array or constructor counts only +/// where its value is kept: not in a statement of its own (`(body,);`), a `let _` or `let _name` +/// binding, or a `drop` or `forget` call. +fn passed_names(m: &[u8], open: usize, close: usize) -> Vec<(String, usize)> { + let mut names = Vec::new(); + let mut at = open + 1; + while at < close { + if !is_ident(m[at]) || (at > 0 && (is_ident(m[at - 1]) || m[at - 1] == b'.')) { + at += 1; + continue; + } + let end = at + m[at..close].iter().take_while(|&&c| is_ident(c)).count(); + let before = m[..at].trim_ascii_end().last().copied(); + let after = m.get(skip_ws(m, end)).copied(); + if matches!(before, Some(b'(' | b'[' | b',')) && matches!(after, Some(b')' | b']' | b',')) && value_kept(m, open, at) { + names.push((String::from_utf8_lossy(&m[at..end]).into_owned(), at)); + } + at = end; + } + names +} + +/// Whether the element at `at` is a call's argument, or sits in a tuple or array whose statement +/// keeps it ([`passed_names`]). +fn value_kept(m: &[u8], open: usize, at: usize) -> bool { + let Some(mut group) = enclosing_open(m, at).filter(|&g| g > open) else { return false }; + // A name in a `let` or `for` pattern (`let (body,) = …`) binds a value rather than passing one. + let from = m[open + 1..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(open + 1, |p| open + 2 + p); + if words(m, b"let", from, at).last().is_some_and(|&l| !m[l..at].contains(&b'=')) + || words(m, b"for", from, at).last().is_some_and(|&f| words(m, b"in", f, at).is_empty()) + { + return false; + } + loop { + let head = m[..group].trim_ascii_end(); + let call = m[group] != b'{' && head.last().is_some_and(|&c| is_ident(c) || c == b'!' || c == b'>'); + let mut start = group; + if call { + // A call runs even when its result is dropped; constructors only store the value. + let name = &head[head.len() - head.iter().rev().take_while(|&&c| is_ident(c)).count()..]; + let constructor = name.first().is_some_and(u8::is_ascii_uppercase) || head.ends_with(b"!") || head.ends_with(b"::new"); + if !constructor { + return !matches!(name, b"drop" | b"forget"); + } + start = head.len() - head.iter().rev().take_while(|&&c| is_ident(c) || matches!(c, b':' | b'!')).count(); + } + if let Some(outer) = enclosing_open(m, group).filter(|&g| g > open && m[g] != b'{') { + group = outer; + continue; + } + let statement = m[..start].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let statement = m[statement..start].trim_ascii(); + // `let _ = …` and `let _name = …` drop or ignore the value. + let discarded = statement + .strip_prefix(b"let") + .filter(|r| r.first().is_some_and(u8::is_ascii_whitespace)) + .is_some_and(|r| r.trim_ascii_start().starts_with(b"_")); + return !discarded && !statement.iter().all(|&c| c.is_ascii_whitespace() || c == b'&'); + } +} + +/// Whether a function or closure in `body` takes a parameter that binds `name`. +fn binds_parameter(body: &[u8], name: &[u8]) -> bool { + let binds = |from, to| { + split_args(body, from, to).into_iter().any(|(start, end)| { + let pattern = &body[start..end]; + let end = pattern.iter().position(|&c| c == b':').unwrap_or(pattern.len()); + !words(pattern, name, 0, end).is_empty() + }) + }; + if words(body, b"fn", 0, body.len()).into_iter().any(|at| { + let Some(open) = body[at + 2..].iter().position(|&c| c == b'(').map(|p| at + 2 + p) else { return false }; + matching(body, open).is_some_and(|close| binds(open + 1, close)) + }) { + return true; + } + let mut at = 0; + while at < body.len() { + let head = body[..at].trim_ascii_end(); + let opens = head.last().is_some_and(|c| matches!(c, b'=' | b'(' | b',' | b'{' | b';')) + || [b"move".as_slice(), b"return", b"=>"].iter().any(|word| head.ends_with(word)); + if body[at] == b'|' && opens { + let Some(close) = body[at + 1..].iter().position(|&c| c == b'|').map(|p| at + 1 + p) else { return false }; + if binds(at + 1, close) { + return true; + } + at = close; + } + at += 1; + } + false +} + +/// Whether the attributes in `file.m[from..to]` include `#[ignore = "…"]` with a non-blank reason. +fn ignored_with_reason(file: &File, from: usize, to: usize) -> bool { + let m = &file.m; + words(m, b"ignore", from, to).into_iter().any(|at| { + let j = skip_ws(m, at + "ignore".len()); + m[..at].ends_with(b"#[") + && m.get(j) == Some(&b'=') + && ignore_reason(&file.src[skip_ws(m, j + 1)..]).is_some_and(|body| body.iter().any(|c| !c.is_ascii_whitespace())) + }) +} + +/// Whether the masked text prints: `println!`, `eprintln!`, `print!` or `eprint!`. +fn prints(m: &[u8], from: usize, to: usize) -> bool { + macro_calls(m, from, to).iter().any(|c| matches!(c.name.as_str(), "println" | "eprintln" | "print" | "eprint")) +} + /// 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. @@ -2029,7 +2285,233 @@ fn positive_all(cond: &str, test_body: &[u8], sizes: &Sizes) -> bool { let body = arg.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(arg, |(_, body)| body); let none_match = not_equal_conjunction(body); let (receiver, need) = receiver_need(&cond[..i], sizes); - !none_match && least_items(receiver, test_body, sizes) < need + // A parenthesized range of literals or constants: `(0..3).all(…)`. + let range = if receiver.starts_with('(') { expr_len(receiver, sizes, "") } else { 0 }; + let known = least_items(receiver, test_body, sizes).max(range); + !none_match && known < need && !(need == 1 && (pinned_source(receiver, test_body, sizes) || fixed_table_call(receiver, test_body, sizes))) + }) +} + +/// Whether an earlier equality assertion compares what `receiver` is made from with a non-empty +/// literal: a plain local whose binding reads `receiver` (`let got = r.items()….collect(); +/// assert_eq!(got, [a, b])` before `r.items().iter().all(…)`, with `got` unchanged in between), or +/// the same call `receiver` is bound to (`let gaps = gaps(&word); assert_eq!(gaps(&word), [a, b])`). +fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { + let r = array_receiver(receiver); + let init = |name: &str, at: usize| let_init(body, name, at).and_then(|(init, _)| init); + // For a receiver bound to `f(&x)`: the call `f(&x)`, `x`, and where the binding of `x` it reads ends. + let source = if plain_local(r) { + let_init(body, r, body.len()).and_then(|(init, bound)| { + let (text, _) = init?; + let s = single_local_arg(&text)?.to_owned(); + if binds(&body[bound..], s.as_bytes()) { + return None; + } + let at = let_init(body, &s, bound).map_or(0, |(_, at)| statement_end(body, at)); + Some((norm(text.as_bytes()), s, at)) + }) + } else { + None + }; + macro_calls(body, 0, body.len()).into_iter().any(|a| { + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) || a.args.len() < 2 || !body_level_statement(body, a.at) { + return false; + } + let (left, right) = (norm(&body[a.args[0].0..a.args[0].1]), norm(&body[a.args[1].0..a.args[1].1])); + [(&left, &right), (&right, &left)].into_iter().any(|(pinned, literal)| { + if literal_len(literal, sizes) == 0 { + return false; + } + // The binding keeps the receiver's items (`r.items().iter().map(…).collect()`), nothing + // changes the binding before the assertion, and nothing changes the receiver's source + // from the binding on. + let read = !plain_local(r) + && plain_local(pinned) + && init(pinned, a.at).is_some_and(|(text, at)| { + let bound = statement_end(body, at); + keeping_base(&text, true) == r + && !touched_after(&body[..a.at], pinned, bound, pinned) + && !touched_after(body, root_local(r), bound, r) + }); + // The assertion compares the same call the receiver is bound to (`gaps(&word)`), so its + // literal is what the receiver holds. + read || source.as_ref().is_some_and(|(call, s, at)| pinned == call && !touched_after(body, s, *at, r)) + }) + }) +} + +/// Whether an expression starts a statement of the test body or a plain nested block. +fn body_level_statement(body: &[u8], mut at: usize) -> bool { + while body[..at].trim_ascii_end().ends_with(b"::") { + at = body[..at].trim_ascii_end().len() - 2; + at = body[..at].trim_ascii_end().len(); + while at > 0 && is_ident(body[at - 1]) { + at -= 1; + } + } + let mut statement = true; + let mut i = 0; + while i < at { + match body[i] { + b'{' if statement => {} + b'(' | b'[' | b'{' => { + let Some(close) = matching(body, i).filter(|&close| close < at) else { return false }; + statement = body[i] == b'{'; + i = close + 1; + continue; + } + b';' | b'}' => statement = true, + c if c.is_ascii_whitespace() => {} + _ => statement = false, + } + i += 1; + } + statement +} + +/// The local a receiver path starts from: `r` of `r.items()`. +fn root_local(expr: &str) -> &str { + let end = expr.bytes().take_while(|&c| is_ident(c)).count(); + &expr[..end] +} + +/// Whether code after `from` uses `name` other than through a read-only use of `receiver`, a shared +/// borrow `&name` read in an assertion, or a getter named `len`, `is_empty` or +/// ending in `_count`. Other uses, including assertion arguments, may change what it holds. +/// A read bound to another local or passed to a call outside an assertion may give out an alias. +fn touched_after(body: &[u8], name: &str, from: usize, receiver: &str) -> bool { + if !plain_local(name) { + return true; + } + words(body, name.as_bytes(), from, body.len()).into_iter().any(|at| { + let rest = norm(&body[at..statement_end(body, at)]); + let head = body[..at].trim_ascii_end(); + // A shared borrow reads the value in an assertion or in the receiver's own binding; passed to + // a call elsewhere (`reset(&r);`, `let old = reset(&r);`), it may change what an + // interior-mutable value holds. + let statement = body[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let raw = body[statement..at].trim_ascii_start(); + let macro_name = &raw[..raw.iter().take_while(|&&c| is_ident(c)).count()]; + let assertion = raw.get(macro_name.len()) == Some(&b'!') + && PLAIN_ASSERTS.iter().any(|p| macro_name.strip_prefix(p.as_bytes()).is_some_and(|r| r.is_empty() || r.starts_with(b"_"))); + // The `let` that binds the receiver itself (`let gaps = gaps(&plain);`) reads its source. + let binds_receiver = raw + .strip_prefix(b"let") + .map(<[u8]>::trim_ascii_start) + .is_some_and(|r| r.starts_with(receiver.as_bytes()) && !r.get(receiver.len()).copied().is_some_and(is_ident)); + let shared = head.ends_with(b"&") && !head.ends_with(b"&&") && (assertion || binds_receiver); + let getter = rest + .strip_prefix(name) + .and_then(|r| r.strip_prefix('.')) + .and_then(|r| r.split_once('(')) + .is_some_and(|(method, _)| plain_local(method) && (matches!(method, "len" | "is_empty") || method.ends_with("_count"))); + let read = rest.strip_prefix(receiver).is_some_and(|tail| { + tail.is_empty() + || tail.starts_with([')', ']', '}', ',']) + || [".iter()", ".len()", ".is_empty()", ".first()", ".last()", ".get(", ".contains("].iter().any(|method| tail.starts_with(method)) + }); + let read_only = assertion || binds_receiver || body_level_statement(body, at); + !((read || getter) && read_only || shared) + }) +} + +/// The plain local of a call with one argument, `f(&x)` or `f(x)`. +fn single_local_arg(call: &str) -> Option<&str> { + let open = call.find('(')?; + let head = &call[..open]; + if head.is_empty() || !head.bytes().all(|c| is_ident(c) || c == b':') || matching(call.as_bytes(), open) != Some(call.len() - 1) { + return None; + } + let arg = &call[open + 1..call.len() - 1]; + let arg = arg.strip_prefix('&').unwrap_or(arg); + plain_local(arg).then_some(arg) +} + +/// Whether `receiver` calls a function of the file whose body lists every row of a non-empty +/// constant table of the file (`const TABLE: [T; 3]`, `TABLE.iter()…`) without filtering it: the +/// call gives at least one row whatever state the test builds. A filter, even one on plain values, +/// may drop every row, so it leaves the function out. +fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { + let r = array_receiver(receiver); + let Some(open) = r.find('(') else { return false }; + let name = &r[..open]; + if !plain_local(name) + || matching(r.as_bytes(), open) != Some(r.len() - 1) + || let_binds(test_body, name.as_bytes()) + || binds_parameter(test_body, name.as_bytes()) + { + return false; + } + let file = sizes.file; + let defs: Vec = words(file, name.as_bytes(), 0, file.len()) + .into_iter() + .filter(|&at| { + let head = file[..at].trim_ascii_end(); + head.ends_with(b"fn") && !(head.len() > 2 && is_ident(head[head.len() - 3])) + }) + .collect(); + // Functions of one name in several modules: the call may reach any of them, so every one has + // to list the table. + if defs.is_empty() { + return false; + } + defs.into_iter().all(|at| { + let head = file[..at].trim_ascii_end(); + let Some((_, _, body_open, body_close)) = item_at(file, head.len() - 2) else { return false }; + let params_open = skip_ws(file, at + name.len()); + let Some(params_close) = (file.get(params_open) == Some(&b'(')).then(|| matching(file, params_open)).flatten() else { return false }; + let signature = norm(&file[params_close + 1..body_open]); + let return_type = signature.strip_prefix("->").unwrap_or(""); + let body = norm(&file[body_open + 1..body_close]); + let table_end = body.bytes().take_while(|&c| is_ident(c) || c == b':').count(); + let table = &body[..table_end]; + let screaming = !table.is_empty() && table.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_'); + if !screaming || item_len(table, sizes) == 0 || !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()")) { + return false; + } + // The body is the chain alone, of steps that keep every row. + let mut at = table_end; + while at < body.len() { + let Some(rest) = body[at..].strip_prefix('.') else { return false }; + let method_len = rest.bytes().take_while(|&c| is_ident(c)).count(); + let method = &rest[..method_len]; + let mut open = at + 1 + method_len; + let mut target = None; + if method == "collect" && body[open..].starts_with("::<") { + let Some(close) = body[open..].find(">(") else { return false }; + target = Some(&body[open + 3..open + close]); + open += close + 1; + } + let Some(close) = (body.as_bytes().get(open) == Some(&b'(')).then(|| matching(body.as_bytes(), open)).flatten() else { return false }; + match method { + "iter" | "into_iter" | "map" | "copied" | "cloned" | "enumerate" | "rev" => {} + "collect" => { + if !known_collection(target.unwrap_or(if close + 1 == body.len() { return_type } else { "" })) { + return false; + } + } + _ => return false, + } + at = close + 1; + } + true + }) +} + +/// Whether a `let` pattern in masked `body` contains `name` as a whole word. +fn let_binds(body: &[u8], name: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let start = at + 3; + let mut end = start; + while end < body.len() { + if matches!(body[end], b'=' | b';') + || (body[end..].starts_with(b"else") && !is_ident(body[end - 1]) && !body.get(end + 4).copied().is_some_and(is_ident)) + { + break; + } + end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 }; + } + !words(body, name, start, end).is_empty() }) } @@ -2907,7 +3389,7 @@ fn strip_stream_configuration(body: &mut [u8]) { } fn no_assertion(v: &View) -> Option { - if v.checks || v.delegates || v.should_panic { + if v.checks || v.delegates || v.should_panic || v.diagnostic { return None; } Some(v.whole(Rule::NoAssertion, "no assertion and no asserting helper".into())) @@ -7307,4 +7789,264 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } + + #[test] + fn a_files_own_helper_decides_over_one_of_the_same_name_in_another_file() { + let own = "fn near(a: f64) { assert!(a < 1.0); }\n#[test]\nfn t() {\n near(f());\n}\n"; + let other = "fn near(a: f64) -> bool { a < 1.0 }\n#[test]\nfn u() {\n assert!(near(f()));\n}\n"; + let caller = "#[test]\nfn v() {\n near(f());\n}\n"; + let files = [ + ("crates/x/tests/it/own.rs".to_owned(), own.to_owned()), + ("crates/x/tests/it/other.rs".to_owned(), other.to_owned()), + ("crates/x/tests/it/caller.rs".to_owned(), caller.to_owned()), + ]; + let ctx = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/tests/it/own.rs", own, &ctx), [], "the file's own near asserts"); + let qualified = own.replace(" near(f());", " other::near(f());"); + let files = [files[0].clone(), files[1].clone(), ("crates/x/tests/it/q.rs".to_owned(), qualified.clone())]; + let ctx_q = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/q.rs", &qualified, &ctx_q), + [(3, "no-assertion")], + "a call with a path may reach the other file's near" + ); + assert_eq!( + hits_in("crates/x/tests/it/caller.rs", caller, &ctx), + [(2, "no-assertion")], + "a file that defines none cannot tell which it reaches" + ); + let nested = "mod a {\n fn near(a: f64) { assert!(a < 1.0); }\n}\nuse other::*;\n#[test]\nfn t() {\n near(f());\n}\n"; + let files = [("crates/x/tests/it/nested.rs".to_owned(), nested.to_owned()), files[1].clone()]; + let ctx_nested = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/nested.rs", nested, &ctx_nested), + [(6, "no-assertion")], + "a helper inside an inline module does not decide for the file's top-level call" + ); + let inner = + "fn near(a: f64) { assert!(a < 1.0); }\nmod inner {\n use super::other::*;\n #[test]\n fn t() {\n near(f());\n }\n}\n"; + let files = [("crates/x/tests/it/inner.rs".to_owned(), inner.to_owned()), files[1].clone()]; + let ctx_inner = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/inner.rs", inner, &ctx_inner), + [(5, "no-assertion")], + "a test inside an inline module may import the other file's near" + ); + let local = "#[test]\nfn t() {\n fn near(a: f64) { assert!(a < 1.0); }\n assert!(f());\n}\n#[test]\nfn u() {\n near(f());\n}\n"; + let files = [("crates/x/tests/it/local.rs".to_owned(), local.to_owned()), files[1].clone()]; + let ctx_local = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/local.rs", local, &ctx_local), + [(7, "no-assertion")], + "a helper inside a test does not decide for another test's call" + ); + } + + #[test] + fn a_test_body_passed_to_a_wrapper_counts_as_its_check() { + let src = "fn keeping(test: fn()) {\n test();\n}\nfn body() {\n assert_eq!(f(), 1);\n}\n#[test]\nfn t() {\n keeping(body);\n}\n"; + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), src.to_owned())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), []); + let wrapper = src.replace(" keeping(body);", " wrapper();") + "fn wrapper() {\n keeping(body);\n}\n"; + let wrapper_ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), wrapper.clone())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &wrapper, &wrapper_ctx), []); + let shadowed_wrapper = wrapper.replace(" keeping(body);", " let body = || {};\n keeping(body);"); + let shadowed_wrapper_ctx = + Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), shadowed_wrapper.clone())]), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/src/tests.rs", &shadowed_wrapper, &shadowed_wrapper_ctx), + [(8, "no-assertion")], + "a local binding in a wrapper shadows the asserting helper" + ); + let shadowed = src.replace(" keeping(body);", " let body = || {};\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &shadowed, &ctx), [(8, "no-assertion")], "a local binding shadows the asserting helper"); + let destructured = src.replace(" keeping(body);", " let (body,) = (|| {},);\n keeping(body);"); + assert_eq!( + hits_in("crates/x/src/tests.rs", &destructured, &ctx), + [(8, "no-assertion")], + "a destructured binding shadows the asserting helper" + ); + let closure = src.replace(" keeping(body);", " keeping(|body| keeping(body));"); + assert_eq!(hits_in("crates/x/src/tests.rs", &closure, &ctx), [(8, "no-assertion")], "a closure parameter shadows the asserting helper"); + let block_closure = src.replace(" keeping(body);", " let _cb = |body: fn()| { drop(body); };\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &block_closure, &ctx), [], "a closure parameter's scope ends with the closure"); + let expr_closure = src.replace(" keeping(body);", " let _cb = |body: fn()| drop(body);\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &expr_closure, &ctx), [], "an expression closure's scope ends at its semicolon"); + let inner = src.replace(" keeping(body);", " let _cb = |body: fn()| { keeping(body); };"); + assert_eq!(hits_in("crates/x/src/tests.rs", &inner, &ctx), [(8, "no-assertion")], "the parameter inside its closure"); + let parameter = src.replace("fn t()", "fn t(body: fn())"); + assert_eq!(hits_in("crates/x/src/tests.rs", ¶meter, &ctx), [(8, "no-assertion")], "a function parameter shadows the asserting helper"); + let later = src.replace(" keeping(body);", " keeping(body);\n {\n let body = || {};\n let _ = body;\n }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &later, &ctx), [], "a binding in a later block does not reach the call"); + let after = src.replace(" keeping(body);", " keeping(body);\n let body = || {};\n let _ = body;"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after, &ctx), [], "a binding after the call"); + let looped = src.replace(" keeping(body);", " for body in [|| {}] {\n keeping(body);\n }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &looped, &ctx), [(8, "no-assertion")], "a loop pattern shadows the helper in the loop body"); + let after_loop = src.replace(" keeping(body);", " for body in [|| {}] {\n let _ = body;\n }\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after_loop, &ctx), [], "the helper after the loop"); + let unused = src.replace(" keeping(body);", " let _unused = (body,);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &unused, &ctx), [(8, "no-assertion")], "a tuple that is never called"); + let dropped = src.replace(" keeping(body);", " (body,);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &dropped, &ctx), [(8, "no-assertion")], "a tuple in a statement of its own"); + let table = src.replace(" keeping(body);", " let cases = [(\"case\", body)];\n run(&cases);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &table, &ctx), [], "a table of named cases"); + let idle = src.replace("assert_eq!(f(), 1);", "f();"); + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), idle.clone())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &idle, &ctx), [(8, "no-assertion")], "a passed body that checks nothing"); + } + + #[test] + fn a_match_arm_binding_shadows_a_helper_only_in_its_arm() { + let src = "fn body() { assert_eq!(f(), 1); }\n#[test]\nfn t() {\n match Some(|| {}) { Some(body) => keeping(body), None => () }\n}\n"; + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), src.to_owned())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [(3, "no-assertion")], "a match-arm pattern shadows the helper"); + let after = src.replace("None => () }", "None => () }\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after, &ctx), [], "the helper after the match"); + } + + #[test] + fn a_dropped_helper_value_is_not_a_check() { + let src = "fn keeping(test: fn()) {\n test();\n}\nfn body() {\n assert_eq!(f(), 1);\n}\n#[test]\nfn t() {\n keeping(body);\n}\n"; + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), src.to_owned())]), ..Ctx::default() }; + let stored = src.replace(" keeping(body);", " let _unused = Some(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &stored, &ctx), [(8, "no-assertion")], "a constructor only stores the helper"); + let boxed = src.replace(" keeping(body);", " let _ = Box::new(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &boxed, &ctx), [(8, "no-assertion")], "a boxed helper that is dropped"); + let called = src.replace(" keeping(body);", " let _ = keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &called, &ctx), [], "a call runs even when its result is dropped"); + let dropped = src.replace(" keeping(body);", " drop(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &dropped, &ctx), [(8, "no-assertion")], "a dropped callback"); + for call in ["std::mem::drop", "mem::drop", "forget", "std::mem::forget", "mem::forget"] { + let forgotten = src.replace(" keeping(body);", &format!(" {call}(body);")); + assert_eq!(hits_in("crates/x/src/tests.rs", &forgotten, &ctx), [(8, "no-assertion")], "a discarded callback: {call}"); + } + for value in ["[body]", "Some(body)"] { + let dropped = src.replace(" keeping(body);", &format!(" drop({value});")); + assert_eq!(hits_in("crates/x/src/tests.rs", &dropped, &ctx), [(8, "no-assertion")], "a discarded stored callback: {value}"); + } + let constructed = src.replace(" keeping(body);", " run(Some(body));"); + assert_eq!(hits_in("crates/x/src/tests.rs", &constructed, &ctx), [], "a stored callback passed to a call"); + let passed = src.replace(" keeping(body);", " run(&[body]);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &passed, &ctx), [], "an array passed to a call"); + let array = src.replace(" keeping(body);", " [body];"); + assert_eq!(hits_in("crates/x/src/tests.rs", &array, &ctx), [(8, "no-assertion")], "a discarded array"); + for value in ["[body]", "[body, other]", "&[body]", "vec![body]"] { + let passed = src.replace(" keeping(body);", &format!(" run({value});")); + assert_eq!(hits_in("crates/x/src/tests.rs", &passed, &ctx), [], "an array argument: {value}"); + let kept = src.replace(" keeping(body);", &format!(" let cases = {value};\n run(cases);")); + assert_eq!(hits_in("crates/x/src/tests.rs", &kept, &ctx), [], "a kept array: {value}"); + let unused = src.replace(" keeping(body);", &format!(" let _ = {value};")); + assert_eq!(hits_in("crates/x/src/tests.rs", &unused, &ctx), [(8, "no-assertion")], "an unused array: {value}"); + } + } + + #[test] + fn a_pin_counts_only_when_its_assertion_runs_and_no_alias_changes_the_source() { + let pinned = "#[test]\nfn t() {\n let got: Vec = r.items().iter().map(|j| j.n).collect();\n assert_eq!(got, vec![1, 2]);\n assert!(r.items().iter().all(|j| j.ok));\n}\n"; + for assertion in ["std::assert_eq!(got, vec![1, 2]);", "core::assert_eq!(got, vec![1, 2]);"] { + let qualified = pinned.replace("assert_eq!(got, vec![1, 2]);", assertion); + assert_eq!(hits(&qualified), [], "{assertion}"); + } + for assertion in [ + "let _check = || assert_eq!(got, vec![1]);", + "if ready { assert_eq!(got, vec![1]); }", + "match ready { true => assert_eq!(got, vec![1]), false => () }", + "while ready { assert_eq!(got, vec![1]); }", + "for _ in rounds { assert_eq!(got, vec![1]); }", + ] { + let conditional = pinned.replace("assert_eq!(got, vec![1, 2]);", assertion); + assert_eq!(only("all-unguarded", &conditional), [(5, "all-unguarded")], "{assertion}"); + } + let block = pinned.replace("assert_eq!(got, vec![1, 2]);", "{ { assert_eq!(got, vec![1]); } }"); + assert_eq!(hits(&block), [], "a plain nested block runs its assertion"); + let after_branch = pinned.replace(" assert_eq!(got", " if ready {} else {}\n assert_eq!(got"); + assert_eq!(hits(&after_branch), [], "an earlier branch does not contain the pinning assertion"); + for change in ["let items = r.items(); items.clear();", "let (items,) = (r.items(),); items.clear();", "clear(r.items());"] { + let aliased = pinned.replace(" assert!(r.items()", &format!(" {change}\n assert!(r.items()")); + assert_eq!(only("all-unguarded", &aliased), [(6, "all-unguarded")], "{change}"); + } + let read = pinned.replace(" assert!(r.items()", " r.items();\n assert!(r.items()"); + assert_eq!(hits(&read), [], "a standalone getter read preserves the pinned source"); + } + + #[test] + fn all_over_a_literal_range_or_a_pinned_source_is_guarded() { + let range = "#[test]\nfn t() {\n assert!((0..3).all(|i| a[i] == b[i]));\n}\n"; + assert_eq!(hits(range), []); + assert_eq!(hits(&range.replace("(0..3)", "(0..n)")), [(3, "all-unguarded")], "a range whose end the test does not show"); + let pinned = "#[test]\nfn t() {\n let got: Vec = r.items().iter().map(|j| j.n).collect();\n assert_eq!(got, vec![1, 2]);\n assert!(r.items().iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(pinned), []); + assert_eq!(hits(&pinned.replace("vec![1, 2]", "vec![]")), [(5, "all-unguarded")], "pinned to an empty list"); + assert_eq!(hits(&pinned.replace("= r.items()", "= other.items()")), [(5, "all-unguarded")], "a list made from another receiver"); + let shadowed = "#[test]\nfn t() {\n let got = f();\n assert_eq!(got, vec![1]);\n let got: Vec = r.items().iter().map(|j| j.n).collect();\n assert!(r.items().iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(shadowed), [(6, "all-unguarded")], "the pinned binding is not the one made from the receiver"); + let cleared = pinned.replace(" assert!(r.items()", " r.clear();\n assert!(r.items()"); + assert_eq!(hits(&cleared), [(6, "all-unguarded")], "the receiver changed after the assertion"); + let cleared_items = pinned.replace(" assert!(r.items()", " r.items().clear();\n assert!(r.items()"); + assert_eq!(hits(&cleared_items), [(6, "all-unguarded")], "the receiver's items changed after the assertion"); + let early = pinned.replace(" assert_eq!(got", " r.clear();\n assert_eq!(got"); + assert_eq!(hits(&early), [(6, "all-unguarded")], "the receiver changed between the binding and the assertion"); + let taken = pinned.replace(" assert!(r.items()", " assert!(r.take_items().is_some());\n assert!(r.items()"); + assert_eq!(hits(&taken), [(6, "all-unguarded")], "an assertion changes the receiver after the pinning assertion"); + let reset = pinned.replace(" assert!(r.items()", " reset(&r);\n assert!(r.items()"); + assert_eq!(hits(&reset), [(6, "all-unguarded")], "a shared borrow passed to a call may change interior-mutable items"); + let bound = pinned.replace(" assert!(r.items()", " let n = count(&r);\n assert!(r.items()"); + assert_eq!(hits(&bound), [(6, "all-unguarded")], "a call whose result is bound may still change interior-mutable items"); + let asserted = pinned.replace(" assert!(r.items()", " assert!(count(&r) > 0);\n assert!(r.items()"); + assert_eq!(hits(&asserted), [], "a shared borrow read in an assertion"); + let counted = pinned.replace(" assert!(r.items()", " assert_eq!(r.unhandled_rejection_count(), 2);\n assert!(r.items()"); + assert_eq!(hits(&counted), [], "a count getter preserves the pinned source"); + let chained = pinned.replace(".map(|j| j.n)", ".map(|j| j.n).chain([1])"); + assert_eq!(hits(&chained), [(5, "all-unguarded")], "a list that is not empty without the receiver's items"); + let reassigned = pinned.replace(" assert_eq!(got", " got = vec![1, 2];\n assert_eq!(got"); + assert_eq!(hits(&reassigned), [(6, "all-unguarded")], "the snapshot was replaced before the assertion"); + let pushed = pinned.replace(" assert_eq!(got", " got.push(1);\n assert_eq!(got"); + assert_eq!(hits(&pushed), [(6, "all-unguarded")], "the snapshot changed before the assertion"); + let read_first = pinned.replace(" assert_eq!(got", " assert!(got.len() < 9);\n assert_eq!(got"); + assert_eq!(hits(&read_first), [], "a read of the snapshot before the assertion"); + let word = "#[test]\nfn t() {\n let plain = word();\n assert_eq!(gaps(&plain), [0.0, 0.0]);\n let gaps = gaps(&plain);\n assert!(gaps.iter().all(|g| g.abs() < 1e-6));\n}\n"; + assert_eq!(hits(word), []); + assert_eq!(hits(&word.replace("gaps(&plain), [", "gaps(&other), [")), [(6, "all-unguarded")], "a literal about another value"); + assert_eq!(hits(&word.replace("gaps(&plain), [", "ids(&plain), [")), [(6, "all-unguarded")], "a literal about another call on the value"); + let emptied = word.replace(" let gaps = gaps(&plain);\n", " let mut gaps = gaps(&plain);\n gaps.clear();\n"); + assert_eq!(hits(&emptied), [(7, "all-unguarded")], "a receiver that may change after its binding"); + let rebound = word.replace(" assert_eq!(gaps(&plain), [0.0, 0.0]);\n", "").replace( + " let gaps = gaps(&plain);", + " let gaps = gaps(&plain);\n let plain = other();\n assert_eq!(gaps(&plain), [0.0, 0.0]);", + ); + assert_eq!(hits(&rebound), [(7, "all-unguarded")], "the assertion reads a later binding of the source"); + } + + #[test] + fn all_over_every_row_of_a_constant_table_is_guarded() { + let src = "const TABLE: [u8; 2] = [1, 2];\nfn reasons(app: &App, key: u8) -> Vec> {\n TABLE.iter().map(|r| app.reason(r, key)).collect()\n}\n#[test]\nfn t() {\n let app = App::new();\n assert!(reasons(&app, 2).iter().all(|r| r.is_none()));\n}\n"; + assert_eq!(hits(src), []); + let shadowed = src.replace(" assert!", " let reasons = |_: &App, _: u8| Vec::>::new();\n assert!"); + assert_eq!(hits(&shadowed), [(9, "all-unguarded")], "a local binding shadows the file's function"); + let twice = format!("{src}mod other {{\n fn reasons(_: &App, _: u8) -> Vec> {{\n Vec::new()\n }}\n}}\n"); + assert_eq!(hits(&twice), [(8, "all-unguarded")], "another module defines a function of the same name"); + let keyed = src.replace(".map(|r|", ".filter(|r| **r == key).map(|r|"); + assert_eq!(hits(&keyed), [(8, "all-unguarded")], "a filter on a plain value may drop every row"); + let state = src.replace(".map(|r|", ".filter(|r| app.has(r)).map(|r|"); + assert_eq!(hits(&state), [(8, "all-unguarded")], "a filter on the state the test builds"); + let empty = src.replace("[u8; 2] = [1, 2]", "[u8; 0] = []"); + assert_eq!(hits(&empty), [(8, "all-unguarded")], "an empty table"); + let elsewhere = src.replace("const TABLE: [u8; 2] = [1, 2];\n", ""); + assert_eq!(hits(&elsewhere), [(7, "all-unguarded")], "a table whose length the file does not show"); + let map_while = src.replace(".map(|r| app.reason(r, key))", ".map_while(|r| app.reason(r, key))"); + assert_eq!(hits(&map_while), [(8, "all-unguarded")], "another step that drops rows"); + let optional = src + .replace("-> Vec>", "-> Option>>") + .replace(".map(|r| app.reason(r, key))", ".map(|r| Some(app.reason(r, key)))") + .replace(".all(|r| r.is_none())", ".all(|r| r.len() == 1)"); + assert_eq!(hits(&optional), [(8, "all-unguarded")], "collecting into an option can discard every row"); + } + + #[test] + fn an_ignored_diagnostic_that_prints_needs_no_assertion() { + let diagnostic = "#[test]\n#[ignore = \"manual timing\"]\nfn t() {\n let n = f();\n eprintln!(\"{n:?}\");\n}\n"; + assert_eq!(hits(diagnostic), []); + assert_eq!(hits(&diagnostic.replace(" eprintln!(\"{n:?}\");\n", "")), [(3, "no-assertion")], "an ignored test that prints nothing"); + assert_eq!(hits(&diagnostic.replace("#[ignore = \"manual timing\"]\n", "")), [(2, "no-assertion")], "a test that runs and only prints"); + } } From df12f897d4be9797c91c96da84594646ea7717a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 01:11:04 -0800 Subject: [PATCH 06/11] xtask: test-lint reads a closure body past turbofish commas An expression closure such as `|body: fn()| forward::(body)` ended at the comma inside the turbofish, so a parameter named like an asserting helper stopped shadowing it at that comma. The closure body now skips a turbofish whole. A count or emptiness getter on a pinned snapshot (`let _ = got.len();`) keeps the pin; only a read of the receiver itself that is bound or passed to a call may hand out an alias. --- xtask/src/test_lint.rs | 46 +++++++++++++++++++++++++++++------------- 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index f6b8a6e2b1..ec88e985fd 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2410,8 +2410,10 @@ fn touched_after(body: &[u8], name: &str, from: usize, receiver: &str) -> bool { || tail.starts_with([')', ']', '}', ',']) || [".iter()", ".len()", ".is_empty()", ".first()", ".last()", ".get(", ".contains("].iter().any(|method| tail.starts_with(method)) }); + // A read of the receiver bound to another local or passed to a call may hand out an alias; + // a count or emptiness getter returns a plain value. let read_only = assertion || binds_receiver || body_level_statement(body, at); - !((read || getter) && read_only || shared) + !(getter || (read && read_only) || shared) }) } @@ -4126,20 +4128,31 @@ fn closure_binding(body: &[u8], name: &str, before: usize) -> Option { let end = match body.get(from) { Some(b'{') => matching(body, from), _ => { - let mut depth = 0usize; - (from..body.len()).find(|&k| match body[k] { - b'(' | b'[' | b'{' => { - depth += 1; - false + // The expression body ends at the first `,`, `;` or closing bracket outside its own + // brackets; a turbofish (`forward::(body)`) is skipped whole. + let (mut depth, mut k, mut end) = (0usize, from, None); + while k < body.len() { + let next = skip_turbofish(body, k); + if next != k { + k = next; + continue; } - b')' | b']' | b'}' if depth == 0 => true, - b')' | b']' | b'}' => { - depth -= 1; - false + match body[k] { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' if depth == 0 => { + end = Some(k); + break; + } + b')' | b']' | b'}' => depth -= 1, + b',' | b';' if depth == 0 => { + end = Some(k); + break; + } + _ => {} } - b',' | b';' => depth == 0, - _ => false, - }) + k += 1; + } + end } }; if !words(params, name.as_bytes(), 0, params.len()).is_empty() && from <= before && end.is_some_and(|end| before < end) { @@ -7902,6 +7915,11 @@ mod tests { assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [(3, "no-assertion")], "a match-arm pattern shadows the helper"); let after = src.replace("None => () }", "None => () }\n keeping(body);"); assert_eq!(hits_in("crates/x/src/tests.rs", &after, &ctx), [], "the helper after the match"); + let turbofish = src.replace( + "match Some(|| {}) { Some(body) => keeping(body), None => () }", + "let cb = |body: fn()| forward::(body);\n cb(|| {});", + ); + assert_eq!(hits_in("crates/x/src/tests.rs", &turbofish, &ctx), [(3, "no-assertion")], "a turbofish comma does not end the closure"); } #[test] @@ -8002,7 +8020,7 @@ mod tests { assert_eq!(hits(&reassigned), [(6, "all-unguarded")], "the snapshot was replaced before the assertion"); let pushed = pinned.replace(" assert_eq!(got", " got.push(1);\n assert_eq!(got"); assert_eq!(hits(&pushed), [(6, "all-unguarded")], "the snapshot changed before the assertion"); - let read_first = pinned.replace(" assert_eq!(got", " assert!(got.len() < 9);\n assert_eq!(got"); + let read_first = pinned.replace(" assert_eq!(got", " let _ = got.len();\n assert_eq!(got"); assert_eq!(hits(&read_first), [], "a read of the snapshot before the assertion"); let word = "#[test]\nfn t() {\n let plain = word();\n assert_eq!(gaps(&plain), [0.0, 0.0]);\n let gaps = gaps(&plain);\n assert!(gaps.iter().all(|g| g.abs() < 1e-6));\n}\n"; assert_eq!(hits(word), []); From b8e72d686c0a1543361d18256953510f2e3d57f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 01:55:10 -0800 Subject: [PATCH 07/11] xtask: test-lint checks a base file's blob size before reading it The changed-lines mode read each base file with `git show` and only then compared the length of the trimmed, lossily decoded text with the 16 MiB limit, so a large blob was loaded in full before it was skipped, and trailing whitespace and invalid UTF-8 changed the length it was judged by. The base reads now take each blob's size from one `git ls-tree -l` listing of `crates`, `apps` and `xtask` (or `git cat-file -s` for a path the listing does not hold) and run `git show` only for blobs within the limit. --- xtask/src/test_lint.rs | 111 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 109 insertions(+), 2 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index c95215cd4c..d44b044412 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -88,8 +88,9 @@ use std::cell::{OnceCell, RefCell}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::io::Write; use std::path::Path; -use std::process::Command; +use std::process::{Command, Stdio}; /// Test files that read Rust source on purpose: they audit the source tree. pub const SOURCE_AUDITS: &[&str] = &[ @@ -343,7 +344,8 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { // Files that load a module through `#[path]`, found with `git grep` (untracked files included) // instead of reading the tree, and the target roots beside a shared `tests//mod.rs`. let overrides = with_root_routes(discover_path_overrides(root, None, &read_work), &files); - let read_base = cached_read(|p| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE)); + let base_sizes = base_blob_sizes(root, &base); + let read_base = cached_read(|p| read_base_blob(root, &base, p, MAX_FILE, base_sizes.as_ref())); // The base's target roots come from the base tree: a root the change deleted still loaded the // shared module beside it. let base_overrides = @@ -626,6 +628,74 @@ fn git(root: &Path, args: &[&str]) -> Result { Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned()) } +/// The file `path` as it is at `rev`, or `None` when it is missing there or its blob is larger +/// than `limit` bytes. `size` and `show` take the `rev:path` object name and give the blob's +/// size and text; a blob over the limit is never passed to `show`. +fn read_blob(rev: &str, path: &str, limit: u64, size: impl Fn(&str) -> Option, show: impl Fn(&str) -> Option) -> Option { + let spec = format!("{rev}:{path}"); + if size(&spec)? > limit { + return None; + } + show(&spec) +} + +/// [`read_blob`] through Git in `root`. +fn read_git_blob(root: &Path, rev: &str, path: &str, limit: u64) -> Option { + let size = |spec: &str| git(root, &["cat-file", "-s", spec]).ok()?.parse().ok(); + read_blob(rev, path, limit, size, |spec| git(root, &["show", spec]).ok()) +} + +fn read_base_blob(root: &Path, rev: &str, path: &str, limit: u64, sizes: Option<&HashMap>) -> Option { + match sizes.and_then(|sizes| sizes.get(path)).copied() { + Some(size) => read_blob(rev, path, limit, |_| Some(size), |spec| git(root, &["show", spec]).ok()), + None => read_git_blob(root, rev, path, limit), + } +} + +/// The size of each `.rs` blob in the tree at `rev`, or `None` when either Git command fails. +fn base_blob_sizes(root: &Path, rev: &str) -> Option> { + let list = git(root, &["ls-tree", "-r", "-z", "--name-only", rev, "--", "crates", "apps", "xtask"]).ok()?; + // Each batch request is one line; paths with newlines use read_git_blob instead. + let paths: Vec<&str> = list.split('\0').filter(|path| is_scanned(path) && !path.contains('\n')).collect(); + let input: String = paths.iter().map(|path| format!("{rev}:{path}\n")).collect(); + let mut child = Command::new("git") + .current_dir(root) + .arg("cat-file") + .arg("--batch-check=%(objectsize)") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .ok()?; + let mut stdin = child.stdin.take()?; + let output = std::thread::scope(|scope| { + let writer = match std::thread::Builder::new().spawn_scoped(scope, move || stdin.write_all(input.as_bytes())) { + Ok(writer) => writer, + Err(_) => { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + }; + let output = child.wait_with_output().ok(); + writer.join().ok()?.ok()?; + output + })?; + if !output.status.success() { + return None; + } + let output = String::from_utf8_lossy(&output.stdout); + let mut lines = output.lines(); + let mut sizes = HashMap::new(); + for path in paths { + let size = lines.next()?; + if !size.ends_with("missing") { + sizes.insert(path.to_owned(), size.parse().ok()?); + } + } + Some(sizes) +} + fn resolve_base(root: &Path, explicit: Option) -> Result { if let Some(rev) = explicit.or_else(|| std::env::var("TEST_LINT_BASE").ok().filter(|v| !v.is_empty())) { return git(root, &["rev-parse", "--verify", "--quiet", &format!("{rev}^{{commit}}")]) @@ -7390,6 +7460,43 @@ mod tests { std::fs::remove_dir_all(root).unwrap(); } + #[test] + fn base_blobs_over_the_limit_are_not_read() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("test-lint-blob-{}-{unique}", std::process::id())); + std::fs::create_dir_all(root.join("crates/x/src")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + // 1 byte of text and 40 of trailing whitespace: the blob is 41 bytes. + std::fs::write(root.join("crates/x/src/padded.rs"), format!("x{}", " \n".repeat(20))).unwrap(); + std::fs::write(root.join("crates/x/src/small.rs"), "fn f() {}\n").unwrap(); + std::fs::write(root.join("crates/x/src/other.txt"), "other\n").unwrap(); + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + assert_eq!(read_git_blob(&root, &base, "crates/x/src/padded.rs", 8), None, "the blob's size counts, not its trimmed text"); + assert_eq!(read_git_blob(&root, &base, "crates/x/src/padded.rs", 41).as_deref(), Some("x")); + assert_eq!(read_git_blob(&root, &base, "crates/x/src/small.rs", 10).as_deref(), Some("fn f() {}")); + assert_eq!(read_git_blob(&root, &base, "crates/x/src/missing.rs", 10), None); + let sizes = base_blob_sizes(&root, &base).unwrap(); + assert_eq!(sizes.get("crates/x/src/padded.rs"), Some(&41)); + assert!(!sizes.contains_key("crates/x/src/other.txt")); + assert_eq!(read_base_blob(&root, &base, "crates/x/src/other.txt", 6, Some(&sizes)).as_deref(), Some("other")); + assert_eq!(read_base_blob(&root, &base, "crates/x/src/other.txt", 5, Some(&sizes)), None); + assert_eq!(read_base_blob(&root, &base, "crates/x/src/padded.rs", 8, Some(&sizes)), None); + assert!(base_blob_sizes(&root, "missing-revision").is_none()); + // A blob over the limit is not read at all. + let shown = RefCell::new(vec![]); + let show = |spec: &str| { + shown.borrow_mut().push(spec.to_owned()); + Some(String::new()) + }; + assert_eq!(read_blob("r", "big.rs", 8, |_| Some(9), show), None); + assert_eq!(read_blob("r", "fits.rs", 8, |_| Some(8), show).as_deref(), Some("")); + assert_eq!(read_blob(&base, "crates/x/src/padded.rs", 8, |_| sizes.get("crates/x/src/padded.rs").copied(), show), None); + assert_eq!(read_blob(&base, "crates/x/src/padded.rs", 41, |_| sizes.get("crates/x/src/padded.rs").copied(), show).as_deref(), Some("")); + assert_eq!(*shown.borrow(), ["r:fits.rs".to_owned(), format!("{base}:crates/x/src/padded.rs")]); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn base_root_routes_come_from_the_base_tree() { let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); From fde52f43a262c201ce2c00ea199ac5581ebcc08d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 02:31:56 -0800 Subject: [PATCH 08/11] xtask: test-lint resolves shadowed helpers, literal selectors and aliases - A renamed import (`use super::other::near as comparison;`) no longer counts as a call with a path; an import that keeps the name still does. - A bare call to a helper's name checks for a local binding in scope (`let near = || {}; near();`), skipping type annotations, field labels and path segments in patterns. - Helpers passed in assertion failure messages no longer count as checks. - A match-arm binding covers the arm's guard, and the arm's pattern stops at the block of the arm before it. - `#[ ignore = "..."]` with whitespace is read as an ignore attribute, both for diagnostic tests and for ignore-without-reason. - Literal ranges read `0x`, `0o` and `0b` bounds. - A pin compares literal arguments (`r.items("active")` against `r.items("archived")`), and does not count when a clone or borrow of the source made before the snapshot is still alive. - A function parameter named like a constant table is not the table. --- xtask/src/test_lint.rs | 434 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 397 insertions(+), 37 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index ec88e985fd..aa75ca051f 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1180,6 +1180,11 @@ const COMMON: &[&str] = &[ /// The names called in `m[from..to]`: functions (`name(`, also through a path), methods /// (`.name(`), including calls with turbofish arguments, and macros (`name!`). fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { + calls_at(m, from, to).into_iter().map(|(name, method, _)| (name, method)).collect() +} + +/// [`calls`] with the offset of each called name. +fn calls_at(m: &[u8], from: usize, to: usize) -> Vec<(String, bool, usize)> { let m = &m[..to]; let mut out = vec![]; let mut i = from; @@ -1196,7 +1201,7 @@ fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { let name = String::from_utf8_lossy(&m[i..end]).into_owned(); let method = i > 0 && m[i - 1] == b'.'; if !KEYWORDS.contains(&name.as_str()) { - out.push((if bang { format!("{name}!") } else { name }, method)); + out.push((if bang { format!("{name}!") } else { name }, method, i)); } } i = end; @@ -1369,10 +1374,50 @@ pub fn asserting_helpers(files: &[(String, String)]) -> HashMap bool { let name = name.trim_end_matches('!'); - words(m, name.as_bytes(), 0, m.len()).into_iter().any(|at| m[..at].trim_ascii_end().ends_with(b"::")) + words(m, name.as_bytes(), 0, m.len()).into_iter().any(|at| { + let after = skip_ws(m, at + name.len()); + let renamed = m[after..].starts_with(b"as") && !m.get(after + 2).copied().is_some_and(is_ident) && { + let mut alias = skip_ws(m, after + 2); + if m[alias..].starts_with(b"r#") { + alias += 2; + } + let alias_end = alias + m[alias..].iter().take_while(|&&c| is_ident(c)).count(); + &m[alias..alias_end] != name.as_bytes() + }; + m[..at].trim_ascii_end().ends_with(b"::") && !(renamed && in_use(m, at)) + }) +} + +/// Whether the masked text at `at` is inside a `use` declaration, its groups (`use a::{b, c}`) +/// included. +fn in_use(m: &[u8], at: usize) -> bool { + let mut depth = 0usize; + let mut start = 0; + for i in (0..at).rev() { + match m[i] { + b'}' => depth += 1, + b'{' if depth > 0 => depth -= 1, + b'{' if m[..i].trim_ascii_end().ends_with(b"::") => {} + b'{' | b';' if depth == 0 => { + start = i + 1; + break; + } + _ => {} + } + } + let mut s = m[start..at].trim_ascii_start(); + if let Some(rest) = s.strip_prefix(b"pub").filter(|r| !r.first().copied().is_some_and(is_ident)) { + s = rest.trim_ascii_start(); + if s.first() == Some(&b'(') { + s = matching(s, 0).map_or(&[][..], |close| s[close + 1..].trim_ascii_start()); + } + } + s.starts_with(b"use") && !s.get(3).copied().is_some_and(is_ident) } /// The asserting helpers a test in the file at `path` can reach: for a top-level test, the file's @@ -1577,10 +1622,22 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { 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 = helpers_for(ctx, file.path, file.depths[t.attr] == 0).unwrap_or(&none); - let delegates = calls(m, t.open, t.close) - .iter() - .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)) - || passes_helper(m, t, helpers); + // Failure messages run only after an assertion has failed, so a helper there does not check. + let messages: Vec<(usize, usize)> = asserts.iter().flat_map(|a| a.args.iter().skip(guard_arg_count(&a.name)).copied()).collect(); + let quiet = |at: usize| !messages.iter().any(|&(from, to)| from <= at && at < to); + // A bare call of a helper's name reaches a local binding of that name where one is in scope; a + // name that says it checks (`check_…`) counts either way. + let delegates = calls_at(m, t.open, t.close).iter().any(|(n, method, at)| { + n != &t.name + && quiet(*at) + && !(n.ends_with('!') && is_assert_macro(n)) + && is_helper_call(n, *method, helpers) + && (*method + || n.ends_with('!') + || is_helper_call(n, false, &HashSet::new()) + || m[..*at].trim_ascii_end().ends_with(b"::") + || !shadows_helper(m, t.fn_at, t.open, t.close, n.as_bytes(), *at)) + }) || passes_helper(m, t, helpers, &quiet); let checks = checks_itself(m, t.open, t.close); let should_panic = should_panic_attr(m, t.attr, t.fn_at); let diagnostic = ignored_with_reason(file, t.attr, t.fn_at) && prints(m, t.open, t.close); @@ -1598,10 +1655,11 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { /// Whether a test's body passes an asserting helper by name as a value, an argument or a tuple /// element (`keeping_settings(the_test_body)`, `[("case", case_body), …]`), excluding local bindings -/// and parameters that shadow helper names. -fn passes_helper(m: &[u8], t: &TestFn, helpers: &HashSet) -> bool { +/// and parameters that shadow helper names. Only names at offsets `counts` accepts count. +fn passes_helper(m: &[u8], t: &TestFn, helpers: &HashSet, counts: &dyn Fn(usize) -> bool) -> bool { passed_names(m, t.open, t.close).into_iter().any(|(name, pos)| { - name != t.name + counts(pos) + && name != t.name && !COMMON.contains(&name.as_str()) && helpers.contains(&name) && !shadows_helper(m, t.fn_at, t.open, t.close, name.as_bytes(), pos) @@ -1629,7 +1687,7 @@ fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool { } end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 }; } - if words(body, name, start, end).is_empty() { + if !pattern_binds(body, name, start, end) { return false; } let head = body[..at].trim_ascii_end(); @@ -1649,6 +1707,34 @@ fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool { lets || loops || arm_binding(body, &name, pos).is_some() || closure_binding(body, &name, pos).is_some() } +/// Whether the `let` pattern in `body[start..end]` binds `name`: not in its type annotation +/// (`let cb: body = …`) or as a field label (`let Row { near: _ } = …`). +fn pattern_binds(body: &[u8], name: &[u8], start: usize, end: usize) -> bool { + let annotation = annotation_start(body, start, end); + words(body, name, start, annotation).into_iter().any(|at| { + let after = skip_ws(body, at + name.len()); + let label = after != annotation && body.get(after) == Some(&b':') && body.get(after + 1) != Some(&b':'); + // A path segment (`let model::near = …`) names a constant or unit struct. + let path = body[..at].trim_ascii_end().ends_with(b"::") || body[after..].starts_with(b"::"); + !label && !path + }) +} + +/// The offset of a `let` pattern's type annotation in `body[start..end]`: its `:` outside the +/// pattern's brackets (not a `::` path), or `end` when there is none. +fn annotation_start(body: &[u8], start: usize, end: usize) -> usize { + let mut i = start; + while i < end { + match body[i] { + b'(' | b'[' | b'{' => i = matching(body, i).map_or(end, |close| close + 1), + b':' if body.get(i + 1) == Some(&b':') => i += 2, + b':' => return i, + _ => i += 1, + } + } + end +} + /// The innermost unclosed `(`, `[` or `{` before `at`. fn enclosing_open(m: &[u8], at: usize) -> Option { let mut depth = 0usize; @@ -1762,7 +1848,7 @@ fn ignored_with_reason(file: &File, from: usize, to: usize) -> bool { let m = &file.m; words(m, b"ignore", from, to).into_iter().any(|at| { let j = skip_ws(m, at + "ignore".len()); - m[..at].ends_with(b"#[") + m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")) && m.get(j) == Some(&b'=') && ignore_reason(&file.src[skip_ws(m, j + 1)..]).is_some_and(|body| body.iter().any(|c| !c.is_ascii_whitespace())) }) @@ -1843,13 +1929,19 @@ fn all_unguarded(v: &View) -> Vec { SIZE_CHECKS.iter().any(|g| norm(&body[from..to]).contains(g)) || reads_counted_local(&body, &locals, from, to) }) }); - let sizes = Sizes { file: &v.file.m, consts: OnceCell::new() }; + let sizes = Sizes { file: &v.file.m, consts: OnceCell::new(), src: v.file.src, open: v.t.open, cond: RefCell::default() }; if checked || first_item_guard(&body, &sizes) { return vec![]; } v.asserts .iter() - .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && unguarded_all(&v.first_arg(a), &v.file.m[v.t.open..a.at], &sizes)) + .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())) + .filter(|a| { + let cond = v.first_arg(a); + let lits = a.args.first().map(|&(from, to)| literals_in(v.file.src, &v.file.m, from, to)).unwrap_or_default(); + *sizes.cond.borrow_mut() = (cond.as_ptr() as usize, cond.clone(), lits); + unguarded_all(&cond, &v.file.m[v.t.open..a.at], &sizes) + }) .map(|a| { let mut h = v.hit(a.at, Rule::AllUnguarded, format!("{}!(…all(…)) with no length or emptiness check in the test", a.name)); h.first = v.file.lines.of(v.t.attr); @@ -2308,7 +2400,8 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { return None; } let at = let_init(body, &s, bound).map_or(0, |(_, at)| statement_end(body, at)); - Some((norm(text.as_bytes()), s, at)) + let end = statement_end(body, bound); + Some((norm(text.as_bytes()), s, at, sizes.literals(let_value(body, bound, end), end))) }) } else { None @@ -2318,7 +2411,7 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { return false; } let (left, right) = (norm(&body[a.args[0].0..a.args[0].1]), norm(&body[a.args[1].0..a.args[1].1])); - [(&left, &right), (&right, &left)].into_iter().any(|(pinned, literal)| { + [(&left, &right, a.args[0]), (&right, &left, a.args[1])].into_iter().any(|(pinned, literal, (from, to))| { if literal_len(literal, sizes) == 0 { return false; } @@ -2329,13 +2422,20 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { && plain_local(pinned) && init(pinned, a.at).is_some_and(|(text, at)| { let bound = statement_end(body, at); + let root = root_local(r); + let root_from = let_init(body, root, at).map_or(0, |(_, pos)| statement_end(body, pos)); keeping_base(&text, true) == r + && sizes.receiver_literals(r).is_some_and(|want| sizes.literals(let_value(body, at, bound), bound).starts_with(&want)) && !touched_after(&body[..a.at], pinned, bound, pinned) - && !touched_after(body, root_local(r), bound, r) + && !touched_after(body, root, bound, r) + && !gives_alias(&body[..at], root, root_from) }); // The assertion compares the same call the receiver is bound to (`gaps(&word)`), so its // literal is what the receiver holds. - read || source.as_ref().is_some_and(|(call, s, at)| pinned == call && !touched_after(body, s, *at, r)) + // Literal arguments (`r.items("active")`) are masked, so they are compared from the source. + read || source + .as_ref() + .is_some_and(|(call, s, at, lits)| pinned == call && *lits == sizes.literals(from, to) && !touched_after(body, s, *at, r)) }) }) } @@ -2369,6 +2469,66 @@ fn body_level_statement(body: &[u8], mut at: usize) -> bool { statement } +/// Where the value of the `let` at `at` starts: after its `=`, past the pattern and any type +/// annotation; `end` when it has none. +fn let_value(body: &[u8], at: usize, end: usize) -> usize { + let mut i = at + 3; + while i < end { + match body[i] { + b'(' | b'[' | b'{' => i = matching(body, i).map_or(end, |close| close + 1), + b'=' if !matches!(body.get(i + 1), Some(b'=' | b'>')) => return i + 1, + _ => i += 1, + } + } + end +} + +/// Whether `body[from..]` may keep a second handle to the local `name` that can change what it +/// holds later: a `let` that binds it or a borrow of it (`let b = &r;`), or a clone of it +/// (`r.clone()`, `Rc::clone(&r)`) anywhere. A borrow that ends with its call (`populate(&mut r)`) +/// and a method call on it (`r.push(1)`, `let n = r.len();`) do not. +fn gives_alias(body: &[u8], name: &str, from: usize) -> bool { + if !plain_local(name) { + return true; + } + words(body, name.as_bytes(), from.min(body.len()), body.len()).into_iter().any(|at| { + let statement = body[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let raw = body[statement..at].trim_ascii_start(); + let head = norm(&body[statement..at]); + // `let b = &r;`, `let b = &mut r;` or `let b = r;` keeps the local itself; `let n = r.len();` reads it. + let whole = matches!(body.get(skip_ws(body, at + name.len())), Some(b';' | b',' | b')') | None); + let bound = raw.strip_prefix(b"let").is_some_and(|r| !r.first().copied().is_some_and(is_ident)) + && whole + && ["=&", "=&mut", "="].iter().any(|end| head.ends_with(end)); + let cloned = body[skip_ws(body, at + name.len())..].starts_with(b".clone()") + || ["Rc::clone(&", "Arc::clone(&"].iter().any(|call| head.ends_with(call)); + // A clone passed straight to `drop`, or bound to `_`, is gone before the snapshot. + let dropped = ["drop(", "drop(Rc::clone(&", "drop(Arc::clone(&"].iter().any(|call| head.ends_with(call)) + || head.starts_with("let_=") + || head.starts_with("let_:"); + if !(bound || (cloned && !dropped)) { + return false; + } + // A handle made in a block that closes before the snapshot, or a bound one dropped before + // it, is gone too. + let mut block = enclosing_open(body, at); + while let Some(open) = block.filter(|&o| body[o] != b'{') { + block = enclosing_open(body, open); + } + if block.is_some_and(|open| matching(body, open).is_some()) { + return false; + } + let pattern = raw.strip_prefix(b"let").map(<[u8]>::trim_ascii_start).unwrap_or_default(); + let pattern = pattern.strip_prefix(b"mut ").map_or(pattern, <[u8]>::trim_ascii_start); + let alias = &pattern[..pattern.iter().take_while(|&&c| is_ident(c)).count()]; + let dropped_later = !alias.is_empty() + && words(body, alias, statement_end(body, at), body.len()) + .into_iter() + .any(|use_at| body[..use_at].trim_ascii_end().strip_suffix(b"(").is_some_and(|h| h.trim_ascii_end().ends_with(b"drop"))); + !dropped_later + }) +} + /// The local a receiver path starts from: `r` of `r.items()`. fn root_local(expr: &str) -> &str { let end = expr.bytes().take_while(|&c| is_ident(c)).count(); @@ -2468,7 +2628,14 @@ fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { let table_end = body.bytes().take_while(|&c| is_ident(c) || c == b':').count(); let table = &body[..table_end]; let screaming = !table.is_empty() && table.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_'); - if !screaming || item_len(table, sizes) == 0 || !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()")) { + // A parameter of the same name (`fn rows(TABLE: &[u8])`) is what the body reads. + let binds_table = + split_args(file, params_open + 1, params_close).into_iter().any(|(from, to)| pattern_binds(file, table.as_bytes(), from, to)); + if !screaming + || binds_table + || item_len(table, sizes) == 0 + || !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()")) + { return false; } // The body is the chain alone, of steps that keep every row. @@ -2513,7 +2680,7 @@ fn let_binds(body: &[u8], name: &[u8]) -> bool { } end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 }; } - !words(body, name, start, end).is_empty() + pattern_binds(body, name, start, end) }) } @@ -3210,9 +3377,31 @@ fn field_len(receiver: &str, sizes: &Sizes) -> usize { struct Sizes<'a> { file: &'a [u8], consts: OnceCell>, + /// The file's source, and the offset in it of the test body that offsets are relative to. + src: &'a [u8], + open: usize, + /// The condition being checked: where its masked, whitespace-free text starts in memory, that + /// text, and its string literals' contents in order. + cond: RefCell<(usize, String, Vec>)>, } impl Sizes<'_> { + /// The contents of the string literals in `from..to` of the test body, in order. + fn literals(&self, from: usize, to: usize) -> Vec> { + literals_in(self.src, self.file, self.open + from, self.open + to) + } + + /// The contents of the string literals of `r`, a slice of the condition being checked; `None` + /// when `r` is not one. + fn receiver_literals(&self, r: &str) -> Option>> { + // A character literal's masked text (`''`) does not say which character it holds. + (!r.contains("''")).then_some(())?; + let cond = self.cond.borrow(); + let (base, masked, lits) = &*cond; + let at = (r.as_ptr() as usize).checked_sub(*base).filter(|&at| at + r.len() <= masked.len())?; + let first = masked.get(..at)?.matches('"').count() / 2; + lits.get(first..first + r.matches('"').count() / 2).map(<[Vec]>::to_vec) + } /// An unsigned integer literal (with `_` and an integer suffix allowed) or a `const` of the /// file whose value is one. fn count(&self, text: &str) -> Option { @@ -3220,14 +3409,27 @@ impl Sizes<'_> { } } +/// The contents of the string literals in `from..to`, in order: the source between each pair of +/// quotes that the masked text `m` keeps. +fn literals_in(src: &[u8], m: &[u8], from: usize, to: usize) -> Vec> { + let quotes: Vec = (from..to.min(m.len())).filter(|&i| m[i] == b'"').collect(); + quotes.as_chunks::<2>().0.iter().map(|&[open, close]| src[open + 1..close].to_vec()).collect() +} + fn int_literal(text: &str) -> Option { - let digits = text.bytes().take_while(|c| c.is_ascii_digit() || *c == b'_').count(); - let suffix = &text[digits..]; + // A decimal literal, or a `0x`, `0o` or `0b` one, takes the same suffixes. + let (radix, body) = [("0x", 16), ("0o", 8), ("0b", 2)] + .into_iter() + .find_map(|(prefix, radix)| text.strip_prefix(prefix).map(|rest| (radix, rest))) + .unwrap_or((10, text)); + let digits = body.bytes().take_while(|c| char::from(*c).is_digit(radix) || *c == b'_').count(); + let suffix = &body[digits..]; let suffixes = ["", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize"]; - if digits == 0 || !text.as_bytes()[0].is_ascii_digit() || !suffixes.contains(&suffix) { + let number = body[..digits].replace('_', ""); + if number.is_empty() || (radix == 10 && !text.as_bytes()[0].is_ascii_digit()) || !suffixes.contains(&suffix) { return None; } - text[..digits].replace('_', "").parse().ok() + usize::from_str_radix(&number, radix).ok() } /// `const NAME: T = ;` in a masked file. A name declared more than once with @@ -3605,9 +3807,9 @@ fn ignore_hits(file: &File) -> Vec { let m = &file.m; let mut out = vec![]; for at in words(m, b"ignore", 0, m.len()) { - if !m[..at].ends_with(b"#[") { - continue; - } + // `#[ignore`, with whitespace allowed between the tokens. + let Some(bracket) = m[..at].trim_ascii_end().len().checked_sub(1).filter(|&b| m[b] == b'[') else { continue }; + let Some(hash) = m[..bracket].trim_ascii_end().len().checked_sub(1).filter(|&h| m[h] == b'#') else { continue }; let j = skip_ws(m, at + "ignore".len()); let reason = match m.get(j) { Some(b'=') => { @@ -3619,8 +3821,8 @@ fn ignore_hits(file: &File) -> Vec { if !reason { let test = file.tests.iter().find(|t| t.fn_at > at).map_or("", |t| t.name.as_str()); // The hit sits on `#[ignore`; its span reaches the attribute's `]`, past a reason on a later line. - let mut hit = file.hit(at - 2, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into()); - hit.last = matching(m, at - 1).map_or(hit.line, |close| file.lines.of(close)); + let mut hit = file.hit(hash, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into()); + hit.last = matching(m, bracket).map_or(hit.line, |close| file.lines.of(close)); out.push(hit); } } @@ -4123,7 +4325,6 @@ fn closure_binding(body: &[u8], name: &str, before: usize) -> Option { i = if opens { close + 1 } else { i + 1 }; continue; } - let params = &body[i + 1..close]; let from = skip_ws(body, close + 1); let end = match body.get(from) { Some(b'{') => matching(body, from), @@ -4155,7 +4356,9 @@ fn closure_binding(body: &[u8], name: &str, before: usize) -> Option { end } }; - if !words(params, name.as_bytes(), 0, params.len()).is_empty() && from <= before && end.is_some_and(|end| before < end) { + // A parameter's type (`|_: helper|`) binds nothing. + let binds = split_args(body, i + 1, close).into_iter().any(|(f, t)| pattern_binds(body, name.as_bytes(), f, t)); + if binds && from <= before && end.is_some_and(|end| before < end) { found = Some(i); } i = close + 1; @@ -4163,16 +4366,24 @@ fn closure_binding(body: &[u8], name: &str, before: usize) -> Option { found } -/// The offset of the `=>` of the innermost match arm whose pattern binds `name` and whose body -/// holds `before`: `Some(n) => assert_eq!(n, 1)` binds `n`, `None => …` does not. +/// The offset of the guard, or of the `=>` when there is none, of the innermost match arm whose +/// pattern binds `name` and whose guard or body holds `before`: `Some(n) => assert_eq!(n, 1)` binds +/// `n`, `None => …` does not. fn arm_binding(body: &[u8], name: &str, before: usize) -> Option { let mut found = None; - for arrow in (0..before.min(body.len().saturating_sub(1))).filter(|&i| &body[i..i + 2] == b"=>") { - // The pattern runs back to the `{` or `,` that opens the arm. + for arrow in (0..body.len().saturating_sub(1)).filter(|&i| &body[i..i + 2] == b"=>") { + // The pattern runs back to the `{` or `,` that opens the arm, or to the `}` that ends the + // block body of the arm before it, which needs no comma. let mut depth = 0usize; let mut start = arrow; while start > 0 { match body[start - 1] { + b'}' if depth == 0 + && enclosing_open(body, start - 1) + .is_some_and(|open| matching(body, open) == Some(start - 1) && body[..open].trim_ascii_end().ends_with(b"=>")) => + { + break; + } b')' | b']' | b'}' => depth += 1, b'(' | b'[' | b'{' if depth == 0 => break, b'(' | b'[' | b'{' => depth -= 1, @@ -4183,8 +4394,17 @@ fn arm_binding(body: &[u8], name: &str, before: usize) -> Option { } // A guard (`Some(x) if x == n`) reads names; it does not bind them. let guard = words(body, b"if", start, arrow).first().copied().unwrap_or(arrow); + if guard >= before { + continue; + } let pattern = norm_words(&body[start..guard]); - if words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { + let p = pattern.as_bytes(); + // A field label (`Row { body: _ }`) names a field; it binds nothing. + let label = |at: usize| { + let after = skip_ws(p, at + name.len()); + p.get(after) == Some(&b':') && p.get(after + 1) != Some(&b':') + }; + if !words(p, name.as_bytes(), 0, p.len()).into_iter().any(|at| !label(at)) { continue; } // The arm's body: a block, or an expression up to the `,` or brace that ends the arm. @@ -4209,7 +4429,8 @@ fn arm_binding(body: &[u8], name: &str, before: usize) -> Option { } }; if end.is_some_and(|end| before < end) { - found = Some(arrow); + // The binding starts at the guard, so a `let` inside the guard or the body is later. + found = Some(guard); } } found @@ -8066,5 +8287,144 @@ mod tests { assert_eq!(hits(diagnostic), []); assert_eq!(hits(&diagnostic.replace(" eprintln!(\"{n:?}\");\n", "")), [(3, "no-assertion")], "an ignored test that prints nothing"); assert_eq!(hits(&diagnostic.replace("#[ignore = \"manual timing\"]\n", "")), [(2, "no-assertion")], "a test that runs and only prints"); + assert_eq!(hits(&diagnostic.replace("#[ignore", "#[ ignore")), [], "whitespace after the attribute's bracket"); + assert_eq!( + hits(&diagnostic.replace("#[ignore = \"manual timing\"]", "#[ ignore = \" \"]")), + [(2, "ignore-without-reason"), (3, "no-assertion")], + "a blank reason after whitespace" + ); + assert_eq!(hits("#[test]\n# [ ignore ]\nfn t() {\n assert!(f());\n}\n"), [(2, "ignore-without-reason")], "no reason, with whitespace"); + } + + /// Two files that each define `near`: `own` asserts in it, the other does not. + fn near_files(own: &str) -> Ctx { + let other = "fn near(a: f64) -> bool { a < 1.0 }\n#[test]\nfn u() {\n assert!(near(f()));\n}\n"; + let files = [("crates/x/tests/it/own.rs".to_owned(), own.to_owned()), ("crates/x/tests/it/other.rs".to_owned(), other.to_owned())]; + Ctx { helpers: asserting_helpers(&files), ..Ctx::default() } + } + + #[test] + fn an_import_of_another_files_helper_is_not_a_call_with_a_path() { + let own = "use super::other::near as comparison;\nfn near(a: f64) { assert!(a < 1.0); }\n#[test]\nfn t() {\n near(f());\n}\n"; + assert_eq!(hits_in("crates/x/tests/it/own.rs", own, &near_files(own)), []); + let called = own.replace(" near(f());", " other::near(f());"); + assert_eq!(hits_in("crates/x/tests/it/own.rs", &called, &near_files(&called)), [(4, "no-assertion")], "a call with a path"); + let raw = own.replace(" as comparison", " as r#near"); + assert_eq!(hits_in("crates/x/tests/it/own.rs", &raw, &near_files(&raw)), [(4, "no-assertion")], "a raw alias that keeps the name"); + let imported = own.replace(" as comparison", ""); + assert_eq!(hits_in("crates/x/tests/it/own.rs", &imported, &near_files(&imported)), [(4, "no-assertion")], "an import that keeps the name"); + } + + #[test] + fn a_local_binding_shadows_a_called_helper() { + let own = "fn near(a: f64) { assert!(a < 1.0); }\n#[test]\nfn t() {\n let near = |_: f64| {};\n near(f());\n}\n"; + assert_eq!(hits_in("crates/x/tests/it/own.rs", own, &near_files(own)), [(3, "no-assertion")]); + let after = own.replace(" let near = |_: f64| {};\n near(f());", " near(f());\n let near = |_: f64| {};\n near(f());"); + assert_eq!(hits_in("crates/x/tests/it/own.rs", &after, &near_files(&after)), [], "a call before the binding"); + let named = "fn check_result() { assert!(f()); }\n#[test]\nfn t() {\n let check = check_result;\n check();\n}\n"; + assert_eq!(hits_in("crates/x/tests/it/own.rs", named, &near_files(named)), [], "a name that says it checks"); + } + + /// A test that passes the asserting `body` to `keeping`, and its helpers. + fn body_src() -> (&'static str, Ctx) { + let src = "fn keeping(test: fn()) {\n test();\n}\nfn body() {\n assert_eq!(f(), 1);\n}\n#[test]\nfn t() {\n keeping(body);\n}\n"; + (src, Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), src.to_owned())]), ..Ctx::default() }) + } + + #[test] + fn a_helper_in_an_assertion_message_does_not_delegate() { + let (src, ctx) = body_src(); + let message = src.replace(" keeping(body);", " assert!(parse(input).is_ok(), \"{}\", keeping(body));"); + assert_eq!(hits_in("crates/x/src/tests.rs", &message, &ctx), [(8, "only-weak")], "the message runs only when the check fails"); + let condition = src.replace(" keeping(body);", " assert!(parse(input).is_ok(), \"{}\", 1);\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &condition, &ctx), [], "a call of its own"); + } + + #[test] + fn a_match_arm_binding_shadows_a_helper_in_its_guard() { + let (src, ctx) = body_src(); + let guard = src.replace(" keeping(body);", " match Some(noop as fn()) { Some(body) if run_body(body) => (), _ => () }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &guard, &ctx), [(8, "no-assertion")]); + let after = guard.replace("_ => () }", "_ => () }\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after, &ctx), [], "the helper after the match"); + let label = src.replace(" keeping(body);", " match row() { Row { body: _ } if run_body(body) => (), _ => () }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &label, &ctx), [], "a field label binds nothing"); + let next_arm = src.replace(" keeping(body);", " match row() { Some(body) if ready() => {} _ if run_body(body) => (), _ => () }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &next_arm, &ctx), [], "a guard after a block arm without a comma"); + } + + #[test] + fn a_type_annotation_does_not_shadow_a_helper() { + let (src, ctx) = body_src(); + let typed = format!("type body = fn();\n{}", src.replace(" keeping(body);", " let cb: body = || {};\n keeping(body);")); + assert_eq!(hits_in("crates/x/src/tests.rs", &typed, &ctx), []); + let bound = format!("type body = fn();\n{}", src.replace(" keeping(body);", " let body: body = || {};\n keeping(body);")); + assert_eq!(hits_in("crates/x/src/tests.rs", &bound, &ctx), [(9, "no-assertion")], "a binding with the same name as its type"); + let closure = format!("type body = u8;\n{}", src.replace(" keeping(body);", " let visit = |_: body| keeping(body);\n visit(0);")); + assert_eq!(hits_in("crates/x/src/tests.rs", &closure, &ctx), [], "a closure parameter's type binds nothing"); + } + + #[test] + fn all_over_a_hexadecimal_literal_range_is_guarded() { + let hex = "#[test]\nfn t() {\n assert!((0x1u8..0x3u8).all(|x| x > 0));\n}\n"; + assert_eq!(hits(hex), []); + assert_eq!(hits(&hex.replace("0x1u8..0x3u8", "0b11..0o3")), [(3, "all-unguarded")], "an empty range"); + assert_eq!(hits(&hex.replace("0x1u8..0x3u8", "0b1..0o3")), [], "binary and octal bounds"); + } + + #[test] + fn a_pin_reads_the_same_literal_selector() { + let pinned = "#[test]\nfn t() {\n let got: Vec = r.items(\"active\").iter().map(|j| j.n).collect();\n assert_eq!(got, vec![1]);\n assert!(r.items(\"active\").iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(pinned), []); + let other = pinned.replace("items(\"active\").iter().all", "items(\"archived\").iter().all"); + assert_eq!(hits(&other), [(5, "all-unguarded")], "another selector"); + let chars = + pinned.replace("items(\"active\").iter().map", "items('a').iter().map").replace("items(\"active\").iter().all", "items('b').iter().all"); + assert_eq!(hits(&chars), [(5, "all-unguarded")], "a character selector"); + } + + #[test] + fn a_parameter_named_like_a_table_is_not_the_table() { + let src = "mod other {\n const TABLE: [u8; 2] = [1, 2];\n}\nfn rows(TABLE: &[u8]) -> Vec {\n TABLE.iter().copied().collect()\n}\n#[test]\nfn t() {\n assert!(rows(&[]).iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), [(9, "all-unguarded")]); + } + + #[test] + fn a_pin_does_not_count_when_an_earlier_alias_shares_the_source() { + let rc = "#[test]\nfn t() {\n let r = Rc::new(RefCell::new(vec![1u8]));\n let got: Vec<_> = r.borrow().iter().copied().collect();\n assert_eq!(got, [1]);\n assert!(r.borrow().iter().all(|n| *n > 0));\n}\n"; + assert_eq!(hits(rc), [], "an unchanged source"); + let aliased = rc + .replace(" let got", " let alias = Rc::clone(&r);\n let got") + .replace(" assert!(r.borrow()", " alias.borrow_mut().clear();\n assert!(r.borrow()"); + assert_eq!(hits(&aliased), [(8, "all-unguarded")], "an alias made before the snapshot"); + let populated = rc.replace(" let got", " populate(&mut r);\n let got"); + assert_eq!(hits(&populated), [], "a borrow that ends with its call"); + let counted = rc.replace(" let got", " let _n = r.borrow().len();\n let got"); + assert_eq!(hits(&counted), [], "a getter read before the snapshot"); + let borrowed = rc + .replace(" let got", " let alias = &r;\n let got") + .replace(" assert!(r.borrow()", " alias.borrow_mut().clear();\n assert!(r.borrow()"); + assert_eq!(hits(&borrowed), [(8, "all-unguarded")], "a borrow bound before the snapshot"); + let dropped = rc.replace(" let got", " drop(Rc::clone(&r));\n let got"); + assert_eq!(hits(&dropped), [], "a clone dropped before the snapshot"); + let scoped = rc.replace(" let got", " {\n let alias = Rc::clone(&r);\n use_it(&alias);\n }\n let got"); + assert_eq!(hits(&scoped), [], "an alias whose block ends before the snapshot"); + let released = rc.replace(" let got", " let alias = Rc::clone(&r);\n drop(alias);\n let got"); + assert_eq!(hits(&released), [], "an alias dropped before the snapshot"); + let discarded = rc.replace(" let got", " let _ = Rc::clone(&r);\n let got"); + assert_eq!(hits(&discarded), [], "a clone bound to `_`"); + let typed = "#[test]\nfn t() {\n let got: Vec<[u8; \"x\".len()]> = r.items(\"active\").to_vec();\n assert_eq!(got, vec![[1]]);\n assert!(r.items(\"active\").iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(typed), [], "a literal in the snapshot's type"); + } + + #[test] + fn a_field_label_in_a_pattern_does_not_shadow_a_helper() { + let own = "fn near(a: f64) { assert!(a < 1.0); }\n#[test]\nfn t() {\n let Row { near: _ } = row();\n near(f());\n}\n"; + assert_eq!(hits_in("crates/x/tests/it/own.rs", own, &near_files(own)), []); + let path = own.replace("Row { near: _ }", "model::near"); + let alone = Ctx { helpers: asserting_helpers(&[("crates/x/tests/it/own.rs".to_owned(), path.clone())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/tests/it/own.rs", &path, &alone), [], "a path segment binds nothing"); + let bound = own.replace("Row { near: _ }", "Row { near }"); + assert_eq!(hits_in("crates/x/tests/it/own.rs", &bound, &near_files(&bound)), [(3, "no-assertion")], "a field shorthand binds"); } } From 806aec918a9425353fa3cb0689bf9d138cf945c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:11:24 -0800 Subject: [PATCH 09/11] xtask: test-lint census rule counts a computation only where it runs on the entry The census rule leaves out a loop that feeds each entry into a computation. It now checks that the computation runs, and that it runs on the entry: - An alias assigned another value no longer holds the entry, and one assigned the entry holds it. Assignments in an empty loop, an async block, a move closure or a closure the loop never calls do not change the alias, and one that may be skipped does not make one. - A nested for body counts only when its source is a literal range or array that is not empty. - A block in an earlier argument keeps the enclosing || or && that can skip the call. - Calling an async closure counts only when the future is awaited or passed to block_on. - A closure that is not bound with let counts only when it is called where it is written; a parenthesized initializer binds the closure. - A closure call resolves to the binding in scope at the call, so a later let of the same name takes it. - A conjunction inside a parenthesized operand of an asserted && is required, unless an || at its level can bypass it. --- xtask/src/test_lint.rs | 557 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 495 insertions(+), 62 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 44d73697e2..19c8bf3c8d 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1739,10 +1739,14 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { let mut derived: Vec<(String, usize, usize)> = pattern_names(pattern).map(|n| (n, from, to)).collect(); // Where a binding does not read the entry, the name holds another value until its scope ends. let mut shadows: Vec<(String, usize, usize)> = vec![]; + let mut empty_bodies = vec![]; for at in words(b, b"for", from, to) { let Some(&kw) = words(b, b"in", at + 3, to).first() else { continue }; let Some(open) = loop_open(b, kw + 2, to) else { continue }; let Some(close) = matching(b, open).filter(|&c| c < to) else { continue }; + if literal_source_yields(&b[at..open]) == Some(false) { + empty_bodies.push((open, close)); + } shadows.extend(pattern_names(&String::from_utf8_lossy(&b[at + 3..kw])).map(|n| (n, open + 1, close))); } // Simple closure parameters shadow captures in both block and expression bodies. @@ -1776,6 +1780,9 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { let names: Vec = params.split(',').flat_map(|p| pattern_names(p.split(':').next().unwrap_or_default()).collect::>()).collect(); shadows.extend(names.into_iter().map(|n| (n, at + 1, until))); } + // The scopes of nested loop patterns and closure parameters, where an assignment to the name + // changes that binding and not the entry. + let nested_bindings = shadows.clone(); // A field access (`options.c`), a path segment (`defaults::c`) or a field label (`Row { c: x }`) // names a field or an item, not the binding. let is_field = |at: usize, len: usize| { @@ -1791,32 +1798,91 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { .any(|at| !is_field(at, n.len()) && !shadows.iter().any(|(s, a, z)| s == n && *a <= at && at < *z)) }) }; - // Names bound inside the loop from the entry count as the entry. - for at in words(b, b"let", from, to) { - let Some(eq) = - (at + 3..to).find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) - else { + let let_eq = |at: usize| { + (at + 3..to).find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) + }; + // An assignment that starts a statement (`input = fallback();`) changes what the name holds + // until the end of the block that declares it. + let assignments: Vec<(usize, usize)> = (from + 1..to) + .filter(|&i| { + b[i] == b'=' + && !matches!(b.get(i + 1), Some(b'=' | b'>')) + && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>' | b'+' | b'-' | b'*' | b'/' | b'%' | b'&' | b'|' | b'^') + }) + .filter_map(|eq| { + let name_end = from + b[from..eq].trim_ascii_end().len(); + let mut at = name_end; + while at > from && is_ident(b[at - 1]) { + at -= 1; + } + let before = b[from..at].trim_ascii_end(); + (at < name_end && !b[at].is_ascii_digit() && (before.is_empty() || matches!(before.last(), Some(b';' | b'{' | b'}')))).then_some((at, eq)) + }) + .collect(); + // Where the value of the initializer or assigned value after the `=` at `eq` starts. A block + // gives the value of its tail (`{ prepare(); c }`). + let value_start = |eq: usize, end: usize| { + let init = skip_ws(b, eq + 1); + let Some(close) = matching(b, init).filter(|&close| b[init] == b'{' && b[close + 1..end].trim_ascii().is_empty()) else { return eq + 1 }; + let mut i = init + 1; + let mut value = i; + while i < close { + match b[i] { + b'(' | b'[' | b'{' => i = matching(b, i).unwrap_or(close), + b';' => value = i + 1, + _ => {} + } + i += 1; + } + value + }; + let mut steps: Vec<(usize, Option)> = words(b, b"let", from, to).into_iter().map(|at| (at, None)).collect(); + steps.extend(assignments.into_iter().map(|(at, eq)| (at, Some(eq)))); + steps.sort_unstable(); + // Names bound or assigned inside the loop from the entry count as the entry. + for (at, assigned) in steps { + if let Some(eq) = assigned { + let name = String::from_utf8_lossy(b[at..eq].trim_ascii_end()).into_owned(); + let end = statement_end(&b[..to], eq); + let until = words(b, b"let", from, at) + .into_iter() + .filter(|&l| block_close(b, l) > at) + .filter(|&l| let_eq(l).is_some_and(|e| pattern_names(&String::from_utf8_lossy(&b[l + 3..e])).any(|n| n == name))) + .map(|l| (l, block_close(b, l).min(to))) + .chain( + nested_bindings + .iter() + .filter(|(n, since, until)| *n == name && *since <= at && at < *until) + .map(|(_, since, until)| (*since, *until)), + ) + .max_by_key(|&(since, _)| since) + .map_or(to, |(_, until)| until); + // Assignments in move closures leave outer bindings unchanged. Assignments in async + // blocks or uncalled closures do not run; conditional assignments do not make aliases. + if in_move_closure(b, from, to, at) || in_async_block(b, from, at) || in_uncalled_closure(b, from, to, at, &[]) { + continue; + } + if live(value_start(eq, end), end, &derived, &shadows) { + if !runs_with_assertion(b, from, to, at) { + continue; + } + // Assigning the entry again ends what earlier assignments in the same scope stored. + for s in shadows.iter_mut().filter(|s| s.0 == name && s.1 <= at && at < s.2 && s.2 == until) { + s.2 = end; + } + derived.push((name, end, until)); + } else if derived.iter().any(|(d, _, _)| *d == name) && !empty_bodies.iter().any(|&(open, close)| open < at && at < close) { + shadows.push((name, end, until)); + } + continue; + } + let Some(eq) = let_eq(at) else { continue; }; // `if let` and `while let` end their initializer at the conditional's block. let conditional = [b"if".as_slice(), b"while"].iter().any(|kw| b[from..at].trim_ascii_end().ends_with(kw)); let end = if conditional { (eq..to).find(|&i| b[i] == b'{').unwrap_or(to) } else { statement_end(&b[..to], eq) }; - // A block initializer binds the value of its tail (`{ prepare(); c }`). - let mut value = eq + 1; - let init = skip_ws(b, value); - if !conditional && b.get(init) == Some(&b'{') && matching(b, init).is_some_and(|close| b[close + 1..end].trim_ascii().is_empty()) { - let close = matching(b, init).unwrap_or(end); - let mut i = init + 1; - value = i; - while i < close { - match b[i] { - b'(' | b'[' | b'{' => i = matching(b, i).unwrap_or(close), - b';' => value = i + 1, - _ => {} - } - i += 1; - } - } + let value = if conditional { eq + 1 } else { value_start(eq, end) }; let names: Vec = pattern_names(&String::from_utf8_lossy(&b[at + 3..eq])).collect(); if live(value, end, &derived, &shadows) { // Rebinding from the entry suspends earlier shadows until this block ends. @@ -1966,6 +2032,42 @@ fn numeric_literal(s: &str) -> bool { matches!(&s[i..], "" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "f32" | "f64") } +/// The value of a decimal integer literal such as `3`, `-4`, `1_000` or `2u8`. +fn integer_literal(s: &str) -> Option { + let (sign, digits) = s.strip_prefix('-').map_or((1, s), |rest| (-1, rest)); + let body = ["u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize"] + .iter() + .find_map(|suffix| digits.strip_suffix(suffix)) + .unwrap_or(digits); + if !numeric_literal(digits) || !body.bytes().all(|c| c.is_ascii_digit() || c == b'_') { + return None; + } + body.replace('_', "").parse::().ok().map(|n| sign * n) +} + +/// Whether the source of the `for … in ` head `head` yields at least one item, for an +/// integer range with literal bounds (`0..3` and `0..=0` do, `0..0` and `5..=4` do not) or an array +/// literal (`[a, b]` and `[x; 2]` do, `[]` and `[x; 0]` do not). `None` for any other source. +fn literal_source_yields(head: &[u8]) -> Option { + let &kw = words(head, b"in", 3, head.len()).first()?; + let mut source: String = String::from_utf8_lossy(&head[kw + 2..]).chars().filter(|c| !c.is_whitespace()).collect(); + while source.starts_with('(') && matching(source.as_bytes(), 0) == Some(source.len() - 1) { + source = source[1..source.len() - 1].to_owned(); + } + if source.starts_with('[') && matching(source.as_bytes(), 0) == Some(source.len() - 1) { + let items = &source[1..source.len() - 1]; + return match top_level_at(items, ";").first() { + Some(&semi) => integer_literal(&items[semi + 1..]).map(|n| n > 0), + None => Some(!items.is_empty()), + }; + } + if let Some((low, high)) = source.split_once("..=") { + return integer_literal(low).zip(integer_literal(high)).map(|(low, high)| low <= high); + } + let (low, high) = source.split_once("..")?; + integer_literal(low).zip(integer_literal(high)).map(|(low, high)| low < high) +} + /// Where the name of a call whose `(` is at `open` ends: right before the `(`, or before the /// `::<…>` of a turbofish (`app.run::(c)`). `None` when no name precedes the `(`. fn call_name_end(b: &[u8], from: usize, open: usize) -> Option { @@ -2008,7 +2110,8 @@ fn call_name_end(b: &[u8], from: usize, open: usize) -> Option { /// assertions pass. A call after `||` in its statement may not run (`menu(c).is_some() || app.run(c)`, /// also with a block as the right operand); the right side of `&&` has to run only in an asserted /// condition. A call inside a closure bound with `let` runs only when the loop calls -/// that closure. +/// that closure ([`closure_calls`]), and a call in a closure that is not bound does not count. A call +/// in a nested `for` body counts only when the loop's source yields an item ([`literal_source_yields`]). fn runs_with_assertion(b: &[u8], from: usize, to: usize, start: usize) -> bool { runs_with_assertion_within(b, from, to, start, &[]) } @@ -2043,12 +2146,16 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } } let prefix = b[head..open].trim_ascii(); + let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { if !runs_with_assertion_within(b, from, to, open, &active) { return false; } + } else if nested_for && literal_source_yields(prefix) != Some(true) { + // A nested `for` body runs only when its source yields an item. + return false; } else if !prefix.ends_with(b"|") - && !(prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace)) + && !nested_for && (prefix.ends_with(b"=>") || [b"async".as_slice(), b"async move"] .iter() @@ -2057,8 +2164,8 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac || (!words(prefix, b"loop", 0, prefix.len()).is_empty() && matching(b, open).is_some_and(|close| !words(b, b"break", open + 1, close).is_empty()))) { - // A nested `for` body is taken to run, like the loop body itself; [`feeds_entry`] keeps - // its own bindings apart. + // A nested `for` body whose source yields an item runs, like the loop body itself; + // [`feeds_entry`] keeps its own bindings apart. return false; } } @@ -2066,8 +2173,13 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac // the operand of `||` or `&&`. let mut stmt = from; let mut braces = 0usize; + // The parenthesis or bracket that most closely encloses the call: a block after it is an + // earlier argument or element (`accept({ 0 }, app.run(c))`), not an earlier statement. + let group = (from..start).rev().find(|&i| matches!(b[i], b'(' | b'[' | b'{') && matching(b, i).is_none_or(|close| start < close)); + let group = group.filter(|&i| b[i] != b'{'); for i in (from..start).rev() { match b[i] { + b'}' if braces == 0 && group.is_some_and(|g| g < i) => braces += 1, // A block that ends before the call closes an earlier statement (`if a || b {} app.run(c)`) // unless an operator joins the call's expression to it. b'}' if braces == 0 && { @@ -2103,8 +2215,8 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac if b[pipe] != b'|' { return None; } - let head = b[stmt..pipe].trim_ascii(); - let head = head.strip_suffix(b"move").or_else(|| head.strip_suffix(b"async")).unwrap_or(head).trim_ascii_end(); + let head = String::from_utf8_lossy(b[stmt..pipe].trim_ascii()); + let head = strip_closure_keywords(&head).0.as_bytes(); if !head.ends_with(b"=") || !head.starts_with(b"let") || !head.get(3).is_some_and(u8::is_ascii_whitespace) { return None; } @@ -2155,42 +2267,162 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac closure = Some(stmt + prefix.len()); } } - // `let run = || app.run(c);`: the closure's body runs only where the loop calls `run`. + // `let run = || app.run(c);`: the closure's body runs only where the loop calls `run`. A closure + // that is not bound with `let` (`Some(|| app.run(c))`) shows no call of it. let Some(end) = closure else { return true }; let head = String::from_utf8_lossy(&b[stmt..end]); - let head = head.trim(); - let head = head.strip_suffix("move").or_else(|| head.strip_suffix("async")).unwrap_or(head).trim_end(); - let Some(binding) = head.strip_suffix('=').map(str::trim).and_then(|h| h.strip_prefix("let")) else { return true }; - let Some(name) = pattern_names(binding).last() else { return true }; - words(b, name.as_bytes(), end, to).into_iter().any(|at| { - // `other.run()` calls a method, not the closure. - b[..at].trim_ascii_end().last() != Some(&b'.') - && b.get(skip_ws(b, at + name.len())) == Some(&b'(') - && runs_with_assertion_within(b, from, to, at, &active) - }) + let (bare, asynchronous) = strip_closure_keywords(head.trim_end()); + // Unwrap parentheses whose outer closing parenthesis ends the initializer. + let unwrapped = (|| { + let mut head = bare; + let mut inner_close = None; + while let Some(prefix) = head.strip_suffix('(') { + let close = matching(b, stmt + prefix.len())?; + if close < start || inner_close.is_some_and(|inner| !b[inner + 1..close].trim_ascii().is_empty()) { + return None; + } + inner_close = Some(close); + head = prefix.trim_end(); + } + inner_close.filter(|&close| b.get(skip_ws(b, close + 1)) == Some(&b';')).map(|_| head) + })(); + let binding_head = unwrapped.unwrap_or(bare); + let Some(binding) = + binding_head.trim_start().strip_suffix('=').and_then(|h| h.strip_prefix("let")).filter(|h| h.starts_with(char::is_whitespace)) + else { + // `(|| app.run(c))()` calls the closure where it is written. + let open = stmt + bare.len(); + let Some(close) = open.checked_sub(1).filter(|&o| b[o] == b'(').and_then(|o| matching(b, o)) else { return false }; + let call = skip_ws(b, close + 1); + if b.get(call) != Some(&b'(') { + return false; + } + if !asynchronous { + return true; + } + let next = matching(b, call).map_or(b.len(), |c| skip_ws(b, c + 1)); + return b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident); + }; + let Some(name) = pattern_names(binding).last() else { return false }; + closure_calls(b, &name, skip_ws(b, stmt), end, to, asynchronous).into_iter().any(|at| runs_with_assertion_within(b, from, to, at, &active)) +} + +/// The head before a closure's parameters with a trailing `move` and `async` removed, and whether +/// the closure is async. +fn strip_closure_keywords(head: &str) -> (&str, bool) { + fn keyword<'a>(h: &'a str, kw: &str) -> Option<&'a str> { + h.strip_suffix(kw).filter(|rest| !rest.ends_with(|c: char| c.is_ascii_alphanumeric() || c == '_')).map(str::trim_end) + } + let head = head.trim_end(); + let head = keyword(head, "move").unwrap_or(head); + match keyword(head, "async") { + Some(head) => (head, true), + None => (head, false), + } +} + +/// Where `b[after..to]` calls the closure that the `let` at `bound` binds to `name`: `name(…)`, not +/// a method (`other.run()`), and not after a later `let` of the same name that is still in scope. +/// Calling an async closure only makes a future, so its call counts only when the future is +/// awaited (`run().await`) or passed to `block_on`. +fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, asynchronous: bool) -> Vec { + let rebinds = |l: usize, at: usize| { + let eq = (l + 3..at).find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')); + // The new name is in scope from the end of its statement (`let run = run();` still calls the + // earlier closure) to the end of its block. + block_close(b, l) > at + && eq.is_some_and(|eq| statement_end(&b[..to], eq) < at && pattern_names(&String::from_utf8_lossy(&b[l + 3..eq])).any(|n| n == name)) + }; + words(b, name.as_bytes(), after, to) + .into_iter() + .filter(|&at| { + let open = skip_ws(b, at + name.len()); + if b[..at].trim_ascii_end().last() == Some(&b'.') || b.get(open) != Some(&b'(') { + return false; + } + if words(b, b"let", bound + 3, at).into_iter().any(|l| rebinds(l, at)) { + return false; + } + if !asynchronous { + return true; + } + let Some(close) = matching(b, open) else { return false }; + let next = skip_ws(b, close + 1); + let awaited = b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident); + awaited || b[..at].trim_ascii_end().ends_with(b"block_on(") + }) + .collect() } /// Whether an `&&` is at the top level of an assertion's first argument. fn asserted_conjunction(b: &[u8], from: usize, to: usize, at: usize) -> bool { macro_calls(b, from, to).iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())).any(|a| { - let Some(&(mut f, mut t)) = a.args.first() else { return false }; - loop { - f += b[f..t].len() - b[f..t].trim_ascii_start().len(); - t = f + b[f..t].trim_ascii_end().len(); - if b.get(f) != Some(&b'(') || matching(b, f) != t.checked_sub(1) { - break; - } - f += 1; - t -= 1; - } - // A top-level `||` lets the assertion pass without the conjunction. - let cond = String::from_utf8_lossy(&b[f..t]); - f <= at && at < t && top_level_at(&cond, "||").is_empty() && top_level_at(&cond, "&&").contains(&(at - f)) + let Some(&(f, t)) = a.args.first() else { return false }; + required_conjunction(b, f, t, at, 0) }) } -/// Whether `start` lies in the block body of a closure bound with `let` in -/// `b[from..to]` (`let run = || { … };`, also `move` or `async`) that the loop never calls. +/// Whether the `&&` at `at` has to hold for the condition `b[f..t]` to hold: it joins the +/// condition's top-level operands, or those of a parenthesized operand of a top-level `&&` +/// (`(a && b) && c`). An `||` at the same level lets the condition hold without it. +fn required_conjunction(b: &[u8], mut f: usize, mut t: usize, at: usize, depth: usize) -> bool { + loop { + f += b[f..t].len() - b[f..t].trim_ascii_start().len(); + t = f + b[f..t].trim_ascii_end().len(); + if b.get(f) != Some(&b'(') || matching(b, f) != t.checked_sub(1) { + break; + } + f += 1; + t -= 1; + } + let cond = String::from_utf8_lossy(&b[f..t]); + if depth > 64 || at < f || t <= at || !top_level_at(&cond, "||").is_empty() { + return false; + } + let ands = top_level_at(&cond, "&&"); + if ands.contains(&(at - f)) { + return true; + } + // The operand that holds `at`, when it is a parenthesized group. + let start = ands.iter().rev().map(|&a| f + a + 2).find(|&s| s <= at).unwrap_or(f); + let end = ands.iter().map(|&a| f + a).find(|&e| e > at).unwrap_or(t); + let open = skip_ws(b, start); + let close = start + b[start..end].trim_ascii_end().len(); + b.get(open) == Some(&b'(') && matching(b, open) == close.checked_sub(1) && required_conjunction(b, open, close, at, depth + 1) +} + +/// Whether `start` lies in the body of an `async` or `async move` block. +fn in_async_block(b: &[u8], from: usize, start: usize) -> bool { + (from..start).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)).any(|open| { + let head = b[from..open].trim_ascii_end(); + let head = head.strip_suffix(b"move").filter(|h| h.last().is_some_and(u8::is_ascii_whitespace)).unwrap_or(head).trim_ascii_end(); + head.strip_suffix(b"async").is_some_and(|h| !h.last().copied().is_some_and(is_ident)) + }) +} + +/// Whether `start` lies in the block or expression body of a move closure. +fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize) -> bool { + words(b, b"move", from, start).into_iter().any(|at| { + let pipe = skip_ws(b, at + 4); + if b.get(pipe) != Some(&b'|') { + return false; + } + let Some(end) = (pipe + 1..to).find(|&i| b[i] == b'|') else { return false }; + let body = skip_ws(b, end + 1); + let mut until = body; + if b.get(body) == Some(&b'{') { + until = matching(b, body).unwrap_or(to).min(to); + } else { + while until < to && !matches!(b[until], b',' | b';' | b')' | b']' | b'}') { + until = if matches!(b[until], b'(' | b'[' | b'{') { matching(b, until).unwrap_or(to) + 1 } else { until + 1 }; + } + } + body <= start && start < until + }) +} + +/// Whether `start` lies in the block body of a closure bound with `let` in `b[from..to]` +/// (`let run = || { … };`, also `move` or `async`) with no call that [`closure_calls`] finds. fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool { let mut depth = 0usize; for i in (from..start).rev() { @@ -2201,18 +2433,14 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & b'{' => { let Some(params) = b[from..i].trim_ascii_end().strip_suffix(b"|") else { continue }; let Some(pipe) = params.iter().rposition(|&c| c == b'|') else { continue }; - let head = params[..pipe].trim_ascii_end(); - let head = String::from_utf8_lossy(head); - let head = head.trim_end(); - let head = head.strip_suffix("move").or_else(|| head.strip_suffix("async")).unwrap_or(head).trim_end(); + let text = String::from_utf8_lossy(params[..pipe].trim_ascii_end()); + let (head, asynchronous) = strip_closure_keywords(&text); let Some(binding) = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { continue }; let Some(name) = pattern_names(binding).last() else { continue }; + let bound = words(b, b"let", from, from + pipe).last().copied().unwrap_or(from); let close = matching(b, i).unwrap_or(to); - if !words(b, name.as_bytes(), close, to).into_iter().any(|at| { - b[..at].trim_ascii_end().last() != Some(&b'.') - && b.get(skip_ws(b, at + name.len())) == Some(&b'(') - && runs_with_assertion_within(b, from, to, at, active) - }) { + if !closure_calls(b, &name, bound, close, to, asynchronous).into_iter().any(|at| runs_with_assertion_within(b, from, to, at, active)) + { return true; } } @@ -8937,6 +9165,211 @@ mod tests { ); } + #[test] + fn census_follows_assignments_to_entry_aliases() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("let mut input = c; input = fallback(); app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an alias assigned another value no longer holds the entry" + ); + assert_eq!( + census("let mut input = c; { input = fallback(); } app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment in a block outlasts the block" + ); + assert_eq!( + census("for mut c in [fallback()] { c = fallback(); } app.run(c); assert!(menu(c).is_some());"), + [], + "an assignment to a nested loop binding ends with its scope" + ); + assert_eq!( + census("let run = |mut c: Command| { c = fallback(); app.run(c) }; run(default()); app.run(c); assert!(menu(c).is_some());"), + [], + "an assignment to a closure parameter ends with its scope" + ); + assert_eq!( + census("let mut input = c; for _ in 0..0 { input = fallback(); } app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in an empty range does not end an alias" + ); + assert_eq!( + census("let mut input = c; for _ in 5..=4 { input = fallback(); } app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in an empty inclusive range does not end an alias" + ); + assert_eq!( + census("let mut input = c; for _ in [x; 0] { input = fallback(); } app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in an array repeated zero times does not end an alias" + ); + assert_eq!( + census("let mut input = c; for x in xs { input = fallback(); } app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment in a loop over an unknown source may end an alias" + ); + assert_eq!( + census("let mut input = c; input = fallback(); input = c; app.run(input); assert!(menu(c).is_some());"), + [], + "an alias assigned the entry again holds it" + ); + assert_eq!( + census("let mut input = fallback(); input = c; app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment from the entry makes an alias" + ); + assert_eq!( + census("let mut input = fallback(); input = { menu(c); fallback() }; app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assigned block gives the value of its tail" + ); + assert_eq!( + census("let mut input = fallback(); let _saved = || { input = c; }; app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment in an uncalled closure does not make an alias" + ); + assert_eq!( + census("let mut input = c; let _saved = || { input = fallback(); }; app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in an uncalled closure does not end an alias" + ); + assert_eq!( + census("let mut input = c; { let _future = async { input = fallback(); }; } app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in an unpolled async block does not end an alias" + ); + assert_eq!( + census("let mut input = c; let _future = async move { input = fallback(); }; app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in an unpolled async move block does not end an alias" + ); + assert_eq!( + census("let mut input = fallback(); if ready { input = c; } app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment that may be skipped does not make an alias" + ); + assert_eq!( + census("let mut input = c; let mut run = move || { input = fallback(); }; run(); app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment to a move capture leaves the outer alias unchanged" + ); + } + + #[test] + fn census_needs_evidence_that_the_call_runs_on_the_entry() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!(census("for _ in 0..0 { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "an empty range never runs its body"); + assert_eq!(census("for x in xs { app.run(c, x); } assert!(menu(c).is_some());"), [(2, "census")], "a source that may be empty"); + assert_eq!(census("for x in 0..=0 { app.run(c, x); } assert!(menu(c).is_some());"), [], "an inclusive range with one value runs"); + assert_eq!(census("for x in [1, 2] { app.run(c, x); } assert!(menu(c).is_some());"), [], "a nonempty array literal runs"); + assert_eq!( + census("let _ = ready || accept({ 0 }, app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "a block in an earlier argument keeps the enclosing ||" + ); + assert_eq!( + census("let _ = accept({ 0 }, app.run(c)); assert!(menu(c).is_some());"), + [], + "a block in an earlier argument does not skip the call" + ); + } + + #[test] + fn census_needs_evidence_that_a_closure_or_conjunction_runs_the_call() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("let run = async || app.run(c); let _future = run(); assert!(menu(c).is_some());"), + [(2, "census")], + "calling an async closure only makes a future" + ); + assert_eq!( + census("let run = async move || app.run(c); let _future = run(); assert!(menu(c).is_some());"), + [(2, "census")], + "calling an async move closure only makes a future" + ); + assert_eq!( + census("let run = async || { app.run(c) }; let _future = run(); assert!(menu(c).is_some());"), + [(2, "census")], + "calling a block-bodied async closure only makes a future" + ); + assert_eq!(census("let run = async || app.run(c); assert!(run().await.is_ok());"), [], "an awaited async closure runs"); + assert_eq!(census("let run = async || { app.run(c) }; assert!(run().await.is_ok());"), [], "an awaited block-bodied async closure runs"); + assert_eq!(census("let _saved = Some(|| app.run(c)); assert!(menu(c).is_some());"), [(2, "census")], "a stored closure is not called"); + assert_eq!(census("let run = (|| app.run(c)); run(); assert!(menu(c).is_some());"), [], "a called parenthesized closure runs"); + assert_eq!( + census("let _run = (|| app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "an uncalled parenthesized closure does not run" + ); + assert_eq!(census("let _ = (|| app.run(c))(); assert!(menu(c).is_some());"), [], "a closure called where it is written runs"); + assert_eq!( + census("let _ = (|| { prepare(); app.run(c) })(); assert!(menu(c).is_some());"), + [], + "a block closure called where it is written runs" + ); + assert_eq!( + census("let _future = (async || app.run(c))(); assert!(menu(c).is_some());"), + [(2, "census")], + "an async closure called where it is written only makes a future" + ); + assert_eq!(census("assert!((async || app.run(c))().await.is_ok());"), [], "an awaited async closure called where it is written runs"); + assert_eq!( + census("let _saved = Some(|| { app.run(c) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a stored block closure is not called" + ); + assert_eq!( + census("let _saved = Some(|| { prepare(); app.run(c) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a later statement of a stored block closure is not run" + ); + assert_eq!(census("let _ = || { prepare(); app.run(c) }; assert!(menu(c).is_some());"), [(2, "census")], "a dropped closure is not called"); + assert_eq!( + census("let _ = ready || { prepare(); app.run(c) }; assert!(menu(c).is_some());"), + [(2, "census")], + "an || before a block can skip it" + ); + assert_eq!( + census("let _ = ready && { prepare(); app.run(c) }; assert!(menu(c).is_some());"), + [(2, "census")], + "an && before a block can skip it" + ); + assert_eq!( + census("let run = || app.run(c); let run = || (); run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a shadowing closure takes the call" + ); + assert_eq!( + census("let run = || { app.run(c) }; let run = || (); run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a shadowing closure takes the call of a block closure" + ); + assert_eq!(census("let run = || app.run(c); run(); assert!(menu(c).is_some());"), [], "a closure called without shadowing runs"); + assert_eq!( + census("let run = || app.run(c); let run = run(); assert!(menu(c).is_some());"), + [], + "a shadowing initializer still calls the earlier closure" + ); + assert_eq!( + census("let run = || app.run(c); { let run = || (); } run(); assert!(menu(c).is_some());"), + [], + "a shadowing closure ends with its block" + ); + assert_eq!( + census("assert!((menu(c).is_some() && app.run(c).is_ok()) && other(c).is_some());"), + [], + "a conjunction inside a required conjunction runs" + ); + assert_eq!( + census("assert!((menu(c).is_some() && app.run(c).is_ok()) || other(c).is_some());"), + [(2, "census")], + "a conjunction on one side of || can be bypassed" + ); + } + #[test] fn census_leaves_out_loops_that_feed_the_entry_into_a_computation() { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); From 12355cb52994d0fdbfd236bd92772d2f324ff682 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:42:17 -0800 Subject: [PATCH 10/11] xtask: test-lint fails on a hit of any rule in the changed lines all-unguarded, only-weak, exit-status-only, no-assertion, early-return, env-gate-unset, census, mirror, constant-echo, fixture-only and exact-pixel only listed their hits before. Their hits on changed lines and tests now fail the check like the other rules. A `// test-lint: allow ` comment still exempts a hit, and hits on unchanged lines still do not fail. A never-run test that builds on macOS or Windows is still listed without failing, since it runs locally on that platform. Docs: docs/development.md. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 52 ++++++++++++++++++++++-------------------- 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/docs/development.md b/docs/development.md index 77e4b736a5..0e528cdab4 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`). `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. A `never-run` test that still builds on macOS or Windows, such as a test of a macOS-only module, is listed without failing; run it locally on that platform. It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it, except a `never-run` test in an unchanged file whose last CI route the change takes away: a changed `mod` declaration or `cfg` in a file that loads it, or a removed `mod` or `#[path]` declaration that was the last one loading it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on a hit of any of its rules: an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`), a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status (`exit-status-only`), a test with no assertion and no asserting helper (`no-assertion`), a silent early `return` on a value from the code under test (`early-return`), an environment variable that no CI leg sets (`env-gate-unset`), and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. A `never-run` test that still builds on macOS or Windows, such as a test of a macOS-only module, is listed without failing; run it locally on that platform. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it, except a `never-run` test in an unchanged file whose last CI route the change takes away: a changed `mod` declaration or `cfg` in a file that loads it, or a removed `mod` or `#[path]` declaration that was the last one loading it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 44d73697e2..7bf34a56be 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -82,9 +82,9 @@ //! rules about a whole test it can be on any line from the line above the test attribute to the //! `fn` line. An allow without a reason exempts nothing. //! -//! `cargo xtask test-lint` fails on hits of `self-compare`, `ignore-without-reason`, `sleep`, -//! `reads-source` and `never-run` (except a test that builds on macOS or Windows) in the lines and -//! tests changed since a base, and lists the other rules' hits there without failing. The base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's +//! `cargo xtask test-lint` fails on a hit of any rule in the lines and tests changed since a base, +//! except a `never-run` test that builds on macOS or Windows, which it lists without failing. The +//! base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's //! merge commit is checked out, and a shallow checkout fetches that parent); elsewhere the merge //! base of `HEAD` and `upstream/main` or `origin/main`. Uncommitted and untracked files count as //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the @@ -223,11 +223,6 @@ impl Rule { } } - /// Whether a hit on a changed line fails the command. The other rules only report. - pub fn fails(self) -> bool { - matches!(self, Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep | Rule::ReadsSource | Rule::NeverRun) - } - fn from_id(id: &str) -> Option { Rule::ALL.into_iter().find(|r| r.id() == id) } @@ -256,14 +251,15 @@ pub struct Hit { /// allow comment there does not exempt it. pub gates: Vec, /// A `never-run` hit on a test that builds on macOS or Windows, which CI does not test on: it is - /// listed with the report-only rules. + /// listed without failing the check. pub report_only: bool, } impl Hit { - /// Whether the hit fails the check when it is on a changed line. + /// Whether the hit fails the check when it is on a changed line: every hit does, except a + /// `never-run` test that builds on macOS or Windows. fn fails(&self) -> bool { - self.rule.fails() && !self.report_only + !self.report_only } fn show(&self) -> String { @@ -555,7 +551,7 @@ fn finish(counted: &[Hit], older: usize, files: usize, base: &str) -> Result<(), let (failing, reported): (Vec<&Hit>, Vec<&Hit>) = counted.iter().partition(|h| h.fails()); if !reported.is_empty() { println!( - "test-lint: {} hit(s) of report-only rules in the lines changed since {base} (they do not fail the check):\n {}", + "test-lint: {} hit(s) on tests that build only on macOS or Windows in the lines changed since {base} (run them there; they do not fail the check):\n {}", reported.len(), listing(&reported).join("\n ") ); @@ -6159,8 +6155,11 @@ mod tests { } #[test] - fn census_is_report_only() { - assert!(!Rule::Census.fails()); + fn census_fails_the_check() { + let census = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.name.starts_with('a'));\n }\n}\n"; + let hits = lint_file("crates/x/src/tests.rs", census, &ctx()); + assert_eq!(hits.iter().map(|h| h.rule).collect::>(), [Rule::Census]); + assert!(finish(&hits, 0, 1, "base").is_err(), "census fails the check"); assert_eq!(Rule::from_id("census"), Some(Rule::Census)); } @@ -7284,23 +7283,26 @@ mod tests { } #[test] - fn only_failing_rules_fail_the_check() { - let failing: Vec<&str> = Rule::ALL.into_iter().filter(|r| r.fails()).map(Rule::id).collect(); - assert_eq!(failing, ["self-compare", "ignore-without-reason", "sleep", "reads-source", "never-run"]); + fn every_rule_fails_the_check() { let ios = "#[cfg(target_os = \"ios\")]\n#[test]\nfn ios() {\n assert_eq!(f(), 1);\n}\n"; assert!(finish(&lint_file("crates/x/src/tests.rs", ios, &ctx()), 0, 1, "base").is_err(), "never-run fails the check"); let weak = "#[test]\nfn weak() {\n assert!(f().is_ok());\n}\n"; let unguarded = "#[test]\nfn all() {\n assert!(f().iter().all(|x| valid(x)));\n}\n"; let skipped = "#[test]\n#[ignore]\nfn skipped() {\n assert_eq!(f(), 1);\n}\n"; + let silent = "#[test]\nfn silent() {\n f();\n}\n"; let hits_of = |src: &str| lint_file("crates/x/src/tests.rs", src, &ctx()); - assert_eq!(finish(&hits_of(unguarded), 0, 1, "base"), Ok(()), "all-unguarded only reports"); - assert_eq!(finish(&hits_of(weak), 0, 1, "base"), Ok(()), "only-weak only reports"); - let all = hits_of(&format!("{weak}{unguarded}{skipped}")); - assert_eq!(all.len(), 3); - let Err(message) = finish(&all, 0, 1, "base") else { panic!("ignore-without-reason fails the check") }; - assert!(message.starts_with("1 test-lint hit(s)"), "{message}"); - assert!(message.contains("[ignore-without-reason] `skipped`"), "{message}"); - assert!(!message.contains("[only-weak]") && !message.contains("[all-unguarded]"), "{message}"); + assert!(finish(&hits_of(unguarded), 0, 1, "base").is_err(), "all-unguarded fails the check"); + assert!(finish(&hits_of(weak), 0, 1, "base").is_err(), "only-weak fails the check"); + assert!(finish(&hits_of(silent), 0, 1, "base").is_err(), "no-assertion fails the check"); + let all = hits_of(&format!("{weak}{unguarded}{skipped}{silent}")); + assert_eq!(all.len(), 4); + let Err(message) = finish(&all, 0, 1, "base") else { panic!("the hits fail the check") }; + assert!(message.starts_with("4 test-lint hit(s)"), "{message}"); + for listed in ["[only-weak] `weak`", "[all-unguarded] `all`", "[ignore-without-reason] `skipped`", "[no-assertion] `silent`"] { + assert!(message.contains(listed), "{listed} in {message}"); + } + let allowed = "#[test]\n// test-lint: allow only-weak the value is random\nfn weak() {\n assert!(f().is_ok());\n}\n"; + assert_eq!(finish(&hits_of(allowed), 0, 1, "base"), Ok(()), "an allow with a reason exempts the test"); assert_eq!(finish(&[], 3, 1, "base"), Ok(())); } From 5594da577bfcfbc3aaff8e23b30ccac151d56e59 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:09:47 -0800 Subject: [PATCH 11/11] xtask: test-lint census rule ends tail assignments at their block and tells closure locals from captures An assignment that ends a block without a semicolon (`{ input = c }`) now makes its alias at the block's close instead of after the next statement. A `let` inside a move closure, or one of its parameters, now counts as a local binding: an assignment to it ends the alias as it does outside a closure. Assignments to outer captures are still skipped. A closure stored with `let` in `Some`, `Ok`, `Err`, `Box::new`, `Rc::new` or `Arc::new` and never used again does not run, so its assignments no longer end an alias. A closure passed to any other call may run and still ends it. An async closure called where it is written now runs when the call is passed straight to `block_on` (a trailing comma included), unless the `block_on` sits inside another closure. --- xtask/src/test_lint.rs | 122 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 111 insertions(+), 11 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 19c8bf3c8d..418cc75b1f 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1843,7 +1843,8 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { for (at, assigned) in steps { if let Some(eq) = assigned { let name = String::from_utf8_lossy(b[at..eq].trim_ascii_end()).into_owned(); - let end = statement_end(&b[..to], eq); + // A block's tail (`{ input = c }`) ends at the block's close. + let end = statement_end(&b[..to], eq).min(block_close(b, at)); let until = words(b, b"let", from, at) .into_iter() .filter(|&l| block_close(b, l) > at) @@ -1859,7 +1860,7 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { .map_or(to, |(_, until)| until); // Assignments in move closures leave outer bindings unchanged. Assignments in async // blocks or uncalled closures do not run; conditional assignments do not make aliases. - if in_move_closure(b, from, to, at) || in_async_block(b, from, at) || in_uncalled_closure(b, from, to, at, &[]) { + if in_move_closure(b, from, to, at, &name) || in_async_block(b, from, at) || in_uncalled_closure(b, from, to, at, &[]) { continue; } if live(value_start(eq, end), end, &derived, &shadows) { @@ -2297,7 +2298,19 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac if b.get(call) != Some(&b'(') { return false; } - if !asynchronous { + // An async closure's future runs when it is passed straight to `block_on` or awaited. A `|` + // before `block_on` may open a closure around it (`let _saved = || block_on(…);`) that + // never runs. + let outer = (stmt..open.saturating_sub(1)).rev().find(|&i| !b[i].is_ascii_whitespace()); + let blocked = matching(b, call).is_some_and(|call_close| { + outer.is_some_and(|o| { + b[o] == b'(' + && !b[stmt..o].contains(&b'|') + && b[..o].trim_ascii_end().strip_suffix(b"block_on").is_some_and(|h| !h.last().copied().is_some_and(is_ident)) + && matching(b, o).is_some_and(|c| matches!(b[call_close + 1..c].trim_ascii(), b"" | b",")) + }) + }); + if !asynchronous || blocked { return true; } let next = matching(b, call).map_or(b.len(), |c| skip_ws(b, c + 1)); @@ -2400,8 +2413,9 @@ fn in_async_block(b: &[u8], from: usize, start: usize) -> bool { }) } -/// Whether `start` lies in the block or expression body of a move closure. -fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize) -> bool { +/// Whether `start` lies in the block or expression body of a move closure that captures `name`: +/// neither the closure's parameters nor a `let` in its body before `start` binds `name`. +fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize, name: &str) -> bool { words(b, b"move", from, start).into_iter().any(|at| { let pipe = skip_ws(b, at + 4); if b.get(pipe) != Some(&b'|') { @@ -2417,12 +2431,22 @@ fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize) -> bool { until = if matches!(b[until], b'(' | b'[' | b'{') { matching(b, until).unwrap_or(to) + 1 } else { until + 1 }; } } - body <= start && start < until + let inside = body <= start && start < until; + let binds = |text: &[u8]| pattern_names(&String::from_utf8_lossy(text)).any(|n| n == name); + let local = inside + && words(b, b"let", body, start).into_iter().any(|l| { + block_close(b, l) > start + && (l + 3..start) + .find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) + .is_some_and(|eq| binds(&b[l + 3..eq])) + }); + inside && !binds(&b[pipe + 1..end]) && !local }) } /// Whether `start` lies in the block body of a closure bound with `let` in `b[from..to]` -/// (`let run = || { … };`, also `move` or `async`) with no call that [`closure_calls`] finds. +/// (`let run = || { … };`, also `move` or `async`) with no call that [`closure_calls`] finds, or of +/// a closure that a `let` stores without a call ([`stored_closure`]). fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool { let mut depth = 0usize; for i in (from..start).rev() { @@ -2435,11 +2459,15 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & let Some(pipe) = params.iter().rposition(|&c| c == b'|') else { continue }; let text = String::from_utf8_lossy(params[..pipe].trim_ascii_end()); let (head, asynchronous) = strip_closure_keywords(&text); - let Some(binding) = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { continue }; - let Some(name) = pattern_names(binding).last() else { continue }; - let bound = words(b, b"let", from, from + pipe).last().copied().unwrap_or(from); let close = matching(b, i).unwrap_or(to); - if !closure_calls(b, &name, bound, close, to, asynchronous).into_iter().any(|at| runs_with_assertion_within(b, from, to, at, active)) + let binding = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b); + let stored = binding.is_none() && stored_closure(b, head, close, to); + let Some(name) = binding.and_then(|binding| pattern_names(binding).last()).or_else(|| stored.then(String::new)) else { continue }; + let bound = words(b, b"let", from, from + pipe).last().copied().unwrap_or(from); + if stored + || !closure_calls(b, &name, bound, close, to, asynchronous) + .into_iter() + .any(|at| runs_with_assertion_within(b, from, to, at, active)) { return true; } @@ -2450,6 +2478,28 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & false } +/// Whether the closure whose block body ends at `close`, with `head` the text before its +/// parameters, is the only argument of `Some`, `Ok`, `Err`, `Box::new`, `Rc::new` or `Arc::new` in +/// a `let` initializer (`let _saved = Some(|| { … });`) whose names `b[..to]` never uses again, so +/// nothing can call it. A closure passed to any other call, a drop guard's included, may run there. +fn stored_closure(b: &[u8], head: &str, close: usize, to: usize) -> bool { + let Some(callee_end) = head.strip_suffix('(').map(str::trim_end) else { return false }; + let path_len = callee_end.bytes().rev().take_while(|&c| is_ident(c) || c == b':').count(); + let (rest, path) = callee_end.split_at(callee_end.len() - path_len); + let mut segments = path.rsplit("::"); + let last = segments.next().unwrap_or_default(); + let owner = segments.next().unwrap_or_default(); + let constructor = matches!(last, "Some" | "Ok" | "Err") || (last == "new" && matches!(owner, "Box" | "Rc" | "Arc")); + let Some(binding) = rest.trim_end().strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { return false }; + let paren = skip_ws(b, close + 1); + let semi = skip_ws(b, paren + 1); + constructor + && binding.starts_with(char::is_whitespace) + && b.get(paren) == Some(&b')') + && b.get(semi) == Some(&b';') + && pattern_names(binding).all(|n| words(b, n.as_bytes(), semi, to).is_empty()) +} + /// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and /// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while /// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions @@ -9254,6 +9304,36 @@ mod tests { [], "an assignment to a move capture leaves the outer alias unchanged" ); + assert_eq!( + census("let mut input = fallback(); { input = c } app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment that ends a block without a semicolon makes an alias there" + ); + assert_eq!( + census("let mut input = fallback(); { input = c; } app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment that ends with a semicolon in a block makes an alias" + ); + assert_eq!( + census("let run = move || { let mut input = c; input = fallback(); app.run(input); }; run(); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment to a binding declared in a move closure ends its alias" + ); + assert_eq!( + census("let mut input = c; let _saved = Some(|| { input = fallback(); }); app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in a closure stored in a call argument does not end an alias" + ); + assert_eq!( + census("let mut input = c; let _ = Some(input).map(|_| { input = fallback(); }); app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment in a closure passed to a call that may run it ends an alias" + ); + assert_eq!( + census("let mut input = c; { let _guard = RunOnDrop(|| { input = fallback(); }); } app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment in a closure kept by another type, which may run it, ends an alias" + ); } #[test] @@ -9316,6 +9396,26 @@ mod tests { "an async closure called where it is written only makes a future" ); assert_eq!(census("assert!((async || app.run(c))().await.is_ok());"), [], "an awaited async closure called where it is written runs"); + assert_eq!( + census("let _ = block_on((async || app.run(c))()); assert!(menu(c).is_some());"), + [], + "an async closure called where it is written and passed to block_on runs" + ); + assert_eq!( + census("let _ = block_on((async || app.run(c))(),); assert!(menu(c).is_some());"), + [], + "a trailing comma after the future passed to block_on" + ); + assert_eq!( + census("let _ = wrap((async || app.run(c))()); assert!(menu(c).is_some());"), + [(2, "census")], + "an async closure called where it is written and passed to another call does not run" + ); + assert_eq!( + census("let _saved = || block_on((async || app.run(c))()); assert!(menu(c).is_some());"), + [(2, "census")], + "block_on in an uncalled closure does not run the async closure" + ); assert_eq!( census("let _saved = Some(|| { app.run(c) }); assert!(menu(c).is_some());"), [(2, "census")],