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/main.rs b/xtask/src/main.rs index 7e9f7787ff..40f38d85f2 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -276,23 +276,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)); @@ -306,9 +304,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() { @@ -319,12 +317,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}")) } } @@ -380,22 +378,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)))); } } @@ -407,13 +416,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. /// /// With `GATE_SHARD` and `GATE_SHARDS` set (the gate's split warm legs), it builds only what that /// shard builds: a test shard's tests, or the checks shard's builds. A split's later parts build @@ -434,14 +441,16 @@ fn cmd_ci_warm() -> Result<(), String> { let (tests, checks) = shards::warm_plan(&checked, only); let mut steps: Vec = Vec::new(); for i in tests { - if let shards::Shard::Tests(crates, _) = checked[i].clone() { - steps.push(( - "build tests", - Box::new(move || { - let (c, what) = warm_tests(&crates); - cache_units::run(c, &what) - }), - )); + if let shards::Shard::Tests(runs, _) = checked[i].clone() { + for r in runs { + steps.push(( + "build tests", + Box::new(move || { + let (c, what) = warm_tests(&r); + cache_units::run(c, &what) + }), + )); + } } } if checks { @@ -477,11 +486,11 @@ fn push_warm_checks(steps: &mut Vec) { steps.push(("wasm", Box::new(cmd_wasm))); } -/// 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 @@ -634,13 +643,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 188f1bbda8..9bc4469ae4 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> { // The shared gate runs only the shards that test a crate a pull request reaches, by these @@ -335,9 +434,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() { @@ -365,8 +467,13 @@ fn workflow_members(workflow: &str) -> Result<(), String> { 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 in the tests). + 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(), }) @@ -385,9 +492,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()), } @@ -472,7 +579,7 @@ mod tests { // builds nothing), and the legs together, like a full warm, build every crate's tests // once and the checks. let real = assign(GROUPS, &members(&crate::metadata().unwrap()).unwrap()).unwrap(); - let mut owned: Vec<&str> = real.iter().flat_map(owners).collect(); + let mut owned: Vec<&str> = real.iter().flat_map(owners).map(|(name, _)| name).collect(); owned.sort_unstable(); let (mut legs, mut leg_checks) = (Vec::new(), 0); for i in 0..GROUPS.len() { @@ -520,17 +627,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(), } } @@ -579,12 +687,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")); @@ -647,26 +755,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")); } @@ -674,11 +817,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); } @@ -720,6 +874,32 @@ geom v0.1.0 (/w/geom)| fn ci_names_the_crates_of_every_shard_for_test_selection() { assert_eq!(workflow_members(include_str!("../../.github/workflows/ci.yml")), Ok(())); assert!(workflow_members(" shard-members: |\n a b\n (rest)\n next: 1\n").is_err()); + 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()); } diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 44d73697e2..e517292e73 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, @@ -82,9 +89,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 @@ -92,8 +99,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] = &[ @@ -223,11 +231,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 +259,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 { @@ -347,7 +351,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 = @@ -555,7 +560,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 ") ); @@ -640,6 +645,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}}")]) @@ -1348,35 +1421,132 @@ 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, +/// other than in a `use` declaration that renames it (`use other::near as comparison;`). An import +/// that keeps the name can bring another module's `name` into scope. +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| { + 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 +/// 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 @@ -1413,7 +1583,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)) } @@ -1424,6 +1601,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, @@ -1468,11 +1647,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)); @@ -1526,19 +1706,36 @@ 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 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)); + let helpers = helpers_for(ctx, file.path, file.depths[t.attr] == 0).unwrap_or(&none); + // 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(|(at, n, method)| { + 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 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)); @@ -1550,6 +1747,212 @@ 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. 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)| { + 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) + }) +} + +/// 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 !pattern_binds(body, name, start, end) { + 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() +} + +/// 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; + 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].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())) + }) +} + +/// 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. @@ -1620,13 +2023,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); @@ -1739,10 +2148,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 +2189,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 +2207,92 @@ 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(); + // 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) + .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, &name) || 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 +2442,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 +2520,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 +2556,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 +2574,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 +2583,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 +2625,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 +2677,185 @@ 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; + } + // 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)); + 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 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'|') { + 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 }; + } + } + 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, 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() { @@ -2201,18 +2866,18 @@ 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 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 text = String::from_utf8_lossy(params[..pipe].trim_ascii_end()); + let (head, asynchronous) = strip_closure_keywords(&text); 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) - }) { + 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; } } @@ -2222,6 +2887,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 @@ -2653,7 +3340,310 @@ 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)); + let end = statement_end(body, bound); + Some((norm(text.as_bytes()), s, at, sizes.literals(let_value(body, bound, end), end))) + }) + } 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, a.args[0]), (&right, &left, a.args[1])].into_iter().any(|(pinned, literal, (from, to))| { + 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); + 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, 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. + // 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)) + }) + }) +} + +/// 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 +} + +/// 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(); + &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)) + }); + // 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); + !(getter || (read && 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'_'); + // 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. + 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 }; + } + pattern_binds(body, name, start, end) }) } @@ -3350,9 +4340,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 { @@ -3360,14 +4372,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 @@ -3531,7 +4556,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())) @@ -3745,9 +4770,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'=') => { @@ -3759,8 +4784,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); } } @@ -4803,28 +5828,40 @@ 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), _ => { - 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) { + // 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; @@ -4832,16 +5869,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, @@ -4852,8 +5897,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. @@ -4878,7 +5932,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 @@ -6159,8 +7214,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 +8342,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(())); } @@ -8155,6 +9216,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(); @@ -8702,6 +9800,58 @@ mod tests { 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 census_follows_the_calls_that_run_for_each_entry() { let census_in = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); @@ -8858,6 +10008,109 @@ mod tests { ); } + #[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"); + 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] + 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 census_follows_block_initializers_argument_guards_and_parameterized_closures() { let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); @@ -8937,6 +10190,261 @@ 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" + ); + 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] + 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 _ = 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")], + "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::>(); @@ -8993,6 +10501,255 @@ mod tests { } } + #[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", " 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), []); + 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"); + 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"); + } + #[test] fn numeric_literals_are_one_token() { for s in ["1", "0x1F", "2.5f32", "1_000", "1e-3", "7usize"] {