diff --git a/docs/development.md b/docs/development.md index e3890df321..a1ceccaf59 100644 --- a/docs/development.md +++ b/docs/development.md @@ -351,6 +351,10 @@ The app decides which cursors exist; whoever draws them works from the list. For `cargo xtask brands` (part of `cargo xtask ci`) fails when user-visible text names another vendor's products or company: string literals in Rust sources (command labels and params docs, menus, panels, MCP tool definitions), `Cargo.toml` descriptions and packaging files. Comments, test files and `#[cfg(test)]` modules are not checked. Say "the reference app" or name the feature itself. A line that must keep an old name, such as an alias that files or preferences from earlier versions still use, or a name another project defines, such as a shared MIME type, carries a `brand-ok` comment. In the Linux desktop entry, whose comments take whole lines, the comment goes on the `#` line just above it; `MARK_ABOVE` in `xtask/src/brands.rs` lists the files that accept a mark there. +## 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`) and `thread::sleep` in test code (`sleep`). 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 test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. + ## Tests - `cargo xtask test` runs the workspace's unit and integration tests with diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 5484c0d3e9..1c9af7db00 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -18,6 +18,7 @@ mod sha256; mod shards; mod stats; mod test262; +mod test_lint; mod ui_commands; mod version; mod web_fonts; @@ -32,6 +33,11 @@ commands: assets check that every icon/image/font/asset is attributed in ASSETS.md brands check that user-visible text (labels, params docs, MCP, docs, packaging) names no other vendor's products cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) + test-lint [--base ] [--all] + weak tests in the lines changed since the base: fail on self-compares, reasonless + #[ignore] and sleeps; list only is_ok/is_some checks, unguarded .all(), no assertion, + early returns, unset env gates... (xtask/src/test_lint.rs); --all lists every hit + by crate and never fails i18n-report list the strings each language's catalog lacks, shown in English (fails only on a broken scan; ci runs it too) ui-commands regenerate crates/mcp/src/ui_catalog.rs from desktop UI_COMMANDS; --check fails on drift @@ -39,7 +45,7 @@ commands: layers enforce the crate dependency layering (plan/architecture.md §3) wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates, the web app and its plug-in worker test the workspace tests (cargo nextest when installed, else cargo test), then the doctests - ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, cursors (warnings only), ui-commands --check, layers, wasm (stops at first failure) + ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, cursors (warnings only), test-lint, ui-commands --check, layers, wasm (stops at first failure) ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs the tests and doctests of its crates, the last shard the other steps ci warm build what every shard builds, without running it (fills the gate's cache); with @@ -74,6 +80,7 @@ fn main() -> ExitCode { Some("assets") => assets::run(&root()), Some("brands") => brands::run(&root()), Some("cursors") => cursors::run(&root()), + Some("test-lint") => test_lint::run(&root(), &rest), Some("i18n-report") => cmd_i18n_report(), Some("ui-commands") => ui_commands::run(&root(), rest.contains(&"--check")), Some("layers") => cmd_layers(), @@ -118,13 +125,13 @@ pub fn root() -> PathBuf { pub fn repo_files(root: &Path) -> Result, String> { let out = Command::new("git") .current_dir(root) - .args(["ls-files", "--cached", "--others", "--exclude-standard"]) + .args(["ls-files", "-z", "--cached", "--others", "--exclude-standard"]) .output() .map_err(|e| format!("git ls-files: {e}"))?; if !out.status.success() { return Err(format!("git ls-files failed: {}", String::from_utf8_lossy(&out.stderr).trim())); } - Ok(String::from_utf8_lossy(&out.stdout).lines().filter(|l| root.join(l).exists()).map(str::to_owned).collect()) + Ok(String::from_utf8_lossy(&out.stdout).split('\0').filter(|l| !l.is_empty() && root.join(l).exists()).map(str::to_owned).collect()) } /// A `cargo` command (the one running xtask, else `cargo` on the PATH) run in the workspace root. @@ -525,6 +532,7 @@ fn ci_steps() -> Vec { ("assets", Box::new(|| assets::run(&root()))), ("brands", Box::new(|| brands::run(&root()))), ("cursors", Box::new(|| cursors::run(&root()))), + ("test-lint", Box::new(|| test_lint::run(&root(), &[]))), ("i18n-report", Box::new(cmd_ci_i18n_report)), ("ui-commands", Box::new(|| ui_commands::run(&root(), true))), ("layers", Box::new(cmd_layers)), diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs new file mode 100644 index 0000000000..8609ace2f5 --- /dev/null +++ b/xtask/src/test_lint.rs @@ -0,0 +1,3991 @@ +//! `cargo xtask test-lint`: tests that a wrong result can pass, in the tests a change touches. +//! +//! Rules, checked in `#[test]` functions (and `#[tokio::test]`, `#[test_case]`, +//! `#[wasm_bindgen_test]`, and `#[test]` inside `proptest!`): +//! * `all-unguarded`: `assert!(….all(…))` in a test that neither checks a length, emptiness, +//! count, first item or `any` in an assertion's condition or compared operands, nor takes a +//! first item by indexing, unwrapping or a panicking `let … else`: `.all()` is true for an empty +//! collection (negated `.all(…)`, including `== false`, and predicates saying that no item +//! matches, with whole negations or `!=` comparisons joined only by `&&`, are left out). An earlier +//! `assert_eq!`, `debug_assert_eq!` or `prop_assert_eq!` comparing a plain local receiver +//! (optionally borrowed or viewed through `.as_slice()` or `[..]`) with a non-empty array +//! literal or `vec![…]` guards only that receiver, and so does an assertion on a local bound to a +//! count, length or emptiness check. Collections that cannot be empty are also left out: +//! non-empty array literals; plain locals of the test bound to an array type of a positive length, +//! to a non-empty array literal or `vec![…]` or a literal range (lengths and repetition counts may +//! 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; +//! * `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 +//! expression calls nothing with arguments (two calls with arguments check determinism) and no +//! method that returns the next value each time ([`ADVANCING`], such as `next`); +//! * `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]`; +//! * `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, +//! corpora, environment variables, the platform or a child process; +//! * `ignore-without-reason`: `#[ignore]` with no `= "reason"`; +//! * `env-gate-unset`: `env::var("NAME")` in a test where no CI workflow, the shared gate or the +//! file's code sets `NAME`; workflow mapping keys and `NAME=` assignments count, but comments, +//! string literals, `echo` or `printf` output that is not written to `$GITHUB_ENV`, and variable +//! reads do not; +//! * `sleep`: `thread::sleep` in test code, or a bare `sleep(…)` in a file that imports it; +//! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, or a walk +//! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`]. +//! +//! Test code is a test file (`tests.rs`, `tests_*.rs`, `*_tests.rs`, a file in a `tests` or +//! `benches` folder, `crates/testkit`), an item under `#[cfg(test)]` or `#[cfg(all(test, …))]`, +//! or a test function. +//! +//! An asserting helper is a function or macro in the crate's test code (or in `crates/testkit`) +//! that asserts, panics or calls one that does (every one of that name, when there are several), +//! or a call whose name starts with `assert`, `check`, `verify`, `ensure` or `expect_`. +//! +//! `// test-lint: allow ` exempts the line it is on and the line below it; for the +//! 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` and `sleep` 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 +//! 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 +//! workspace by crate and rule, and does not fail. + +use std::cell::OnceCell; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::path::Path; +use std::process::Command; + +/// Test files that read Rust source on purpose: they audit the source tree. +pub const SOURCE_AUDITS: &[&str] = &[ + "crates/plugins/tests/grant_sites.rs", + "crates/ui-egui/src/i18n/tests.rs", + "crates/ui-egui/src/icons.rs", + "crates/eps/src/import/tests_generators.rs", +]; + +/// Variables the shared gate workflow and its setup action set on every leg, besides those named +/// in `.github/workflows/*.yml`. +const SHARED_GATE_ENV: &[&str] = + &["CRAFT_FONTS_DIR", "CRAFT_FONTS_REQUIRED", "GATE_SHARD", "GATE_SHARDS", "NEXTEST_PARTITION", "NEXTEST_ARCHIVE_FILE"]; + +/// Variables the runner, the operating system or cargo set. +const SYSTEM_ENV: &[&str] = &[ + "HOME", + "PATH", + "USER", + "USERNAME", + "LOGNAME", + "TMPDIR", + "TEMP", + "TMP", + "APPDATA", + "LOCALAPPDATA", + "USERPROFILE", + "PROGRAMDATA", + "PROGRAMFILES", + "WINDIR", + "SYSTEMROOT", + "CI", + "LANG", + "SHELL", + "PWD", + "OUT_DIR", +]; +const SYSTEM_ENV_PREFIXES: &[&str] = &["CARGO_", "NEXTEST", "RUST", "GITHUB_", "RUNNER_", "XDG_"]; + +/// Larger source files are refused rather than read. +const MAX_FILE: u64 = 16 << 20; + +/// The marker of an exemption comment. +const ALLOW: &str = "test-lint: allow "; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Rule { + AllUnguarded, + OnlyWeak, + SelfCompare, + ExitStatusOnly, + NoAssertion, + EarlyReturn, + IgnoreWithoutReason, + EnvGateUnset, + Sleep, + ReadsSource, +} + +impl Rule { + pub const ALL: [Rule; 10] = [ + Rule::AllUnguarded, + Rule::OnlyWeak, + Rule::SelfCompare, + Rule::ExitStatusOnly, + Rule::NoAssertion, + Rule::EarlyReturn, + Rule::IgnoreWithoutReason, + Rule::EnvGateUnset, + Rule::Sleep, + Rule::ReadsSource, + ]; + + pub fn id(self) -> &'static str { + match self { + Rule::AllUnguarded => "all-unguarded", + Rule::OnlyWeak => "only-weak", + Rule::SelfCompare => "self-compare", + Rule::ExitStatusOnly => "exit-status-only", + Rule::NoAssertion => "no-assertion", + Rule::EarlyReturn => "early-return", + Rule::IgnoreWithoutReason => "ignore-without-reason", + Rule::EnvGateUnset => "env-gate-unset", + Rule::Sleep => "sleep", + Rule::ReadsSource => "reads-source", + } + } + + fn advice(self) -> &'static str { + match self { + Rule::AllUnguarded => "also assert the expected length (or that the collection is not empty)", + Rule::OnlyWeak => "assert the value itself (assert_eq! on the result), not only that there is one", + Rule::SelfCompare => "compare with an expected value written out, or with a second, independent computation", + Rule::ExitStatusOnly => "also check the output (stdout, stderr or the files written)", + Rule::NoAssertion => "assert what the code returns or changes", + Rule::EarlyReturn => "assert the condition instead of returning, so a wrong value fails the test", + Rule::IgnoreWithoutReason => "write #[ignore = \"why\"]", + Rule::EnvGateUnset => "set the variable in a CI leg, or make the test run without it", + Rule::Sleep => "wait on a handshake (channel, barrier) or a controllable clock", + Rule::ReadsSource => "test the behavior, or add the file to SOURCE_AUDITS in xtask/src/test_lint.rs if it audits the source tree", + } + } + + /// 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) + } + + fn from_id(id: &str) -> Option { + Rule::ALL.into_iter().find(|r| r.id() == id) + } +} + +/// A rule broken in a file. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Hit { + pub path: String, + /// 1-based: the line of the finding, or of `fn` for a rule about a whole test. + pub line: usize, + pub rule: Rule, + /// The test it is in; empty for test code outside a test function. + pub test: String, + pub note: String, + /// The first and last line of what the hit covers: the test, from its attribute to its closing + /// brace, for a rule about a whole test or `all-unguarded`, through the second operand for + /// `self-compare`, through the variable's name for `env-gate-unset`, through the attribute's + /// `]` for `ignore-without-reason`, else `line`. This span + /// controls changed-line detection; `all-unguarded` and `self-compare` exemptions still apply + /// only near `line`. + pub first: usize, + pub last: usize, +} + +impl Hit { + fn show(&self) -> String { + let test = if self.test.is_empty() { String::new() } else { format!(" `{}`", self.test) }; + format!("{}:{}: [{}]{test}: {}", self.path, self.line, self.rule.id(), self.note) + } +} + +/// What the rules need beyond the file: asserting helper names by crate and the variables CI sets. +pub struct Ctx { + pub helpers: HashMap>, + pub ci_env: HashSet, +} + +pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { + let opts = Options::parse(args)?; + let repo = crate::repo_files(root)?; + let ci_env = ci_env(root, &repo)?; + let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); + if opts.all { + let sources = read_all(root, &files)?; + let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env }; + let hits: Vec = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); + print!("{}", report(&hits, sources.len())); + return Ok(()); + } + let base = resolve_base(root, opts.base)?; + let changed = changed_lines(root, &base)?; + let changed: BTreeMap>> = changed.into_iter().filter(|(p, _)| is_scanned(p)).collect(); + let crates: BTreeSet = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); + let helper_files: Vec = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); + let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env }; + let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); + let (mut counted, mut older) = (vec![], 0usize); + for (path, src) in read_all(root, &present)? { + for hit in lint_file(&path, &src, &ctx) { + if touches(&hit, changed.get(&path).and_then(Option::as_ref)) { + counted.push(hit); + } else { + older += 1; + } + } + } + finish(&counted, older, present.len(), &base) +} + +/// The command line: `--all`, `--base `. +#[derive(Debug, Default, PartialEq)] +struct Options { + all: bool, + base: Option, +} + +impl Options { + fn parse(args: &[&str]) -> Result { + let mut opts = Options::default(); + let mut it = args.iter(); + while let Some(&arg) = it.next() { + match arg { + "--all" if !opts.all => opts.all = true, + "--base" if opts.base.is_none() => match it.next() { + Some(rev) if !rev.is_empty() && !rev.starts_with('-') => opts.base = Some((*rev).to_owned()), + _ => return Err("test-lint: --base takes a revision".into()), + }, + _ => return Err(format!("test-lint: unexpected argument `{arg}` (usage: cargo xtask test-lint [--all] [--base ])")), + } + } + if opts.all && opts.base.is_some() { + return Err("test-lint: --all checks every file and takes no --base".into()); + } + Ok(opts) + } +} + +fn finish(counted: &[Hit], older: usize, files: usize, base: &str) -> Result<(), String> { + let older = if older == 0 { String::new() } else { format!("; {older} hit(s) on unchanged lines of those files are not counted") }; + let (failing, reported): (Vec<&Hit>, Vec<&Hit>) = counted.iter().partition(|h| h.rule.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 {}", + reported.len(), + listing(&reported).join("\n ") + ); + } + if failing.is_empty() { + println!("test-lint: no failing hits in the changed lines of {files} Rust file(s) since {base}{older}"); + return Ok(()); + } + Err(format!( + "{} test-lint hit(s) in the lines changed since {base}{older} (exempt a line with `// {ALLOW} `):\n {}", + failing.len(), + listing(&failing).join("\n ") + )) +} + +/// Each hit, then the advice for each rule they break. +fn listing(hits: &[&Hit]) -> Vec { + let mut out: Vec = hits.iter().map(|h| h.show()).collect(); + let rules: BTreeSet = hits.iter().map(|h| h.rule).collect(); + out.extend(rules.iter().map(|r| format!("{}: {}", r.id(), r.advice()))); + out +} + +/// `--all`: counts by crate and rule, then every hit. +fn report(hits: &[Hit], files: usize) -> String { + let mut by_crate: BTreeMap> = BTreeMap::new(); + for h in hits { + *by_crate.entry(crate_of(&h.path)).or_default().entry(h.rule).or_default() += 1; + } + let mut out = format!("test-lint --all: {} hit(s) in {files} Rust file(s)\n\nby rule:\n", hits.len()); + for rule in Rule::ALL { + out += &format!(" {:<22} {}\n", rule.id(), hits.iter().filter(|h| h.rule == rule).count()); + } + out += "\nby crate:\n"; + for (krate, rules) in &by_crate { + let list: Vec = rules.iter().map(|(r, n)| format!("{} {n}", r.id())).collect(); + out += &format!(" {krate}: {}\n", list.join(", ")); + } + out += "\nhits:\n"; + for h in hits { + out += &format!(" {}\n", h.show()); + } + out +} + +/// Rust files the lint reads. +fn is_scanned(path: &str) -> bool { + path.ends_with(".rs") && ["crates/", "apps/", "xtask/"].iter().any(|d| path.starts_with(d)) +} + +/// `crates/` or `apps/` for a file in one, else its first path component. +fn crate_of(path: &str) -> String { + let parts: Vec<&str> = path.split('/').collect(); + match parts.as_slice() { + [top @ ("crates" | "apps"), name, _, ..] => format!("{top}/{name}"), + [first, ..] => (*first).to_owned(), + [] => String::new(), + } +} + +fn read_all(root: &Path, paths: &[String]) -> Result, String> { + paths + .iter() + .map(|p| { + let full = root.join(p); + let len = std::fs::metadata(&full).map_err(|e| format!("{p}: {e}"))?.len(); + if len > MAX_FILE { + return Err(format!("{p}: {len} bytes, over test-lint's limit of {MAX_FILE}")); + } + Ok((p.clone(), std::fs::read_to_string(&full).map_err(|e| format!("{p}: {e}"))?)) + }) + .collect() +} + +// ---- Git: the base and the changed lines ---- + +fn git(root: &Path, args: &[&str]) -> Result { + let out = Command::new("git").current_dir(root).args(args).output().map_err(|e| format!("git {}: {e}", args.join(" ")))?; + if !out.status.success() { + return Err(format!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim())); + } + Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned()) +} + +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}}")]) + .map_err(|_| format!("test-lint: base `{rev}` is not a commit")); + } + if std::env::var_os("GITHUB_ACTIONS").is_some() { + if let Ok(parent) = git(root, &["rev-parse", "--verify", "--quiet", "HEAD^1^{commit}"]) { + return Ok(parent); + } + let head = git(root, &["rev-parse", "HEAD"])?; + git(root, &["fetch", "--no-tags", "--quiet", "--depth=2", "origin", &head])?; + return git(root, &["rev-parse", "--verify", "--quiet", "HEAD^1^{commit}"]) + .map_err(|_| "test-lint: HEAD has no parent to compare with (set TEST_LINT_BASE)".into()); + } + for main in ["upstream/main", "origin/main"] { + if let Ok(base) = git(root, &["merge-base", "HEAD", main]) { + return Ok(base); + } + } + Err("test-lint: no upstream/main or origin/main to compare with; pass --base or set TEST_LINT_BASE".into()) +} + +/// The changed files since `base` with their changed lines (new numbering); `None` for a file that +/// is new or untracked. A pure deletion marks the lines before and after it, or line 1 at the top +/// of the file. +fn changed_lines(root: &Path, base: &str) -> Result>>, String> { + let diff = git( + root, + &[ + "-c", + "core.quotepath=off", + "diff", + "-U0", + "--inter-hunk-context=0", + "--no-color", + "--no-ext-diff", + "--src-prefix=a/", + "--dst-prefix=b/", + base, + "--", + "*.rs", + ], + )?; + let mut out = parse_diff(&diff); + for path in git(root, &["ls-files", "-z", "--others", "--exclude-standard", "--", "*.rs"])?.split('\0').filter(|p| !p.is_empty()) { + out.insert(path.to_owned(), None); + } + Ok(out) +} + +/// The changed new-side lines in each file. A pure deletion includes its anchor and the following +/// line, or just line 1 when the anchor is 0. +fn parse_diff(diff: &str) -> BTreeMap>> { + let mut out: BTreeMap>> = BTreeMap::new(); + let mut current: Option = None; + // Inside a file's header (from `diff --git` to its first hunk), where `+++ ` names the file. + let (mut header, mut new_file) = (false, false); + for line in diff.lines() { + if line.starts_with("diff --git ") { + (header, new_file) = (true, false); + } else if header && line.starts_with("new file mode") { + new_file = true; + } else if let Some(path) = line.strip_prefix("+++ ").filter(|_| header) { + current = patch_path(path).and_then(|p| p.strip_prefix("b/").map(str::to_owned)); + if let Some(p) = ¤t { + out.insert(p.clone(), if new_file { None } else { Some(BTreeSet::new()) }); + } + } else if let (Some(hunk), Some(path)) = (line.strip_prefix("@@ "), ¤t) { + header = false; + if let (Some((start, count)), Some(Some(lines))) = (hunk_range(hunk), out.get_mut(path)) { + if count == 0 { + lines.extend(start.max(1)..=start.saturating_add(1)); + } else { + lines.extend(start..start + count); + } + } + } + } + out +} + +/// The path in a `+++ ` label: git ends a label that contains a space with a tab, and writes a +/// path with a quote, a backslash or a control character as a C-style quoted string. +fn patch_path(label: &str) -> Option { + let label = label.strip_suffix('\t').unwrap_or(label); + let Some(quoted) = label.strip_prefix('"') else { return Some(label.to_owned()) }; + let body = quoted.strip_suffix('"')?.as_bytes(); + let (mut out, mut i) = (Vec::with_capacity(body.len()), 0); + while i < body.len() { + if body[i] != b'\\' { + out.push(body[i]); + i += 1; + continue; + } + let c = *body.get(i + 1)?; + let octal = body.get(i + 1..i + 4).filter(|d| d.iter().all(|c| (b'0'..=b'7').contains(c))); + if let Some(digits) = octal { + out.push(digits.iter().fold(0u8, |n, d| n.wrapping_mul(8).wrapping_add(d - b'0'))); + i += 4; + continue; + } + out.push(match c { + b'a' => 7, + b'b' => 8, + b't' => b'\t', + b'n' => b'\n', + b'v' => 11, + b'f' => 12, + b'r' => b'\r', + other => other, + }); + i += 2; + } + String::from_utf8(out).ok() +} + +/// `(start, count)` of the new side of a hunk header's `-a,b +c,d @@`. A pure deletion has count 0 +/// and sits between lines c and c + 1; c = 0 places it before line 1. +fn hunk_range(hunk: &str) -> Option<(usize, usize)> { + let new = hunk.split_whitespace().find(|w| w.starts_with('+'))?.trim_start_matches('+'); + match new.split_once(',') { + Some((s, c)) => Some((s.parse().ok()?, c.parse().ok()?)), + None => Some((new.parse().ok()?, 1)), + } +} + +/// Whether `hit` covers a changed line (`None`: the whole file is new). +fn touches(hit: &Hit, changed: Option<&BTreeSet>) -> bool { + changed.is_none_or(|lines| lines.range(hit.first..=hit.last).next().is_some()) +} + +// ---- What CI sets ---- + +fn ci_env(root: &Path, files: &[String]) -> Result, String> { + let mut names: HashSet = SHARED_GATE_ENV.iter().map(|s| (*s).to_owned()).collect(); + for path in files.iter().filter(|p| p.starts_with(".github/workflows/") && (p.ends_with(".yml") || p.ends_with(".yaml"))) { + let text = std::fs::read_to_string(root.join(path)).map_err(|e| format!("{path}: {e}"))?; + names.extend(upper_words(&text)); + } + Ok(names) +} + +/// Workflow mapping keys and assignments with capitalized environment variable names. +fn upper_words(text: &str) -> impl Iterator + '_ { + text.lines().flat_map(|line| { + let line = workflow_code(line); + let start = line.trim_start().strip_prefix("- ").unwrap_or(line.trim_start()).trim_start(); + let mapping = + start.split_once(':').filter(|(name, rest)| env_assignment_name(name) && (rest.is_empty() || rest.starts_with(char::is_whitespace))); + let assignments = line.match_indices('=').filter_map(move |(at, _)| { + let name = line[..at].rsplit(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')).next().unwrap_or_default(); + let from = at - name.len(); + let boundary = from == 0 || line.as_bytes().get(from - 1).is_some_and(|c| c.is_ascii_whitespace() || matches!(c, b'\'' | b'"' | b';')); + (boundary && env_assignment_name(name) && !line[at + 1..].starts_with(['=', '>']) && !printed(line, from)).then(|| name.to_owned()) + }); + mapping.map(|(name, _)| name.to_owned()).into_iter().chain(assignments) + }) +} + +/// Whether the text at `from` is an argument of `echo` or `printf` in its shell command, on a line +/// that does not write to `$GITHUB_ENV`. +fn printed(line: &str, from: usize) -> bool { + let command = line[..from].rsplit([';', '&', '|']).next().unwrap_or_default().as_bytes(); + let prints = ["echo", "printf"].iter().any(|w| !words(command, w.as_bytes(), 0, command.len()).is_empty()); + prints && !line.contains("GITHUB_ENV") +} + +fn env_assignment_name(name: &str) -> bool { + name.starts_with(|c: char| c.is_ascii_uppercase()) && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_') +} + +/// Removes comment text outside quotes from a workflow line. +fn workflow_code(line: &str) -> &str { + let (mut quote, mut escaped) = (None, false); + for (at, c) in line.char_indices() { + if escaped { + escaped = false; + } else if c == '\\' && quote != Some('\'') { + escaped = true; + } else if quote == Some(c) { + quote = None; + } else if quote.is_none() { + match c { + '\'' | '"' => quote = Some(c), + '#' => return &line[..at], + _ => {} + } + } + } + line +} + +fn set_by_system(name: &str) -> bool { + SYSTEM_ENV.contains(&name) || SYSTEM_ENV_PREFIXES.iter().any(|p| name.starts_with(p)) +} + +// ---- Lexing ---- + +fn is_ident(c: u8) -> bool { + c.is_ascii_alphanumeric() || c == b'_' +} + +/// `src` with the text of comments and of string and character literals replaced by spaces (line +/// breaks and quotes kept), at the same byte offsets. +fn mask(src: &str) -> Vec { + mask_with(src, true) +} + +/// [`mask`], keeping comments when `comments` is false. +fn mask_with(src: &str, comments: bool) -> Vec { + mask_parts(src, comments, true) +} + +/// Blanks the selected comments and literal contents, preserving line breaks and literal quotes. +fn mask_parts(src: &str, comments: bool, literals: bool) -> Vec { + let b = src.as_bytes(); + let mut out = b.to_vec(); + let mut i = 0; + while i < b.len() { + let next = match b[i] { + b'/' if b.get(i + 1) == Some(&b'/') => { + let end = find(b, b"\n", i).unwrap_or(b.len()); + if comments { + blank(&mut out, i, end); + } + end + } + b'/' if b.get(i + 1) == Some(&b'*') => { + let end = block_comment_end(b, i); + if comments { + blank(&mut out, i, end); + } + end + } + b'"' => { + let end = string_end(b, i + 1); + if literals { + blank(&mut out, i + 1, end.saturating_sub(1)); + } + end + } + b'\'' => { + let end = after_char_or_lifetime(src, i); + if literals { + blank(&mut out, i + 1, end.saturating_sub(1).max(i + 1)); + } + end + } + c if c.is_ascii_alphabetic() || c == b'_' => after_ident(b, &mut out, i, literals), + _ => i + 1, + }; + i = next.max(i + 1); + } + out +} + +fn blank(out: &mut [u8], from: usize, to: usize) { + for c in out.iter_mut().take(to).skip(from) { + if *c != b'\n' { + *c = b' '; + } + } +} + +fn block_comment_end(b: &[u8], mut i: usize) -> usize { + let mut nest = 0usize; + while i < b.len() { + if b[i..].starts_with(b"/*") { + nest += 1; + i += 2; + } else if b[i..].starts_with(b"*/") { + nest = nest.saturating_sub(1); + i += 2; + if nest == 0 { + return i; + } + } else { + i += 1; + } + } + b.len() +} + +/// The index after the closing quote of a `"…"` literal whose body starts at `i`. +fn string_end(b: &[u8], mut i: usize) -> usize { + while i < b.len() && b[i] != b'"' { + i += if b[i] == b'\\' { 2 } else { 1 }; + } + (i + 1).min(b.len()) +} + +/// The index after a char literal (`'x'`, `'\n'`, `'\u{…}'`) at `i`, or after the quote of a +/// lifetime or label. +fn after_char_or_lifetime(src: &str, i: usize) -> usize { + let b = src.as_bytes(); + if b.get(i + 1) == Some(&b'\\') { + let close = (i + 3..b.len()).find(|&j| b[j] == b'\'').unwrap_or(b.len()); + return (close + 1).min(b.len()); + } + match src.get(i + 1..).and_then(|s| s.chars().next()) { + Some(c) if b.get(i + 1 + c.len_utf8()) == Some(&b'\'') => i + 2 + c.len_utf8(), + _ => i + 1, + } +} + +/// Skips the identifier at `start`; a raw string prefix (`r`, `br`, `cr`) also skips the raw +/// string after it and blanks its contents when `literals` is true. +fn after_ident(b: &[u8], out: &mut [u8], start: usize, literals: bool) -> usize { + let mut i = start; + while i < b.len() && is_ident(b[i]) { + i += 1; + } + if start > 0 && is_ident(b[start - 1]) { + return i; + } + let hashes = b[i..].iter().take_while(|&&h| h == b'#').count(); + if !matches!(&b[start..i], b"r" | b"br" | b"cr") || b.get(i + hashes) != Some(&b'"') { + return i; + } + let body = i + hashes + 1; + let close: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(b, &close, body).unwrap_or(b.len()); + if literals { + blank(out, body, end); + } + (end + close.len()).min(b.len()) +} + +fn find(hay: &[u8], needle: &[u8], from: usize) -> Option { + if needle.is_empty() || from >= hay.len() { + return None; + } + hay[from..].windows(needle.len()).position(|w| w == needle).map(|p| p + from) +} + +fn contains(hay: &[u8], needle: &[u8]) -> bool { + find(hay, needle, 0).is_some() +} + +fn skip_ws(b: &[u8], mut i: usize) -> usize { + while i < b.len() && b[i].is_ascii_whitespace() { + i += 1; + } + i +} + +/// Every start of `word` in `b[from..to]` with no identifier character on either side. +fn words(b: &[u8], word: &[u8], from: usize, to: usize) -> Vec { + let mut out = vec![]; + let mut i = from; + while let Some(at) = find(&b[..to.min(b.len())], word, i) { + let before = at.checked_sub(1).and_then(|j| b.get(j)).copied().is_some_and(is_ident); + let after = b.get(at + word.len()).copied().is_some_and(is_ident); + if !before && !after { + out.push(at); + } + i = at + 1; + } + out +} + +/// The index of the bracket closing the one at `open`. +fn matching(m: &[u8], open: usize) -> Option { + let (o, c) = match m.get(open)? { + b'(' => (b'(', b')'), + b'[' => (b'[', b']'), + b'{' => (b'{', b'}'), + _ => return None, + }; + let mut depth = 0usize; + for (j, &ch) in m.iter().enumerate().skip(open) { + if ch == o { + depth += 1; + } else if ch == c { + depth = depth.saturating_sub(1); + if depth == 0 { + return Some(j); + } + } + } + None +} + +/// The ranges of the top-level comma-separated parts of `m[from..to]`. +fn split_args(m: &[u8], from: usize, to: usize) -> Vec<(usize, usize)> { + let (mut out, mut depth, mut start) = (vec![], 0i32, from); + let mut angles = 0usize; + for (j, &ch) in m.iter().enumerate().take(to).skip(from) { + match ch { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + b'<' if angles > 0 || m[from..j].trim_ascii_end().ends_with(b"::") => angles += 1, + b'>' if angles > 0 => angles -= 1, + b',' if depth == 0 && angles == 0 => { + out.push((start, j)); + start = j + 1; + } + _ => {} + } + } + if m[start..to].iter().any(|c| !c.is_ascii_whitespace()) { + out.push((start, to)); + } + out +} + +/// `b` without whitespace. +fn norm(b: &[u8]) -> String { + String::from_utf8_lossy(&b.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect::>()).into_owned() +} + +/// Line starts, to turn byte offsets into 1-based lines. +struct Lines(Vec); + +impl Lines { + fn new(src: &str) -> Lines { + Lines(std::iter::once(0).chain(src.match_indices('\n').map(|(i, _)| i + 1)).collect()) + } + + fn of(&self, pos: usize) -> usize { + self.0.partition_point(|&s| s <= pos) + } +} + +// ---- Tests and calls ---- + +/// A test function: its name, the offsets of its first attribute and `fn`, and its body's braces. +#[derive(Debug)] +struct TestFn { + name: String, + /// The first attribute of the function (`#[should_panic]` can come before `#[test]`). + attr: usize, + fn_at: usize, + open: usize, + close: usize, +} + +fn is_test_attr(path: &[u8]) -> bool { + matches!(path, b"test" | b"wasm_bindgen_test" | b"test_case") || path.ends_with(b"::test") || path.ends_with(b"::test_case") +} + +/// The test functions of masked source `m`. +fn tests_in(m: &[u8]) -> Vec { + let mut out: Vec = vec![]; + let mut i = 0; + while let Some(at) = find(m, b"#[", i) { + i = at + 2; + let start = skip_ws(m, at + 2); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c) || c == b':').count(); + if !is_test_attr(&m[start..end]) || !matches!(m.get(skip_ws(m, end)), Some(b']' | b'(')) { + continue; + } + let Some(t) = fn_after(m, at, end) else { continue }; + if out.iter().any(|o| o.fn_at == t.fn_at) { + continue; + } + i = t.open; + out.push(t); + } + out +} + +/// The function an attribute at `attr` (ending at `from`) belongs to. +fn fn_after(m: &[u8], attr: usize, from: usize) -> Option { + // The attribute's arguments, and the attributes after it, can hold `;` (`#[test_case(1; "one")]`). + let mut from = from.max(matching(m, attr + 1)? + 1); + while m[skip_ws(m, from)..].starts_with(b"#[") { + from = matching(m, skip_ws(m, from) + 1)? + 1; + } + let limit = (from + 800).min(m.len()); + let fn_at = *words(m, b"fn", from, limit).first()?; + if m[from..fn_at].iter().any(|&c| c == b'{' || c == b';') { + return None; + } + let name_start = skip_ws(m, fn_at + 2); + // Identifiers may hold non-ASCII letters (`échec`); their UTF-8 bytes are all 0x80 or above. + let name_end = name_start + m[name_start..].iter().take_while(|&&c| is_ident(c) || c >= 0x80).count(); + if name_end == name_start { + return None; + } + let open = name_end + m[name_end..].iter().position(|&c| c == b'{' || c == b';')?; + if m[open] != b'{' { + return None; + } + let close = matching(m, open)?; + // The item starts after the previous item or block opening; comments before it are masked. + // Inner attributes (`#![…]`) there belong to the enclosing module or crate. + let mut item = m[..attr].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + while m[skip_ws(m, item)..].starts_with(b"#![") && skip_ws(m, item) < attr { + item = matching(m, skip_ws(m, item) + 2)? + 1; + } + let attr = skip_ws(m, item).min(attr); + Some(TestFn { name: String::from_utf8_lossy(&m[name_start..name_end]).into_owned(), attr, fn_at, open, close }) +} + +/// A macro call in a test: its name, offset and argument ranges. +struct MacroCall { + name: String, + at: usize, + args: Vec<(usize, usize)>, +} + +/// The macro calls (`name!(…)`, `name![…]`, `name!{…}`) in `m[from..to]`. +fn macro_calls(m: &[u8], from: usize, to: usize) -> Vec { + let mut out = vec![]; + let mut i = from; + while let Some(bang) = find(&m[..to], b"!", i) { + i = bang + 1; + let start = (from..bang).rev().take_while(|&j| is_ident(m[j])).last().unwrap_or(bang); + let open = skip_ws(m, bang + 1); + if start == bang || start.checked_sub(1).is_some_and(|j| is_ident(m[j])) || !matches!(m.get(open), Some(b'(' | b'[' | b'{')) { + continue; + } + let Some(close) = matching(m, open).filter(|&c| c < to) else { continue }; + out.push(MacroCall { name: String::from_utf8_lossy(&m[start..bang]).into_owned(), at: start, args: split_args(m, open + 1, close) }); + } + out +} + +fn is_assert_macro(name: &str) -> bool { + ["assert", "debug_assert", "prop_assert"].iter().any(|p| name.starts_with(p)) +} + +const KEYWORDS: &[&str] = &["if", "while", "match", "for", "loop", "return", "fn", "in", "as", "let", "else", "move", "Some", "Ok", "Err"]; + +/// Names that helper detection ignores: too common to tell a helper from the code under test. +const COMMON: &[&str] = &[ + "new", "default", "from", "into", "get", "set", "run", "apply", "build", "make", "open", "load", "save", "parse", "read", "write", "draw", + "render", "len", "clone", "push", "vec", "format", "json", "Box", "Arc", "Vec", "String", "main", +]; + +/// The names called in `m[from..to]`: functions (`name(`, also through a path), methods +/// (`.name(`), including calls with turbofish arguments, and macros (`name!`). +fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { + let m = &m[..to]; + let mut out = vec![]; + let mut i = from; + while i < to { + if !(m[i].is_ascii_alphabetic() || m[i] == b'_') || (i > 0 && is_ident(m[i - 1])) { + i += 1; + continue; + } + let end = i + m[i..to].iter().take_while(|&&c| is_ident(c)).count(); + let bang = m.get(end) == Some(&b'!'); + let after = skip_ws(m, end + usize::from(bang)); + let after = if bang { after } else { skip_turbofish(m, after) }; + if matches!(m.get(after), Some(b'(' | b'[' | b'{')) && (bang || m[after] == b'(') { + let name = String::from_utf8_lossy(&m[i..end]).into_owned(); + let method = i > 0 && m[i - 1] == b'.'; + if !KEYWORDS.contains(&name.as_str()) { + out.push((if bang { format!("{name}!") } else { name }, method)); + } + } + i = end; + } + out +} + +/// Skips optional `::<…>` arguments and the whitespace after them. +fn skip_turbofish(m: &[u8], at: usize) -> usize { + if !m[at..].starts_with(b"::") { + return at; + } + let open = skip_ws(m, at + 2); + if m.get(open) != Some(&b'<') { + return at; + } + let (mut i, mut depth) = (open + 1, 1usize); + while i < m.len() { + match m[i] { + b'<' => depth += 1, + b'>' if m[i - 1] != b'-' => { + depth -= 1; + if depth == 0 { + return skip_ws(m, i + 1); + } + } + b'(' | b'[' | b'{' => i = matching(m, i).unwrap_or(m.len()), + _ => {} + } + i += 1; + } + m.len() +} + +/// Whether `name` (a call in a test) is an asserting helper. +fn is_helper_call(name: &str, method: bool, helpers: &HashSet) -> bool { + let base = name.trim_end_matches('!'); + let named = ["assert", "check", "verify", "ensure", "expect_"].iter().any(|p| base.starts_with(p)); + named || (!method && !COMMON.contains(&base) && helpers.contains(name)) +} + +/// Whether the masked text checks something itself: an assertion, `panic!`, `unwrap_err` or +/// `expect_err`. +fn checks_itself(m: &[u8], from: usize, to: usize) -> bool { + let body = &m[from..to]; + contains(body, b"panic!") + || contains(body, b".unwrap_err()") + || contains(body, b".expect_err(") + || macro_calls(m, from, to).iter().any(|c| is_assert_macro(&c.name)) +} + +/// `tests.rs`, `tests_*.rs`, `*_tests.rs`, files in a `tests` or `benches` folder, and +/// `crates/testkit`. +fn is_test_file(path: &str) -> bool { + let mut parts = path.split('/').rev(); + let file = parts.next().unwrap_or_default(); + file == "tests.rs" + || file.starts_with("tests_") + || file.ends_with("_tests.rs") + || parts.any(|d| d == "tests" || d == "benches") + || path.starts_with("crates/testkit/") +} + +/// Whether a `cfg` predicate holds only in test builds: `test`, or an `all(…)` with such a +/// predicate among its arguments. +fn cfg_requires_test(pred: &[u8]) -> bool { + let pred: Vec = pred.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect(); + if pred == b"test" { + return true; + } + let Some(args) = pred.strip_prefix(b"all(").and_then(|a| a.strip_suffix(b")")) else { return false }; + let mut depth = 0usize; + let mut start = 0; + for (i, &c) in args.iter().enumerate() { + match c { + b'(' => depth += 1, + b')' => depth = depth.saturating_sub(1), + b',' if depth == 0 => { + if cfg_requires_test(&args[start..i]) { + return true; + } + start = i + 1; + } + _ => {} + } + } + cfg_requires_test(&args[start..]) +} + +/// The byte ranges of test code in a file: all of a test file, else each item under a `#[cfg(…)]` +/// that holds only in test builds ([`cfg_requires_test`]) and has a body in the file, and each +/// test function. +fn test_regions(path: &str, m: &[u8], tests: &[TestFn]) -> Vec<(usize, usize)> { + if is_test_file(path) { + return vec![(0, m.len())]; + } + let mut out: Vec<(usize, usize)> = tests.iter().map(|t| (t.attr, t.close)).collect(); + for at in words(m, b"cfg", 0, m.len()) { + let open = skip_ws(m, at + "cfg".len()); + // Whitespace and comments (masked to spaces) may separate `#`, `[` and `cfg`. + let outer_attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + if !outer_attr || m.get(open) != Some(&b'(') { + continue; + } + let Some(close) = matching(m, open) else { continue }; + let end = skip_ws(m, close + 1); + if m.get(end) != Some(&b']') || !cfg_requires_test(&m[open + 1..close]) { + continue; + } + // The item's body: the first `{` before any `;` (`mod tests;` has none here). + let after = end + 1; + let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; + if let (b'{', Some(close)) = (m[open], matching(m, open)) { + out.push((at, close)); + } + } + out +} + +fn in_regions(regions: &[(usize, usize)], pos: usize) -> bool { + regions.iter().any(|&(from, to)| from <= pos && pos <= to) +} + +/// A function or macro in test code: its name (`name!` for a macro), whether it checks something +/// itself, and the names it calls. +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. +pub fn asserting_helpers(files: &[(String, String)]) -> HashMap> { + let mut defs: HashMap> = HashMap::new(); + 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 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() +} + +/// 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 { + 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 + .iter() + .filter(|(name, same)| !known.contains(**name) && same.iter().all(|d| checks(d))) + .map(|(name, _)| (*name).to_owned()) + .collect(); + if more.is_empty() { + return known; + } + known.extend(more); + } +} + +/// The name, kind (`true` for a macro) and body braces of the `fn` or `macro_rules!` at `at`. +fn item_at(m: &[u8], at: usize) -> Option<(&[u8], bool, usize, usize)> { + let is_macro = m[at..].starts_with(b"macro_rules"); + let mut start = skip_ws(m, at + if is_macro { "macro_rules".len() } else { 2 }); + if is_macro { + start = skip_ws(m, start + usize::from(m.get(start) == Some(&b'!'))); + } + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + if end == start { + return None; + } + let open = end + m[end..].iter().position(|&c| c == b'{' || c == b';')?; + if m[open] != b'{' { + return None; + } + Some((&m[start..end], is_macro, open, matching(m, open)?)) +} + +/// The `fn` or `macro_rules!` at `at`. +fn definition(m: &[u8], at: usize) -> Option { + let (name, is_macro, open, close) = item_at(m, at)?; + let name = String::from_utf8_lossy(name).into_owned(); + let called = calls(m, open, close).into_iter().filter(|(_, method)| !method).map(|(n, _)| n).collect(); + Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) +} + +// ---- The rules ---- + +/// The source, its masked copy and its tests. +struct File<'a> { + path: &'a str, + src: &'a [u8], + m: Vec, + /// [`File::m`] with the functions and macros declared inside each test blanked: declaring + /// one does not run its body ([`executed`]). + exec: Vec, + lines: Lines, + tests: Vec, + /// The test code ([`test_regions`]). + regions: Vec<(usize, usize)>, +} + +impl File<'_> { + fn hit(&self, at: usize, rule: Rule, test: &str, note: String) -> Hit { + let line = self.lines.of(at); + Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line } + } + + fn test_at(&self, pos: usize) -> &str { + self.tests.iter().find(|t| t.open <= pos && pos <= t.close).map_or("", |t| t.name.as_str()) + } + + /// The source of `from..to` without whitespace and comments between tokens; string and + /// character literals keep their text. + fn src_norm(&self, (from, to): (usize, usize)) -> String { + let mut out = Vec::with_capacity(to - from); + let mut in_literal = false; + for i in from..to { + let (s, m) = (self.src[i], self.m[i]); + if m == b'"' || (m == b'\'' && !in_literal && self.m.get(i + 1) == Some(&b' ')) { + in_literal = !in_literal; + } else if m == b'\'' && in_literal { + in_literal = false; + } + if in_literal || (m == s && !s.is_ascii_whitespace()) { + out.push(s); + } + } + String::from_utf8_lossy(&out).into_owned() + } +} + +/// Every hit in one file, exemptions applied. +pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { + let m = mask(src); + let tests = tests_in(&m); + let regions = test_regions(path, &m, &tests); + let exec = executed(&m, &tests); + let file = File { path, src: src.as_bytes(), m, exec, lines: Lines::new(src), tests, regions }; + let mut hits: Vec = file.tests.iter().flat_map(|t| test_hits(&file, t, ctx)).collect(); + hits.extend(ignore_hits(&file)); + hits.extend(sleep_hits(&file)); + hits.extend(reads_source_hits(&file)); + let allows = allows(src, &file.m); + hits.retain(|h| { + let first = if h.rule == Rule::AllUnguarded { h.line } else { h.first }; + !allows.iter().any(|&(line, rule)| rule == h.rule && line + 1 >= first && line <= h.line) + }); + hits.sort(); + hits +} + +/// `m` with each `fn` and `macro_rules!` declared inside a test's body replaced by spaces, from +/// its keyword to its closing brace. A call to one stays, so it can still count as a helper call. +fn executed(m: &[u8], tests: &[TestFn]) -> Vec { + let mut out = m.to_vec(); + for t in tests { + for at in words(m, b"fn", t.open, t.close).into_iter().chain(words(m, b"macro_rules", t.open, t.close)) { + if let Some((_, _, _, close)) = item_at(m, at).filter(|&(_, _, _, close)| close < t.close) { + blank(&mut out, at, close + 1); + } + } + } + out +} + +/// `(line, rule)` of each exemption comment that names a rule and a reason. +/// A marker counts only inside a comment: masked (`m`) there, and kept when only literals are +/// masked. +fn allows(src: &str, m: &[u8]) -> Vec<(usize, Rule)> { + let literals = mask_with(src, false); + let lines = Lines::new(src); + src.match_indices(ALLOW) + .filter(|&(p, _)| m[p] == b' ' && literals[p] == b't') + .filter_map(|(p, _)| { + // The reason ends with the line, or with the block comment that holds the marker. + let rest = src[p + ALLOW.len()..].lines().next()?.split("*/").next()?; + let mut words = rest.split_whitespace(); + let rule = Rule::from_id(words.next()?)?; + words.next().map(|_| (lines.of(p), rule)) + }) + .collect() +} + +/// What the rules read of one test. +struct View<'a> { + file: &'a File<'a>, + t: &'a TestFn, + asserts: Vec, + delegates: bool, + checks: bool, + should_panic: 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 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 mut hits = all_unguarded(&v); + hits.extend(self_compare(&v)); + hits.extend(early_returns(&v)); + hits.extend(env_gates(&v, ctx)); + hits.extend([only_weak(&v), exit_status_only(&v), no_assertion(&v)].into_iter().flatten()); + hits +} + +/// Whether the attributes in `m[from..to]` include an applied `should_panic`: `#[should_panic]`, +/// `#[should_panic(…)]`, or one inside `#[cfg_attr(test, …)]`. Another `cfg_attr` predicate may +/// not hold, so it does not count. +fn should_panic_attr(m: &[u8], from: usize, to: usize) -> bool { + let attached = words(m, b"should_panic", from, to).into_iter().any(|at| { + let before = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + before && matches!(m.get(skip_ws(m, at + "should_panic".len())), Some(b']' | b'(')) + }); + attached + || words(m, b"cfg_attr", from, to).into_iter().any(|at| { + let open = skip_ws(m, at + "cfg_attr".len()); + let Some(close) = matching(m, open).filter(|&c| m[open] == b'(' && c < to) else { return false }; + let args = split_args(m, open + 1, close); + let name = |&(f, t): &(usize, usize)| { + let a = norm(&m[f..t]); + a == "should_panic" || a.starts_with("should_panic(") + }; + args.first().is_some_and(|&(f, t)| norm(&m[f..t]) == "test") && args.iter().skip(1).any(name) + }) +} + +impl View<'_> { + fn hit(&self, at: usize, rule: Rule, note: String) -> Hit { + self.file.hit(at, rule, &self.t.name, note) + } + + /// A hit for the whole test, on its `fn` line. + fn whole(&self, rule: Rule, note: String) -> Hit { + let mut h = self.hit(self.t.fn_at, rule, note); + h.first = self.file.lines.of(self.t.attr); + h.last = self.file.lines.of(self.t.close); + h + } + + fn body(&self) -> &[u8] { + &self.file.exec[self.t.open..self.t.close] + } + + /// The masked body with assertion failure-message arguments replaced by spaces. + fn body_without_messages(&self) -> Vec { + let mut body = self.body().to_vec(); + for a in &self.asserts { + for &(from, to) in a.args.iter().skip(guard_arg_count(&a.name)) { + blank(&mut body, from - self.t.open, to - self.t.open); + } + } + body + } + + /// The first argument of an assertion, masked, without whitespace. + fn first_arg(&self, a: &MacroCall) -> String { + a.args.first().map(|&(f, t)| norm(&self.file.m[f..t])).unwrap_or_default() + } +} + +const PLAIN_ASSERTS: &[&str] = &["assert", "debug_assert", "prop_assert"]; + +/// Calls whose result says how many items a collection has. +const SIZE_CHECKS: &[&str] = &[".len()", ".is_empty()", ".count()", ".first()", ".any(", ".next()", ".last()"]; + +fn all_unguarded(v: &View) -> Vec { + let mut body = v.body_without_messages(); + strip_all_predicates(&mut body); + let locals = bindings(&body); + let checked = v.asserts.iter().any(|a| { + a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { + let (from, to) = (from - v.t.open, to - v.t.open); + 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() }; + 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)) + .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); + h.last = v.file.lines.of(v.t.close); + h + }) + .collect() +} + +/// The number of condition or compared operands in a standard assertion macro. +fn guard_arg_count(name: &str) -> usize { + match name { + "assert" | "debug_assert" | "prop_assert" => 1, + "assert_eq" | "assert_ne" | "debug_assert_eq" | "debug_assert_ne" | "prop_assert_eq" | "prop_assert_ne" => 2, + _ => 0, + } +} + +/// Blanks `.all(…)` predicates so their checks do not guard the collection. +fn strip_all_predicates(body: &mut [u8]) { + for at in words(body, b"all", 0, body.len()) { + let method = body[..at].trim_ascii_end().ends_with(b"."); + let open = skip_ws(body, at + 3); + let Some(close) = (method && body.get(open) == Some(&b'(')).then(|| matching(body, open)).flatten() else { continue }; + blank(body, at, close + 1); + } +} + +/// Whether test code accesses a first item in a way that fails on an empty collection. +fn first_item_guard(body: &[u8], sizes: &Sizes) -> bool { + let compact = norm(body); + let unwrapped = [".first().unwrap()", ".first().expect(", ".next().unwrap()", ".next().expect("]; + let indexed = compact.match_indices("[0]").any(|(at, _)| array_literal_len(&compact[..at + 3], sizes).is_none_or(|n| n == 0)); + indexed || unwrapped.iter().any(|g| compact.contains(g)) || panicking_first_binding(body) +} + +/// Whether a `let Some(…) = ….first() else { panic!(…) }` binding checks for an item. +fn panicking_first_binding(body: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let rest = &body[at + 3..]; + let Some(otherwise) = words(rest, b"else", 0, rest.len()).first().copied() else { return false }; + let binding = norm(&rest[..otherwise]); + let Some(close) = binding.strip_prefix("Some(").and_then(|_| matching(binding.as_bytes(), 4)) else { return false }; + let Some(value) = binding[close + 1..].strip_prefix('=') else { return false }; + let first = value.ends_with(".first()") || value.ends_with(".next()"); + first && !value.contains([';', '{', '}']) && norm(&rest[otherwise + 4..]).starts_with("{panic!(") + }) +} + +/// Whether a (masked, whitespace-free) condition holds an `.all(…)` that an empty collection would +/// pass by mistake. Left out: a negated result, a closure that says no item matches (whole +/// negations or `!=` comparisons joined only by `&&`), and a collection the test shows cannot be +/// empty ([`least_items`]). +fn unguarded_all(cond: &str, body: &[u8], sizes: &Sizes) -> bool { + all_with_polarity(cond, true, body, sizes) +} + +/// Tracks negation through boolean operands and comparisons with `false`. +fn all_with_polarity(cond: &str, positive: bool, body: &[u8], sizes: &Sizes) -> bool { + if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) { + return all_with_polarity(&cond[1..cond.len() - 1], positive, body, sizes); + } + if let Some(at) = boolean_split(cond) { + return all_with_polarity(&cond[..at], positive, body, sizes) || all_with_polarity(&cond[at + 2..], positive, body, sizes); + } + if let Some(expr) = cond.strip_suffix("==false").or_else(|| cond.strip_prefix("false==")) { + return all_with_polarity(expr, !positive, body, sizes); + } + if let Some(expr) = cond.strip_prefix('!') { + return all_with_polarity(expr, !positive, body, sizes); + } + positive && positive_all(cond, body, sizes) +} + +/// Finds a boolean operator outside parentheses, brackets and braces. +fn boolean_split(cond: &str) -> Option { + let b = cond.as_bytes(); + let mut at = 0; + while at < b.len() { + if b[at..].starts_with(b"&&") || b[at..].starts_with(b"||") { + return Some(at); + } + at = if matches!(b[at], b'(' | b'[' | b'{') { matching(b, at)? + 1 } else { at + 1 }; + } + None +} + +fn positive_all(cond: &str, test_body: &[u8], sizes: &Sizes) -> bool { + cond.match_indices(".all(").any(|(i, _)| { + let rest = &cond[i + ".all(".len()..]; + let arg = &rest[..arg_end(rest)]; + 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 + }) +} + +/// Whether every boolean operand is a whole negation or `!=` comparison joined only by `&&`. +fn not_equal_conjunction(body: &str) -> bool { + if body.starts_with('(') && matching(body.as_bytes(), 0) == Some(body.len() - 1) { + return not_equal_conjunction(&body[1..body.len() - 1]); + } + if let Some(at) = boolean_split(body) { + return body[at..].starts_with("&&") && not_equal_conjunction(&body[..at]) && not_equal_conjunction(&body[at + 2..]); + } + if whole_negation(body) { + return true; + } + let (mut at, mut comparisons) = (0, 0); + let b = body.as_bytes(); + while at < b.len() { + if b[at..].starts_with(b"!=") { + comparisons += 1; + at += 2; + } else if matches!(b[at], b'=' | b'<' | b'>' | b'&' | b'|') { + return false; + } else if matches!(b[at], b'(' | b'[' | b'{') { + let Some(close) = matching(b, at) else { return false }; + at = close + 1; + } else { + at += 1; + } + } + comparisons == 1 +} + +/// Whether `!` negates the whole operand rather than one side of a binary expression. +fn whole_negation(body: &str) -> bool { + let Some(rest) = body.strip_prefix('!') else { return false }; + let rest = rest.trim_start_matches(['!', '*', '&']); + let b = rest.as_bytes(); + let mut at = 0; + while at < b.len() { + if matches!(b[at], b'=' | b'<' | b'>' | b'&' | b'|' | b'+' | b'-' | b'*' | b'/' | b'%' | b'^') { + return false; + } + at = if matches!(b[at], b'(' | b'[' | b'{') { + let Some(close) = matching(b, at) else { return false }; + close + 1 + } else { + at + 1 + }; + } + !rest.is_empty() +} + +/// The fewest items the test shows `receiver` (the text before `.all(`, without its iterator +/// method) to have: a non-empty array literal, a plain local bound to one or to a sized +/// initializer ([`expr_len`]) or filled by a loop ([`loop_fill_len`]), a plain local an earlier +/// equality assertion compares with a non-empty literal, or a field the file declares as an +/// array of a positive length. 0 when the test does not show it. +fn least_items(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { + let literal = array_literal_len(receiver, sizes).unwrap_or(0); + let derived = derived_locals(receiver, body).iter().map(|(d, from)| equal_len(d, body, sizes, Some(*from))).max().unwrap_or(0); + literal + .max(bound_len(receiver, body, sizes)) + .max(equal_len(receiver, body, sizes, None)) + .max(derived) + .max(field_len(receiver, sizes)) + .max(if binds(body, array_receiver(receiver).as_bytes()) { 0 } else { item_len(receiver, sizes) }) +} + +/// Whether `body` has a `let` binding of `name`. +fn binds(body: &[u8], name: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); + } + body[start..].starts_with(name) && !body.get(start + name.len()).copied().is_some_and(is_ident) + }) +} + +/// Methods that give at least one item for each distinct item they are given, and none from none, +/// with `collect` restricted to known collection targets. +const KEEPING: &[&str] = &["map", "iter", "into_iter", "cloned", "copied", "enumerate", "rev", "collect", "to_vec", "to_owned", "clone"]; + +/// Whether a normalized type names a collection that keeps an item of a non-empty iterator. +fn known_collection(ty: &str) -> bool { + let (name, args) = ty.split_once('<').map_or((ty, None), |(name, args)| (name, args.strip_suffix('>'))); + match name { + "Vec" | "std::vec::Vec" | "String" | "std::string::String" => true, + "Box" | "std::boxed::Box" => args.is_some_and(|args| { + args.starts_with('[') && matching(args.as_bytes(), 0) == Some(args.len() - 1) && !has_top_level(&args.as_bytes()[1..args.len() - 1], b';') + }), + _ => matches!( + name.strip_prefix("std::collections::").unwrap_or(name), + "VecDeque" | "HashSet" | "BTreeSet" | "HashMap" | "BTreeMap" | "BinaryHeap" | "LinkedList" + ), + } +} + +/// `operand` (masked, whitespace-free) without trailing calls of [`KEEPING`] methods: the +/// collection a compared or bound value was built from. Only the final call may use an +/// inferred `collect` target, when the caller knows it is a collection. +fn keeping_base(operand: &str, inferred_collect: bool) -> &str { + let mut op = operand; + while op.ends_with(')') { + let b = op.as_bytes(); + let mut depth = 0usize; + let Some(open) = (0..b.len()).rev().find(|&i| { + match b[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' => depth = depth.saturating_sub(1), + _ => {} + } + depth == 0 + }) else { + break; + }; + let mut head = &op[..open]; + let mut target = None; + if head.ends_with('>') { + let Some(turbofish) = head.rfind("::<") else { break }; + target = Some(&head[turbofish + 3..head.len() - 1]); + head = &head[..turbofish]; + } + let Some((rest, method)) = head.rsplit_once('.') else { break }; + if !KEEPING.contains(&method) || (method == "collect" && !target.map_or(inferred_collect && op.len() == operand.len(), known_collection)) { + break; + } + op = rest; + } + op +} + +/// Plain locals of the test bound (`let name = …;`, latest binding) to `receiver` through +/// [`KEEPING`] methods only, so they have no more distinct items than it, when no later code may +/// shrink or replace `receiver` ([`may_shrink`]), paired with the end of each binding. +fn derived_locals(receiver: &str, body: &[u8]) -> Vec<(String, usize)> { + let name = array_receiver(receiver); + if !plain_local(name) { + return vec![]; + } + let mut latest: HashMap = HashMap::new(); + for at in words(body, b"let", 0, body.len()) { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); + } + let end = start + body[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || body[start].is_ascii_digit() { + continue; + } + let stop = statement_end(body, end); + let stmt = norm(&body[end..stop]); + let (annotation, from) = stmt.split_once('=').unwrap_or(("", "")); + let inferred_collect = annotation.strip_prefix(':').is_some_and(known_collection); + let base = keeping_base(from, inferred_collect); + let derived = base != from && collection_operand(base) == name && !may_shrink(body, name.as_bytes(), stop); + latest.insert(String::from_utf8_lossy(&body[start..end]).into_owned(), (derived, stop)); + } + latest.into_iter().filter(|&(_, (derived, _))| derived).map(|(n, (_, stop))| (n, stop)).collect() +} + +/// The length a `const` or `static` item of the file declares for a plain name +/// (`const NAME: [T; N]`), taking the smallest length across all declarations of that name, +/// or 0 when any declaration has an unknown or non-array type. +fn item_len(receiver: &str, sizes: &Sizes) -> usize { + let name = array_receiver(receiver); + if !plain_local(name) { + return 0; + } + let file = sizes.file; + let mut len = None; + for at in words(file, name.as_bytes(), 0, file.len()) { + let before = file[..at].trim_ascii_end(); + let before = before.strip_suffix(b"mut").map_or(before, |b| b.trim_ascii_end()); + let keyword = |w: &[u8]| before.ends_with(w) && !before.len().checked_sub(w.len() + 1).is_some_and(|j| is_ident(before[j])); + if !keyword(b"const") && !keyword(b"static") { + continue; + } + let colon = skip_ws(file, at + name.len()); + let ty = skip_ws(file, colon + 1); + if file.get(colon) != Some(&b':') || file.get(ty) != Some(&b'[') { + return 0; + } + let Some(close) = matching(file, ty) else { return 0 }; + let count = repeat_count(&file[ty + 1..close], sizes).unwrap_or(0); + len = Some(len.map_or(count, |n: usize| n.min(count))); + } + len.unwrap_or(0) +} + +/// The receiver without its iterator method and the items it needs for `.all(…)` to see one: +/// `.windows(k)` and `.chunks_exact(k)` need `k`, anything else one. An unknown `k` needs more +/// than any collection has. +fn receiver_need<'a>(receiver: &'a str, sizes: &Sizes) -> (&'a str, usize) { + let r = array_receiver(receiver); + for (method, exact) in [(".windows(", true), (".chunks_exact(", true), (".chunks(", false)] { + let Some(at) = r.rfind(method) else { continue }; + let open = at + method.len() - 1; + if matching(r.as_bytes(), open) != Some(r.len() - 1) { + continue; + } + let need = match sizes.count(&r[open + 1..r.len() - 1]) { + Some(k) if k > 0 => { + if exact { + k + } else { + 1 + } + } + _ => usize::MAX, + }; + return (array_receiver(&r[..at]), need); + } + (r, 1) +} + +/// The length of the non-empty literal an earlier equality assertion compares this plain local +/// receiver with, or 0. For a derived local, its binding must reach the assertion unchanged. +fn equal_len(receiver: &str, body: &[u8], sizes: &Sizes, binding: Option) -> usize { + let name = array_receiver(receiver); + if !plain_local(name) { + return 0; + } + let lens = macro_calls(body, 0, body.len()).into_iter().filter_map(|a| { + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) { + return None; + } + let &(lf, lt) = a.args.first()?; + let &(rf, rt) = a.args.get(1)?; + if binding.is_some_and(|from| lf < from || may_change(&body[..lf], name.as_bytes(), from, false)) { + return None; + } + let end = a.args.last().map_or(rt, |&(_, to)| to); + if may_shrink(body, name.as_bytes(), end) { + return None; + } + let (left, right) = (norm(&body[lf..lt]), norm(&body[rf..rt])); + if collection_operand(keeping_base(&left, true)) == name { + Some(literal_len(&right, sizes)) + } else if collection_operand(keeping_base(&right, true)) == name { + Some(literal_len(&left, sizes)) + } else { + None + } + }); + lens.max().unwrap_or(0) +} + +/// Whether `name` is a plain local name: an identifier that does not start with a digit. +fn plain_local(name: &str) -> bool { + !name.is_empty() && !name.as_bytes()[0].is_ascii_digit() && name.bytes().all(is_ident) +} + +/// Removes one borrow and a slice view from a compared operand. +fn collection_operand(operand: &str) -> &str { + let operand = operand.strip_prefix('&').unwrap_or(operand); + operand.strip_suffix(".as_slice()").or_else(|| operand.strip_suffix("[..]")).unwrap_or(operand) +} + +/// The length of an operand that is wholly an array literal or `vec![…]`, else 0. +fn literal_len(operand: &str, sizes: &Sizes) -> usize { + let b = operand.strip_prefix("vec!").unwrap_or(operand).as_bytes(); + if b.first() == Some(&b'[') && matching(b, 0) == Some(b.len() - 1) { array_len(&b[1..b.len() - 1], sizes) } else { 0 } +} + +/// The length of a call's arguments in `rest`, the text after its `(`: up to its closing bracket. +fn arg_end(rest: &str) -> usize { + let mut depth = 0i32; + rest.bytes() + .position(|c| { + depth += match c { + b'(' | b'[' | b'{' => 1, + b')' | b']' | b'}' => -1, + _ => 0, + }; + depth < 0 + }) + .unwrap_or(rest.len()) +} + +/// The length of the array literal `receiver` (the text before `.all(`) ends with, through +/// `.iter()` or `.into_iter()`, or `None` when it does not end with one. +fn array_literal_len(receiver: &str, sizes: &Sizes) -> Option { + let r = array_receiver(receiver); + let b = r.as_bytes(); + if b.last() != Some(&b']') { + return None; + } + let mut depth = 0usize; + for (j, &c) in b.iter().enumerate().rev() { + match c { + b']' => depth += 1, + b'[' => { + depth = depth.saturating_sub(1); + if depth == 0 { + let literal = !j.checked_sub(1).and_then(|k| b.get(k)).is_some_and(|&p| is_ident(p) || matches!(p, b')' | b']' | b'.')); + return literal.then(|| array_len(&b[j + 1..b.len() - 1], sizes)); + } + } + _ => {} + } + } + None +} + +/// Removes the iterator method from an array receiver. +fn array_receiver(receiver: &str) -> &str { + receiver.strip_suffix(".iter()").or_else(|| receiver.strip_suffix(".into_iter()")).unwrap_or(receiver) +} + +/// The fewest items a plain local receiver has after its latest preceding binding still in scope: from the +/// binding ([`array_binding`]) or a loop that fills it ([`loop_fill_len`]), and 0 when a later +/// statement may shrink or replace it ([`may_shrink`]). +fn bound_len(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { + let name = array_receiver(receiver); + if !plain_local(name) { + return 0; + } + let name = name.as_bytes(); + let mut in_scope = words(body, b"let", 0, body.len()).into_iter().rev().filter(|&at| open_at_end(body, at)); + let Some((len, end)) = in_scope.find_map(|at| array_binding(body, at, name, sizes)) else { + return 0; + }; + if may_shrink(body, name, end) { + return 0; + } + len.max(loop_fill_len(body, name, end, sizes)) +} + +/// Whether the block holding offset `at` of `body` is still open at the end of `body`: a binding +/// there is still in scope. +fn open_at_end(body: &[u8], at: usize) -> bool { + let mut depth = 0usize; + for &c in &body[at..] { + match c { + b'{' => depth += 1, + b'}' if depth == 0 => return false, + b'}' => depth -= 1, + _ => {} + } + } + true +} + +/// For a `let` at `at` that binds `name` (allowing `mut`): the fewest items its array type +/// annotation gives (which decides when there is one), else its initializer gives ([`expr_len`]), +/// and where the statement ends. `None` for a binding of another name. +fn array_binding(body: &[u8], at: usize, name: &[u8], sizes: &Sizes) -> Option<(usize, usize)> { + let mut at = skip_ws(body, at + 3); + if body[at..].starts_with(b"mut") && body.get(at + 3).is_some_and(u8::is_ascii_whitespace) { + at = skip_ws(body, at + 3); + } + let end = at + body[at..].iter().copied().take_while(|&c| is_ident(c)).count(); + if &body[at..end] != name { + return None; + } + let stop = statement_end(body, end); + let stmt = &body[end..stop]; + let eq = (0..stmt.len()).find(|&i| { + stmt[i] == b'=' + && !matches!(stmt.get(i + 1), Some(b'=' | b'>')) + && !matches!(i.checked_sub(1).map(|j| stmt[j]), Some(b'=' | b'!' | b'<' | b'>')) + }); + let (annotation, init) = match eq { + Some(eq) => (&stmt[..eq], Some(&stmt[eq + 1..])), + None => (stmt, None), + }; + let annotation = norm(annotation); + if let Some(ty) = annotation.strip_prefix(':') + && ty.starts_with('[') + && matching(ty.as_bytes(), 0) == Some(ty.len() - 1) + { + return Some((repeat_count(&ty.as_bytes()[1..ty.len() - 1], sizes).unwrap_or(0), stop)); + } + Some((init.map_or(0, |init| expr_len(&norm(init), sizes, annotation.strip_prefix(':').unwrap_or(""))), stop)) +} + +/// The index of the `;` that ends the statement starting at `from`, outside brackets, or the +/// end of `body`. +fn statement_end(body: &[u8], from: usize) -> usize { + let mut at = from; + while at < body.len() { + match body[at] { + b';' => return at, + b'(' | b'[' | b'{' => match matching(body, at) { + Some(close) => at = close + 1, + None => return body.len(), + }, + _ => at += 1, + } + } + body.len() +} + +/// The fewest items a (masked, whitespace-free) expression yields: an array literal or `vec![…]`, +/// a literal range, either followed only by methods that keep at least one item of a non-empty +/// input (`map`, `iter`, `into_iter`, `cloned`, `copied`, `enumerate`, `rev`, `chain`, `to_vec`, +/// `to_owned`, `clone`, and `collect` into a known collection or `step_by`, after which at least +/// one is known). Only a final `collect` without a turbofish can use the binding's type. 0 for +/// anything else. +fn expr_len(e: &str, sizes: &Sizes, binding_type: &str) -> usize { + let e = e.strip_prefix("vec!").unwrap_or(e); + let b = e.as_bytes(); + let (mut n, mut rest) = match b.first() { + Some(b'[') => { + let Some(close) = matching(b, 0) else { return 0 }; + (array_len(&b[1..close], sizes), &e[close + 1..]) + } + Some(b'(') => { + let Some(close) = matching(b, 0) else { return 0 }; + (range_len(&e[1..close], sizes), &e[close + 1..]) + } + _ => return range_len(e, sizes), + }; + while !rest.is_empty() { + let Some(tail) = rest.strip_prefix('.') else { return 0 }; + let end = tail.bytes().take_while(|&c| is_ident(c)).count(); + let method = &tail[..end]; + let mut open = end; + if tail[open..].starts_with("::<") { + let mut depth = 0usize; + let Some(close) = tail[open + 2..].bytes().position(|c| { + depth = match c { + b'<' => depth + 1, + b'>' => depth.saturating_sub(1), + _ => depth, + }; + depth == 0 + }) else { + return 0; + }; + open += 2 + close + 1; + } + if tail.as_bytes().get(open) != Some(&b'(') { + return 0; + } + let Some(close) = matching(tail.as_bytes(), open) else { return 0 }; + match method { + "map" | "iter" | "into_iter" | "cloned" | "copied" | "enumerate" | "rev" | "chain" | "to_vec" | "to_owned" | "clone" => {} + "collect" => { + let target = if open > end { + &tail[end + 3..open - 1] + } else if close + 1 == tail.len() { + binding_type + } else { + "" + }; + if !known_collection(target) { + return 0; + } + n = n.min(1); + } + "step_by" => n = n.min(1), + _ => return 0, + } + rest = &tail[close + 1..]; + } + n +} + +/// The number of items in a range of integer literals or constants (`a..b`, `a..=b`); 0 for +/// anything else, an open range included. +fn range_len(e: &str, sizes: &Sizes) -> usize { + let (lo, hi, inclusive) = match e.split_once("..=") { + Some((lo, hi)) => (lo, hi, true), + None => match e.split_once("..") { + Some((lo, hi)) => (lo, hi, false), + None => return 0, + }, + }; + let value = |t: &str| match t.strip_prefix('-') { + Some(t) => sizes.count(t).and_then(|v| i128::try_from(v).ok()).map(|v| -v), + None => sizes.count(t).and_then(|v| i128::try_from(v).ok()), + }; + let (Some(lo), Some(hi)) = (value(lo), value(hi)) else { return 0 }; + let len = hi - lo + i128::from(inclusive); + usize::try_from(len).unwrap_or(0) +} + +/// The number of items in an array literal's masked contents: the count of a repetition, or the +/// elements of a list. +fn array_len(contents: &[u8], sizes: &Sizes) -> usize { + if let Some(count) = repeat_count(contents, sizes) { + return count; + } + if has_top_level(contents, b';') { + return 0; + } + split_args(contents, 0, contents.len()).len() +} + +/// The count of a repetition `[x; N]` (a literal or a `const` of the file), from its masked +/// contents; `None` when they are not a repetition, `Some(0)` when the count is not known. +fn repeat_count(contents: &[u8], sizes: &Sizes) -> Option { + let mut at = 0; + while at < contents.len() { + match contents[at] { + b';' => return Some(sizes.count(&norm(&contents[at + 1..])).unwrap_or(0)), + b'(' | b'[' | b'{' => at = matching(contents, at)? + 1, + _ => at += 1, + } + } + None +} + +/// Whether `c` occurs in `b` outside brackets. +fn has_top_level(b: &[u8], c: u8) -> bool { + let mut at = 0; + while at < b.len() { + match b[at] { + x if x == c => return true, + b'(' | b'[' | b'{' => match matching(b, at) { + Some(close) => at = close + 1, + None => return true, + }, + _ => at += 1, + } + } + false +} + +/// The fewest items a `for` loop after `from`, in the same block, adds to `name`: a loop over a +/// sized source ([`expr_len`]) whose own block (not a nested one) pushes or inserts into `name` +/// on every pass, with no `break`, `continue`, `return` or `?` in the loop. 0 when there is none. +fn loop_fill_len(body: &[u8], name: &[u8], from: usize, sizes: &Sizes) -> usize { + let mut best = 0; + for at in words(body, b"for", from, body.len()) { + if block_depth(&body[from..at]) != Some(0) { + continue; + } + let Some(&in_at) = words(body, b"in", at + 3, body.len()).first() else { continue }; + let Some(open) = (in_at + 2..body.len()).find(|&i| body[i] == b'{' && !has_open_bracket(&body[in_at + 2..i])) else { continue }; + let Some(close) = matching(body, open) else { continue }; + let source = expr_len(&norm(&body[in_at + 2..open]), sizes, ""); + let block = &body[open + 1..close]; + let exits = [&b"break"[..], b"continue", b"return"].iter().any(|w| !words(block, w, 0, block.len()).is_empty()) || contains(block, b"?"); + if source == 0 || exits { + continue; + } + let pushes = words(block, name, 0, block.len()).into_iter().any(|p| { + let before = block[..p].trim_ascii_end(); + let statement = matches!(before.last(), None | Some(b';' | b'{' | b'}')); + let call = norm(&block[p + name.len()..block.len().min(p + name.len() + 16)]); + statement && block_depth(&block[..p]) == Some(0) && [".push(", ".push_back(", ".insert("].iter().any(|m| call.starts_with(m)) + }); + if pushes { + best = best.max(source); + } + } + best +} + +/// The brace depth at the end of `b`, or `None` when it closes a block it did not open. +fn block_depth(b: &[u8]) -> Option { + let mut depth = 0usize; + for &c in b { + match c { + b'{' => depth += 1, + b'}' => depth = depth.checked_sub(1)?, + _ => {} + } + } + Some(depth) +} + +/// Whether `b` leaves a `(` or `[` open. +fn has_open_bracket(b: &[u8]) -> bool { + let mut depth = 0i32; + for &c in b { + match c { + b'(' | b'[' => depth += 1, + b')' | b']' => depth -= 1, + _ => {} + } + } + depth > 0 +} + +/// Whether code after `from` may remove items from `name` or replace it. +fn may_shrink(body: &[u8], name: &[u8], from: usize) -> bool { + may_change(body, name, from, true) +} + +/// Whether code after `from` may change the item count of `name`: an unknown method call, +/// an assignment, or a `&mut` borrow. Growth is harmless only for the source collection. +fn may_change(body: &[u8], name: &[u8], from: usize, allow_growth: bool) -> bool { + const PRESERVING: &[&str] = &[ + "iter", + "iter_mut", + "into_iter", + "len", + "is_empty", + "contains", + "get", + "get_mut", + "first", + "last", + "first_mut", + "last_mut", + "as_slice", + "as_ref", + "clone", + "to_vec", + "to_owned", + "windows", + "chunks", + "chunks_exact", + "sort", + "sort_by", + "sort_by_key", + "sort_unstable", + "sort_unstable_by", + "sort_unstable_by_key", + "reverse", + "binary_search", + "binary_search_by", + "binary_search_by_key", + "starts_with", + "ends_with", + "map", + "concat", + "join", + "keys", + "values", + ]; + const ADDING: &[&str] = &["push", "push_back", "push_front", "insert", "extend"]; + words(body, name, from, body.len()).into_iter().any(|p| { + let after = &body[skip_ws(body, p + name.len())..]; + let assigned = (after.starts_with(b"=") && !after.starts_with(b"==") && !after.starts_with(b"=>")) + || ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="].iter().any(|op| after.starts_with(op.as_bytes())); + let before = body[from..p].trim_ascii_end(); + let borrowed = before.strip_suffix(b"mut").is_some_and(|b| b.trim_ascii_end().ends_with(b"&")); + let called = if after.first() == Some(&b'.') { + let start = skip_ws(after, 1); + let end = start + after[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + let rest = &after[skip_ws(after, end)..]; + let method = &after[start..end]; + (rest.starts_with(b"(") || rest.starts_with(b"::<")) + && !PRESERVING.iter().any(|m| method == m.as_bytes()) + && !(allow_growth && ADDING.iter().any(|m| method == m.as_bytes())) + } else { + false + }; + assigned || borrowed || called + }) +} + +/// The length of a field the file declares as an array of a positive length (`name: [T; N]`), +/// for a receiver `….name`. 0 when any other `name:` in the file may start a type: anything but +/// an array, a lowercase name that is not a path or a primitive type (a value in a struct +/// expression), or a literal. +fn field_len(receiver: &str, sizes: &Sizes) -> usize { + let Some((owner, field)) = receiver.rsplit_once('.') else { return 0 }; + if owner.is_empty() || !plain_local(field) { + return 0; + } + const PRIMITIVE: &[&str] = &[ + "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "f32", "f64", "bool", "char", "str", "dyn", "impl", + "fn", "mut", "crate", "self", "super", + ]; + let file = sizes.file; + let mut least: Option = None; + for at in words(file, field.as_bytes(), 0, file.len()) { + let colon = skip_ws(file, at + field.len()); + if file.get(colon) != Some(&b':') || file.get(colon + 1) == Some(&b':') || at.checked_sub(1).is_some_and(|j| file[j] == b':') { + continue; + } + let ty = skip_ws(file, colon + 1); + let word_end = ty + file[ty..].iter().copied().take_while(|&c| is_ident(c)).count(); + let word = &file[ty..word_end]; + let value = match file.get(ty) { + Some(b'[') => false, + Some(c) if c.is_ascii_digit() || matches!(c, b'"' | b'\'' | b'-') => true, + Some(c) if c.is_ascii_lowercase() || *c == b'_' => { + let path = file[skip_ws(file, word_end)..].starts_with(b"::"); + !path && !PRIMITIVE.iter().any(|p| p.as_bytes() == word) + } + _ => return 0, + }; + if value { + continue; + } + let Some(close) = matching(file, ty) else { return 0 }; + match repeat_count(&file[ty + 1..close], sizes) { + Some(n) if n > 0 => least = Some(least.map_or(n, |l| l.min(n))), + Some(_) => return 0, + None => {} + } + } + least.unwrap_or(0) +} + +/// What the rules know about collection sizes in one masked file: its `const` counts, read on first use. +struct Sizes<'a> { + file: &'a [u8], + consts: OnceCell>, +} + +impl Sizes<'_> { + /// 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 { + int_literal(text).or_else(|| self.consts.get_or_init(|| file_consts(self.file)).get(text).copied()) + } +} + +fn int_literal(text: &str) -> Option { + let digits = text.bytes().take_while(|c| c.is_ascii_digit() || *c == b'_').count(); + let suffix = &text[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) { + return None; + } + text[..digits].replace('_', "").parse().ok() +} + +/// `const NAME: T = ;` in a masked file. A name declared more than once with +/// different values, or with a value that is not a literal, is left out (its value is unknown). +fn file_consts(file: &[u8]) -> HashMap { + // `None` for a name declared with a value that is not a literal or with different values. + let mut out: HashMap> = HashMap::new(); + for at in words(file, b"const", 0, file.len()) { + let start = skip_ws(file, at + 5); + let end = start + file[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || skip_ws(file, end) >= file.len() || file[skip_ws(file, end)] != b':' { + continue; + } + let stop = statement_end(file, end); + let stmt = norm(&file[end..stop]); + let Some((_, value)) = stmt.split_once('=') else { continue }; + let value = int_literal(value); + let name = String::from_utf8_lossy(&file[start..end]).into_owned(); + let slot = out.entry(name).or_insert(value); + if *slot != value { + *slot = None; + } + } + out.into_iter().filter_map(|(name, value)| Some((name, value?))).collect() +} + +/// A `let` of a plain name: the name, where the statement ends, and whether it binds an expression +/// that checks a size ([`SIZE_CHECKS`]). +struct Binding { + name: Vec, + end: usize, + counts: bool, + /// The local whose method the initializer calls (`xs` in `let n = xs.len()`). + source: Option>, +} + +/// Every `let` of a plain name in `body`, in order. +fn bindings(body: &[u8]) -> Vec { + words(body, b"let", 0, body.len()) + .into_iter() + .filter_map(|at| { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); + } + let end = start + body[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || body[start].is_ascii_digit() { + return None; + } + let stop = statement_end(body, end); + let stmt = norm(&body[end..stop]); + let init = stmt.split_once('=').map_or("", |(_, init)| init); + let counts = SIZE_CHECKS.iter().any(|g| init.contains(g)); + let ident = init.bytes().take_while(|&c| is_ident(c)).count(); + let source = (ident > 0 && init[ident..].starts_with('.')).then(|| init.as_bytes()[..ident].to_vec()); + Some(Binding { name: body[start..end].to_vec(), end: stop, counts, source }) + }) + .collect() +} + +/// Whether `body[from..to]` (an assertion operand) reads a local whose binding reaching that +/// point checks a size and was not assigned since, of a collection that no later code may shrink +/// or replace. +fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> bool { + all.iter().filter(|b| b.counts && b.name != b"_").any(|b| { + words(body, &b.name, from, to).into_iter().any(|p| { + let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p); + reaching + .is_some_and(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end) && r.source.as_ref().is_none_or(|s| !may_shrink(body, s, r.end))) + }) + }) +} + +/// Whether an assertion's (masked, whitespace-free) condition only says that there is a value. +fn is_weak(cond: &str) -> bool { + let cond = unparenthesized(cond); + let (negated, expr) = match cond.strip_prefix('!') { + Some(rest) => (true, unparenthesized(rest)), + None => (false, cond), + }; + let plain = |rest: &str| !["&&", "||", "==", "!=", "<", ">"].iter().any(|op| rest.contains(op)); + let suffix = |s: &str| expr.strip_suffix(s).is_some_and(plain); + if negated { + return suffix(".is_empty()"); + } + suffix(".is_ok()") || suffix(".is_some()") || suffix(".len()>0") || suffix(".len()!=0") || suffix(".len()>=1") +} + +/// `expr` without the balanced parentheses around all of it (`((a.is_ok()))` gives `a.is_ok()`). +fn unparenthesized(mut expr: &str) -> &str { + while expr.starts_with('(') && matching(expr.as_bytes(), 0) == Some(expr.len() - 1) { + expr = &expr[1..expr.len() - 1]; + } + expr +} + +fn only_weak(v: &View) -> Option { + let all_weak = v.asserts.iter().all(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && is_weak(&v.first_arg(a))); + // Failure messages run only after an assertion has failed, so a check there does not count. + let body = v.body_without_messages(); + let other = contains(&body, b"panic!") || contains(&body, b".unwrap_err()") || contains(&body, b".expect_err("); + if v.asserts.is_empty() || !all_weak || other || v.delegates || v.should_panic { + return None; + } + Some(v.whole(Rule::OnlyWeak, format!("its {} assertion(s) only check is_ok/is_some/non-empty", v.asserts.len()))) +} + +/// Methods that return the next value of something each time (`assert_ne!(it.next(), it.next())` +/// compares two items). +const ADVANCING: &[&str] = + &["next", "next_back", "pop", "pop_front", "pop_back", "recv", "try_recv", "read_line", "take", "tick", "step", "advance", "now", "elapsed"]; + +fn self_compare(v: &View) -> Vec { + v.asserts + .iter() + .filter(|a| a.name.ends_with("_eq") || a.name.ends_with("_ne")) + .filter_map(|a| { + let right = *a.args.get(1)?; + let (l, r) = (v.file.src_norm(*a.args.first()?), v.file.src_norm(right)); + let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); + let calls_with_args = l.replace("()", "").contains(['(', '!']); + let advances = ADVANCING.iter().any(|m| l.contains(&format!(".{m}()"))); + (l == r && !l.is_empty() && !calls_with_args && !advances).then(|| { + let mut h = v.hit(a.at, Rule::SelfCompare, format!("{}! compares `{l}` with itself", a.name)); + let end = right.0 + v.file.m[right.0..right.1].trim_ascii_end().len(); + h.last = v.file.lines.of(end.saturating_sub(1)); + h + }) + }) + .collect() +} + +fn exit_status_only(v: &View) -> Option { + let mut body = norm(&v.body_without_messages()).into_bytes(); + let runs = contains(&body, b"Command::new") || contains(&body, b".output()") || contains(&body, b".status()"); + strip_stream_configuration(&mut body); + let reads = + ["stdout", "stderr", "fs::read", "read_to_string", "from_slice", "from_str", "contains("].iter().any(|w| contains(&body, w.as_bytes())); + let status_only = |a: &MacroCall| { + a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { + let c = norm(&v.file.m[from..to]); + c.contains(".success()") || c.contains(".code()") + }) + }; + if !runs || reads || v.asserts.is_empty() || !v.asserts.iter().all(status_only) || v.delegates { + return None; + } + Some(v.whole(Rule::ExitStatusOnly, "runs a process and checks only its exit status".into())) +} + +/// Blanks the names of builder calls that set a process's streams (`.stdout(…)`, whatever the +/// argument) in whitespace-free text. Reads of the output fields (`out.stdout`) stay. +fn strip_stream_configuration(body: &mut [u8]) { + for stream in ["stdout", "stderr", "stdin"] { + for at in words(body, stream.as_bytes(), 0, body.len()) { + if body[..at].ends_with(b".") && body[at + stream.len()..].starts_with(b"(") { + blank(body, at, at + stream.len()); + } + } + } +} + +fn no_assertion(v: &View) -> Option { + if v.checks || v.delegates || v.should_panic { + return None; + } + Some(v.whole(Rule::NoAssertion, "no assertion and no asserting helper".into())) +} + +/// Guards that mark a skip for a missing resource or another platform, or a test that runs itself +/// in a child process, matched case-sensitively on the guard without whitespace. +const SKIP_GUARDS: &[&str] = &[ + "in_own_process", + "OWN_PROCESS", + "_TEST_CHILD", + "current_exe()", + "skip_without_craft_fonts", + "CRAFT_FONTS", + "japanese_fonts", + "craft_fonts", + "env::var", + "cfg!(", + "target_os", + "geteuid", + "Command::new", + "File::open", + "fs::read", + "read_dir(", + ".exists()", + "which(", +]; + +/// The same, matched without regard to case. +const SKIP_GUARDS_ANY_CASE: &[&str] = &[ + "installed_family", + "kufi", + "library/fonts", + "default_font(", + "arabic_face", + "arabic_test_face", + "devanagari_test_face", + "joiner_test_faces", + "mark_text(", + "arabic_style", + "has_family", + "variable_font", + "fontdb", + ".face(", + "covers(", + "thai", + "cjk", + "corpus", + "suite_dir", + "json2_file", + "read_fixture", + "samples(", + "pinned(", + "platform()", + "is_mac", + "/system/library", +]; + +fn early_returns(v: &View) -> Vec { + let (m, t) = (&v.file.m, v.t); + words(m, b"return", t.open, t.close) + .into_iter() + .filter_map(|at| { + let end = bare_return_end(m, at + "return".len())?; + let rest_empty = m[end..t.close].iter().all(|c| c.is_ascii_whitespace() || matches!(c, b';' | b'}')); + if rest_empty || nested(m, t.open, at) || skip_guard(v.file, t.open, at, end) { + return None; + } + Some(v.hit(at, Rule::EarlyReturn, "returns early on a value from the code under test".into())) + }) + .collect() +} + +/// The end of a bare `return` (`return;`, `return }`, `return Ok(());`) whose keyword ends at `i`. +fn bare_return_end(m: &[u8], i: usize) -> Option { + let mut j = skip_ws(m, i); + if m[j..].starts_with(b"Ok") { + j += 2; + for c in *b"(())" { + j = skip_ws(m, j); + if m.get(j) != Some(&c) { + return None; + } + j += 1; + } + j = skip_ws(m, j); + } + match m.get(j)? { + b';' => Some(j + 1), + b'}' | b',' => Some(j), + _ => None, + } +} + +/// Whether `pos` is inside a closure or a nested function in the body opened at `open`. +fn nested(m: &[u8], open: usize, pos: usize) -> bool { + let mut stack: Vec = vec![]; + for i in open..pos { + match m[i] { + b'{' => stack.push(i > open && opens_closure_or_fn(m, open, i)), + b'}' => { + stack.pop(); + } + _ => {} + } + } + stack.contains(&true) +} + +fn opens_closure_or_fn(m: &[u8], open: usize, brace: usize) -> bool { + let from = brace.saturating_sub(160).max(open + 1); + let head = &m[from..brace]; + let start = head.iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let head = String::from_utf8_lossy(&head[start..]).into_owned(); + let head = head.trim_end(); + let closure = head.ends_with('|') || head.rfind("->").is_some_and(|p| head[..p].trim_end().ends_with('|')); + let block = head.strip_suffix("move").unwrap_or(head).trim_end(); + let future = block.ends_with("async") && !block[..block.len() - "async".len()].ends_with(|c: char| c.is_ascii_alphanumeric() || c == '_'); + closure || future || !words(head.as_bytes(), b"fn", 0, head.len()).is_empty() +} + +/// Whether the return at `at..end` is not a silent skip on a value: the block it ends asserts +/// first; a comment or a printed note from the start of its statement to the end of its line says +/// why it returns; or its guard skips for a resource, a platform or a child process. +fn skip_guard(file: &File, open: usize, at: usize, end: usize) -> bool { + let m = &file.m; + let block = m[open..at].iter().rposition(|&c| c == b'{').map_or(open, |p| p + open); + let stmt = m[open..block].iter().rposition(|&c| c == b';' || c == b'}').map_or(open, |p| p + open); + let line_end = find(m, b"\n", end).unwrap_or(m.len()); + let asserted = macro_calls(m, block, at).iter().any(|c| is_assert_macro(&c.name)); + let printed = macro_calls(m, stmt, at).iter().any(|c| c.name.ends_with("print") || c.name.ends_with("println")); + let commented = (stmt..line_end).any(|i| file.src[i..].starts_with(b"//") && m[i] == b' '); + if asserted || printed || commented { + return true; + } + let guard = norm(&file.src[stmt..end]); + let lower = guard.to_ascii_lowercase(); + let wide = &file.src[stmt.saturating_sub(250).max(open)..end]; + SKIP_GUARDS.iter().any(|g| guard.contains(g)) + || SKIP_GUARDS_ANY_CASE.iter().any(|g| lower.contains(g)) + || (lower.contains("fs::write(") && lower.contains(".is_err()")) + || ["in_own_process", "OWN_PROCESS", "_TEST_CHILD", "current_exe()"].iter().any(|g| contains(wide, g.as_bytes())) + || !words(wide, b"CHILD", 0, wide.len()).is_empty() +} + +fn env_gates(v: &View, ctx: &Ctx) -> Vec { + let (m, src, t) = (&v.file.m, v.file.src, v.t); + let mut out = vec![]; + for at in words(m, b"var", t.open, t.close).into_iter().chain(words(m, b"var_os", t.open, t.close)) { + if !m[..at].ends_with(b"env::") { + continue; + } + let Some((name, end)) = env_name(m, src, at) else { continue }; + if ctx.ci_env.contains(&name) || set_by_system(&name) { + continue; + } + if !set_in_file(m, src, &name) { + // The hit sits on `var`; its span reaches the name, which can be on a later line. + let mut hit = v.hit(at, Rule::EnvGateUnset, format!("reads {name}, which no CI leg sets")); + hit.last = v.file.lines.of(end); + out.push(hit); + } + } + out +} + +/// Whether the file's code (masked `m`, outside comments and literals) sets `name`: `.env("NAME", …)`, +/// `set_var("NAME", …)`, or a constant `= "NAME";`. The name is read from the source. +fn set_in_file(m: &[u8], src: &[u8], name: &str) -> bool { + let call = |word: &[u8], method: bool| { + words(m, word, 0, m.len()).into_iter().any(|at| { + let dot = m[..at].trim_ascii_end().ends_with(b"."); + (dot || !method) && env_name(m, src, at).is_some_and(|(n, _)| n == name) + }) + }; + let constant = find_all(src, name.as_bytes()).any(|p| { + let (open, close) = (p.wrapping_sub(1), p + name.len()); + let (Some(b'"'), Some(b'"')) = (m.get(open), m.get(close)) else { return false }; + m[..open].trim_ascii_end().ends_with(b"=") && m.get(skip_ws(m, close + 1)) == Some(&b';') + }); + call(b"env", true) || call(b"set_var", false) || constant +} + +/// Every start of `needle` in `hay`. +fn find_all<'a>(hay: &'a [u8], needle: &'a [u8]) -> impl Iterator + 'a { + let mut from = 0; + std::iter::from_fn(move || { + let at = find(hay, needle, from)?; + from = at + 1; + Some(at) + }) +} + +/// The literal name in `env::var("NAME")` whose `var` is at `at`, and the offset of its closing +/// quote. +fn env_name(m: &[u8], src: &[u8], at: usize) -> Option<(String, usize)> { + let open = skip_ws(m, at + m[at..].iter().take_while(|&&c| is_ident(c)).count()); + if m.get(open) != Some(&b'(') { + return None; + } + let quote = skip_ws(m, open + 1); + if m.get(quote) != Some(&b'"') { + return None; + } + let end = string_end(src, quote + 1).saturating_sub(1); + let name = std::str::from_utf8(&src[quote + 1..end]).ok()?; + (!name.is_empty() && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')).then(|| (name.to_owned(), end)) +} + +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; + } + let j = skip_ws(m, at + "ignore".len()); + let reason = match m.get(j) { + Some(b'=') => { + let q = skip_ws(m, j + 1); + ignore_reason(&file.src[q..]).is_some_and(|body| body.iter().any(|c| !c.is_ascii_whitespace())) + } + _ => false, + }; + 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)); + out.push(hit); + } + } + out +} + +/// The body of an ordinary or raw string literal used as an ignore reason. +fn ignore_reason(src: &[u8]) -> Option<&[u8]> { + if src.first() == Some(&b'"') { + return src.get(1..string_end(src, 1).saturating_sub(1)); + } + let raw = src.strip_prefix(b"r")?; + let hashes = raw.iter().take_while(|&&c| c == b'#').count(); + if raw.get(hashes) != Some(&b'"') { + return None; + } + let body = hashes + 2; + let close: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(src, &close, body)?; + src.get(body..end) +} + +fn sleep_hits(file: &File) -> Vec { + let m = &file.m; + // A bare `sleep(…)` counts only where a `use` brings in `thread::sleep`. + let imported = words(m, b"use", 0, m.len()).into_iter().any(|u| { + let item = norm(&m[u..statement_end(m, u)]); + item.contains("thread::sleep") + || item.split_once("thread::{").is_some_and(|(_, list)| !words(list.as_bytes(), b"sleep", 0, list.len()).is_empty()) + }); + words(m, b"sleep", 0, m.len()) + .into_iter() + .filter(|&at| { + if !in_regions(&file.regions, at) || m.get(skip_ws(m, at + "sleep".len())) != Some(&b'(') { + return false; + } + let before = m[..at].trim_ascii_end(); + let path = before.strip_suffix(b"::").map(<[u8]>::trim_ascii_end); + match path { + Some(p) => p.ends_with(b"thread") && !p.ends_with(b"_thread"), + None => imported && !before.ends_with(b".") && !before.ends_with(b"fn"), + } + }) + .map(|at| file.hit(at, Rule::Sleep, file.test_at(at), "sleeps in test code".into())) + .collect() +} + +fn reads_source_hits(file: &File) -> Vec { + if SOURCE_AUDITS.contains(&file.path) { + return vec![]; + } + let m = &file.m; + let mut out = vec![]; + for (word, note) in [(&b"include_str"[..], "includes a .rs file as text"), (&b"ends_with"[..], "keeps files ending in .rs")] { + for at in words(m, word, 0, m.len()).into_iter().filter(|&at| in_regions(&file.regions, at)) { + let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); + let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; + let arg = norm(&file.src[open + 1..close]); + // An ordinary or raw string literal: `".rs"`, `r".rs"`, `r#"…/lib.rs"#`. + let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); + let literal = raw.unwrap_or(&arg); + let rs = if word == b"ends_with" { literal == "\".rs\"" } else { arg.trim_end_matches('#').ends_with(".rs\"") }; + if rs { + out.push(file.hit(at, Rule::ReadsSource, file.test_at(at), note.into())); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ctx() -> Ctx { + Ctx { helpers: HashMap::new(), ci_env: ["SET_IN_CI".to_owned()].into_iter().collect() } + } + + /// The rule ids of `src`'s hits, as `(line, rule)`. + fn hits(src: &str) -> Vec<(usize, &'static str)> { + hits_in("crates/x/src/tests.rs", src, &ctx()) + } + + fn hits_in(path: &str, src: &str, ctx: &Ctx) -> Vec<(usize, &'static str)> { + lint_file(path, src, ctx).into_iter().map(|h| (h.line, h.rule.id())).collect() + } + + #[test] + fn all_needs_a_non_empty_guard() { + let bad = "#[test]\nfn t() {\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(bad), [(4, "all-unguarded")]); + let good = "#[test]\nfn t() {\n let xs = f();\n assert_eq!(xs.len(), 3);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(good), []); + let inner = "#[test]\nfn t() {\n assert!(rows().iter().all(|r| r.len() == 3));\n}\n"; + assert_eq!(hits(inner), [(3, "all-unguarded")], "a length inside the predicate is about each item"); + let none = "#[test]\nfn t() {\n assert!(warnings().iter().all(|w| !w.contains(\"lost\")), \"no warning\");\n}\n"; + assert_eq!(hits(none), [], "all(|w| !…) says that no item matches"); + let other = "#[test]\nfn t() {\n assert!(listed().iter().all(|e| e[\"id\"] != id));\n assert!([0, 4, 20].iter().all(|&i| glow[i].a() == 0));\n}\n"; + assert_eq!(hits(other), [], "one != comparison, and an array literal"); + let indexed = "#[test]\nfn t() {\n assert!(rows()[2].iter().all(|r| r.ok && r.n != 0));\n assert!(f().iter().all(|x| x.0 != 1 && x.1 != 2));\n}\n"; + assert_eq!(hits(indexed), [(3, "all-unguarded")]); + let mixed = "#[test]\nfn t() {\n assert!(f().iter().all(|x| x.0 != 1 && x.1 > 2));\n}\n"; + assert_eq!(hits(mixed), [(3, "all-unguarded")]); + } + + #[test] + fn all_equality_guards_match_each_receiver() { + for assertion in ["assert_eq", "debug_assert_eq", "prop_assert_eq"] { + for operand in ["xs", "&xs", "xs.as_slice()", "&xs.as_slice()", "xs[..]", "&xs[..]"] { + for literal in ["[1]", "[1, 2,]", "[1; 2]", "vec![1, 2]", "vec![1; 2]", "[\"[;]\", name]"] { + for (left, right) in [(operand, literal), (literal, operand)] { + let src = format!( + "#[test]\nfn t() {{\n {assertion}!({left}, {right}, \"items\");\n assert!(xs.iter().all(|x| valid(x)));\n assert!(ys.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{assertion}!({left}, {right})"); + let combined = src.replace("valid(x)));\n assert!(ys", "valid(x)) && ys"); + assert_eq!(hits(&combined), [(4, "all-unguarded")], "another receiver in the same condition"); + } + } + } + } + } + + #[test] + fn all_equality_guards_require_non_empty_literals() { + for expected in ["[]", "[1; 0]", "vec![]", "vec![1; 0]", "expected", "items()", "[1].map(f)", "vec![1].clone()"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!(xs, {expected});\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{expected}"); + } + for operand in ["ys", "xs_other", "other.xs", "other::xs", "xs()", "xs.filter(f)", "xs.iter().filter(f).collect()", "xs[1..]", "&&xs"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({operand}, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{operand}"); + } + } + + #[test] + fn all_equality_guards_require_earlier_compared_operands_in_the_test() { + for assertion in ["assert_ne", "debug_assert_ne", "prop_assert_ne"] { + let src = format!("#[test]\nfn t() {{\n {assertion}!(xs, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{assertion}"); + } + let later = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n assert_eq!(xs, [1]);\n}\n"; + assert_eq!(hits(later), [(3, "all-unguarded")]); + let outside = "fn helper() { assert_eq!(xs, [1]); }\n#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(outside), [(4, "all-unguarded")]); + let message = "#[test]\nfn t() {\n assert_eq!(a, b, \"items {:?} {:?}\", xs, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(message), [(4, "all-unguarded")]); + } + + #[test] + fn all_skips_conjunctions_of_not_equal_comparisons() { + for predicate in [ + "|(id, _)| id != \"action.batch\" && id != \"flattener.preview\"", + "|x| x.0 != 1 && x.1 != 2", + "|x| x != 1 && x != 2 && x != 3", + "|x| (x != 1) && ((x != 2) && x != 3)", + "|x| value(x) != expected(1, 2) && *x != 3", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(names.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [], "{predicate}"); + let mixed = src.replace("));\n", ") && ys.iter().all(|y| valid(y)));\n"); + assert_eq!(hits(&mixed), [(3, "all-unguarded")], "another positive predicate beside {predicate}"); + } + } + + #[test] + fn all_reports_conjunctions_with_other_predicates() { + for predicate in [ + "|x| x != 1 && x == 2", + "|x| x != 1 && x < 2", + "|x| x.0 != 1 && x.1 > 2", + "|x| x != 1 && valid(x)", + "|x| valid(x) && x != 1", + "|x| x != 1 || x != 2", + "|x| x != 1 && x != 2 || x != 3", + "|x| x != 1 && (x != 2 || x != 3)", + "|x| (x != 1 && x > 2) && x != 3", + "|x| valid(x != 1) && x != 2", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(names.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{predicate}"); + } + } + + #[test] + fn all_skips_only_whole_negations_and_not_equal_conjunctions() { + for predicate in [ + "|x| !x.contains(\"lost\")", + "|x| !blocked!(x)", + "|x| !(blocked(x) && invalid(x))", + "|x| !a(x) && !b(x)", + "|x| !a(x) && x != 1", + "|x| x != 1 && (!a(x) && !(b(x)))", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(xs.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [], "{predicate}"); + } + for predicate in [ + "|x| !blocked(x) && valid(x)", + "|x| valid(x) && !blocked(x)", + "|x| !a(x) || b(x)", + "|x| !a(x) == b(x)", + "|x| (!a(x) == b(x)) && x != 1", + "|x| !a(x) && (!b(x) || c(x))", + "|x| !a(x) ^ b(x)", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(xs.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{predicate}"); + } + } + + #[test] + fn all_skips_locally_bound_non_empty_arrays() { + for binding in [ + "let xs = [1, 2];", + "let mut xs = [1, 2];", + "let xs: [u8; 2] = [1, 2];", + "let mut xs: [u8; 2] = [1, 2];", + "let xs = [1; 2];", + "let xs = [[1, 2], [3, 4]];", + "let xs = [\"[\", \";\", \"bad ] brackets [\"].map(|s| s.trim());", + "let xs = [1, 2].map(|x| { let pair = [x, x]; pair });", + "let xs /* items */ : [u8; 2] = [1, 2] . map (|x| x + 1);", + ] { + for method in ["iter", "into_iter"] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding} through {method}"); + let mixed = src.replace("valid(x)))", "valid(x)) && ys.iter().all(|y| valid(y)))"); + assert_eq!(hits(&mixed), [(4, "all-unguarded")], "another collection beside {binding}"); + } + } + } + + #[test] + fn all_reports_empty_arrays_and_other_initializers() { + for value in [ + "[]", + "[1; 0]", + "[1; 0].map(|x| x + 1)", + "vec![]", + "vec![1; 0]", + "vec![1; n]", + "items()", + "items().collect()", + "items().collect::>()", + "(0..0).collect::>()", + "(3..1).collect::>()", + "(0..n).collect::>()", + "(0..).take(3).collect::>()", + "[1, 2].iter().filter(|x| keep(x)).collect::>()", + "[1, 2].into_iter().zip(ys).collect::>()", + "[None::].into_iter().collect::>>()", + "[Err::(error())].into_iter().collect::, E>>()", + "[1, 2].into_iter().collect()", + "[1, 2].into_iter().collect::()", + "[1, 2].into_iter().collect::>()", + ] { + for binding in [format!("let xs = {value};"), format!("let mut xs = {value};"), format!("let xs: [u8; 0] = {value};")] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{binding}"); + } + } + } + + #[test] + fn all_array_bindings_match_only_plain_preceding_local_names() { + for (binding, receiver) in [ + ("let xs_other = [1, 2];", "xs"), + ("let other_xs = [1, 2];", "xs"), + ("let (xs, ys) = ([1, 2], items());", "xs"), + ("let xs = [1, 2]; let xs = items();", "xs"), + ("let xs = [1, 2];", "other.xs"), + ("let xs = [1, 2];", "other::xs"), + ("let xs = [1, 2];", "xs()"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!({receiver}.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{binding} with {receiver}"); + } + let later = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n let xs = [1, 2];\n}\n"; + assert_eq!(hits(later), [(3, "all-unguarded")], "a later binding does not initialize the receiver"); + let outside = "fn helper() { let xs = [1, 2]; }\n#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(outside), [(4, "all-unguarded")], "a binding outside the test does not count"); + } + + #[test] + fn all_direct_array_literals_must_be_non_empty() { + for method in ["iter", "into_iter"] { + for array in ["[]", "[1; 0]", "[items(); 0]", "[1; 0usize]"] { + let src = format!("#[test]\nfn t() {{\n assert!({array}.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{array} through {method}"); + } + for array in ["[1]", "[1, 2]", "[1; 2]", "[[1; 0]]", "[\"[;]\"]"] { + let src = format!("#[test]\nfn t() {{\n assert!({array}.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{array} through {method}"); + } + } + } + + #[test] + fn all_skips_mapped_arrays_of_named_rectangles() { + for (name, labels, message) in [ + ("chips", "[\"Color (, or Shift+,)\", \"Gradient (. or Shift+.)\", \"None (/)\"]", "one line"), + ("modes", "[\"Draw Normal (Shift+D)\", \"Draw Behind (Shift+D)\", \"Draw Inside (Shift+D)\"]", "side by side"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let {name} = {labels}.map(|label| named_rect(&nodes, label));\n assert!({name}.iter().all(|r| (r.top() - {name}[0].top()).abs() < 0.5), \"{message}: {{{name}:?}}\");\n}}\n" + ); + assert_eq!(hits(&src), [], "{name}"); + let empty = src.replace(labels, "[]"); + assert_eq!(hits(&empty), [(4, "all-unguarded")], "an empty {name} still passes vacuously"); + } + } + + #[test] + fn all_skips_bindings_with_sized_initializers() { + let consts = "const N: usize = 3;\nconst NONE: usize = 0;\n"; + for binding in [ + "let xs = vec![1, 2];", + "let mut xs = vec![[1, 2]; 2];", + "let xs: Vec<_> = [1, 2].into_iter().collect();", + "let xs = [1, 2].map(|x| x + 1).map(|x| x + 1);", + "let xs: Vec = [1, 2].iter().copied().rev().collect();", + "let xs: Vec = (0..40u8).map(|n| px(n)).collect();", + "let xs = (1..=3).collect::>();", + "let xs = (-2..1).step_by(2).collect::>();", + "let xs: Vec<_> = (0..N).collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect::>().into_iter().collect();", + "let xs = [0.0; N];", + "let xs: [u8; 3] = items();", + "let xs: [u8; N] = items();", + ] { + let src = format!("{consts}#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(7, "all-unguarded")], "{binding} then cleared"); + } + for binding in [ + "let xs = (0..NONE).collect::>();", + "let xs = [0.0; NONE];", + "let xs: [u8; NONE] = [1];", + "let xs = (0..M).collect::>();", + "let xs = [None::].into_iter().collect::>>();", + "let xs = [Err::(error())].into_iter().collect::, E>>();", + "let xs: Option> = [1].into_iter().collect();", + "let xs: Result, E> = [1].into_iter().collect();", + "let xs = [1, 2].into_iter().collect();", + "let xs: Items = [1, 2].into_iter().collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect().clone();", + "let xs: Vec<_> = [1, 2].into_iter().collect().into_iter().collect();", + "let xs: Vec<_> = [None::].into_iter().collect::>>().into_iter().collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect::();", + ] { + let src = format!("{consts}#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(6, "all-unguarded")], "{binding}"); + } + for later in [ + "xs.retain(|x| keep(x));", + "xs = items();", + "take(&mut xs);", + "xs.truncate(0);", + "xs.pop();", + "xs.resize(0, 0);", + "xs.resize_with(0, f);", + "xs.pop_front();", + "xs.pop_back();", + "xs.unknown_method_that_may_shrink();", + "xs . unknown::();", + ] { + let src = format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n {later}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{later}"); + } + for op in ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="] { + let src = + format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n xs {op} other;\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{op}"); + } + for later in [ + "xs[0] = 5; use_it(&xs);", + "xs[1] = 5; use_it(&xs);", + "use_it(&xs);", + "use_it(xs);", + "use_it(xs == other);", + "match other { xs => use_it(xs), _ => () };", + "xs.push(3); xs.push_back(4); xs.push_front(5); xs.insert(0, 6); xs.extend(other);", + "xs.sort(); xs.sort_by(f); xs.sort_by_key(f); xs.sort_unstable(); xs.reverse();", + "use_it(xs.iter()); use_it(xs.iter_mut()); use_it(xs.into_iter());", + "use_it(xs.len()); use_it(xs.is_empty()); use_it(xs.contains(&1));", + "use_it(xs.get(0)); use_it(xs.get_mut(0)); use_it(xs.first()); use_it(xs.last());", + "use_it(xs.first_mut()); use_it(xs.last_mut()); use_it(xs.as_slice()); use_it(xs.as_ref());", + "use_it(xs.clone()); use_it(xs.to_vec()); use_it(xs.windows(2)); use_it(xs.chunks(2));", + "use_it(xs.binary_search(&1)); use_it(xs.starts_with(&[1])); use_it(xs.ends_with(&[2]));", + "use_it(xs.map(f)); use_it(xs.concat()); use_it(xs.join(sep)); use_it(xs.keys()); use_it(xs.values());", + ] { + let src = format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n {later}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{later}"); + } + } + + #[test] + fn all_collects_require_known_collection_targets() { + for target in [ + "Vec<_>", + "std::vec::Vec<_>", + "VecDeque<_>", + "std::collections::VecDeque<_>", + "HashSet<_>", + "std::collections::HashSet<_>", + "BTreeSet<_>", + "std::collections::BTreeSet<_>", + "HashMap<_, _>", + "std::collections::HashMap<_, _>", + "BTreeMap<_, _>", + "std::collections::BTreeMap<_, _>", + "BinaryHeap<_>", + "std::collections::BinaryHeap<_>", + "LinkedList<_>", + "std::collections::LinkedList<_>", + "String", + "std::string::String", + "Box<[_]>", + "std::boxed::Box<[_]>", + ] { + let source = if target.contains("Map") { "[(1, 2)]" } else { "['a', 'b']" }; + for binding in [ + format!("let xs = {source}.into_iter().collect::<{target}>();"), + format!("let xs: {target} = {source}.into_iter().collect();"), + format!("let xs = {source}.into_iter().collect::<{target}>().into_iter().collect::>();"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + } + } + } + + #[test] + fn all_skips_collections_every_pass_of_a_sized_loop_fills() { + for (source, fill) in [ + ("[1, 2, 3]", "xs.push(i);"), + ("0..3", "xs.push(i);"), + ("[[0, 1], [1, 0]]", "let s = Fill { a: 1 }.span(i);\n xs.push(s);"), + ("[1, 2].iter().enumerate()", "for j in items() { use_it(j); }\n xs.insert(i);"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let mut xs = vec![];\n for i in {source} {{\n {fill}\n }}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [], "{source}: {fill}"); + let after = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&after), [(line + 1, "all-unguarded")], "{source} then cleared"); + } + for (source, fill) in [ + ("items()", "xs.push(i);"), + ("0..0", "xs.push(i);"), + ("0..n", "xs.push(i);"), + ("[1, 2]", "if keep(i) { xs.push(i); }"), + ("[1, 2]", "if !keep(i) { continue; }\n xs.push(i);"), + ("[1, 2]", "let v = get(i)?;\n xs.push(v);"), + ("[1, 2]", "ys.iter().for_each(|y| xs.push(*y));"), + ("[1, 2]", "ys.push(i);"), + ("[1, 2]", "let mut xs = vec![];\n xs.push(i);"), + ("[1, 2].iter().filter(|x| keep(x))", "xs.push(i);"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let mut xs = vec![];\n for i in {source} {{\n {fill}\n }}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [(line, "all-unguarded")], "{source}: {fill}"); + } + let nested = "#[test]\nfn t() {\n let mut xs = vec![];\n if ready() {\n for i in [1, 2] {\n xs.push(i);\n }\n }\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(nested), [(9, "all-unguarded")], "a loop that may not run"); + } + + #[test] + fn all_skips_fields_the_file_declares_as_arrays() { + let test = "#[test]\nfn t() {\n let c = parse();\n assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v)));\n}\n"; + for decl in [ + "struct C { rgb: [f32; 3] }\n", + "const N: usize = 3;\nstruct C { pub rgb: [f32; N], alpha: Option }\n", + "struct C { rgb: [f32; 3] }\nfn c() -> C { C { rgb: rgb_of(\"x\"), alpha: 1 } }\n", + ] { + let src = format!("{decl}{test}"); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [], "{decl}"); + let other = format!("{decl}struct D {{ rgb: Vec }}\n{test}"); + assert_eq!(hits(&other), [(line + 1, "all-unguarded")], "another struct's rgb can be empty"); + } + for decl in + ["struct C { rgb: [f32; 0] }\n", "struct C { rgb: &'static [f32] }\n", "struct C { rgb: [f32; LEN] }\n", "struct C { other: [f32; 3] }\n"] + { + let src = format!("{decl}{test}"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{decl}"); + } + for other in ["std::vec::Vec", "Pixels", "u8", "(f32, f32)", "T"] { + let src = format!("struct C {{ rgb: [f32; 3] }}\nstruct D {{ rgb: {other} }}\n{test}"); + assert_eq!(hits(&src), [(6, "all-unguarded")], "another struct's rgb is {other}"); + } + let local = "struct C { rgb: [f32; 3] }\n#[test]\nfn t() {\n let rgb = parse();\n assert!(rgb.iter().all(|v| valid(v)));\n}\n"; + assert_eq!(hits(local), [(5, "all-unguarded")], "a local name is not the field"); + } + + #[test] + fn all_equality_guards_follow_methods_that_keep_items() { + for operand in [ + "xs.clone()", + "xs.iter().map(|l| l.0).collect()", + "xs.iter().copied().collect::>().into_iter().collect()", + "xs.iter().map(|l| l.0).collect::>()", + "&xs.iter().copied().rev().collect::>()", + ] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({operand}, vec![0, 7]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{operand}"); + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(5, "all-unguarded")], "{operand} then cleared"); + } + for (binding, compared) in [ + ("let ids: Vec<&str> = xs.iter().map(|l| l.id()).collect();", "assert_eq!(ids, [\"a\", \"b\"]);"), + ("let ids = xs.iter().cloned().collect::>();", "assert_eq!([\"a\"], ids);"), + ("let ids = xs.iter().copied().collect::>();", "assert_eq!(ids, [1]);"), + ("let ids: Vec<_> = xs.iter().copied().collect::>().into_iter().collect();", "assert_eq!(ids, [1]);"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n {compared}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + let filtered = src.replace(binding, &binding.replace(".iter()", ".iter().filter(|x| keep(x))")); + assert_eq!(hits(&filtered), [(5, "all-unguarded")], "{binding} through a filter"); + let rebound = src.replace(&format!(" {compared}\n"), &format!(" let ids = other();\n {compared}\n")); + assert_eq!(hits(&rebound), [(6, "all-unguarded")], "{binding} then bound again"); + for change in ["ids = vec![1];", "ids.clear();", "reset(&mut ids);", "ids.push(1);"] { + let reassigned = + src.replace("let ids", "let mut ids").replace(&format!(" {compared}\n"), &format!(" {change}\n {compared}\n")); + assert_eq!(hits(&reassigned), [(6, "all-unguarded")], "{binding} then {change}"); + } + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(6, "all-unguarded")], "{binding} then the source cleared"); + } + } + + #[test] + fn all_equality_guards_stop_at_other_collect_targets() { + for operand in [ + "xs.iter().copied().collect().into_iter().collect::>()", + "xs.iter().copied().collect().into_iter().collect()", + "xs.iter().copied().collect().clone()", + ] { + for compared in [format!("{operand}, [vec![]]"), format!("[vec![]], {operand}")] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({compared});\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{compared}"); + } + } + for binding in [ + "let ids: Option> = xs.iter().copied().collect();", + "let ids: Result, E> = xs.iter().copied().collect();", + "let ids: Items = xs.iter().copied().collect();", + "let ids = xs.iter().copied().collect();", + "let ids: Vec<_> = xs.iter().copied().collect().into_iter().collect();", + "let ids: Vec<_> = xs.iter().copied().collect().into_iter().collect::>();", + "let ids: Vec<_> = xs.iter().copied().collect().clone();", + ] { + let src = format!( + "#[test]\nfn t() {{\n {binding}\n assert_eq!(ids.into_iter().collect::>(), [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{binding}"); + } + for target in ["Option>", "Result, E>", "Items"] { + let operand = format!("xs.iter().copied().collect::<{target}>().iter().collect::>()"); + let direct = format!("#[test]\nfn t() {{\n assert_eq!({operand}, [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&direct), [(4, "all-unguarded")], "{target} compared directly"); + let derived = format!( + "#[test]\nfn t() {{\n let ids = {operand};\n assert_eq!(ids, [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&derived), [(5, "all-unguarded")], "{target} through a local"); + } + } + + #[test] + fn all_skips_const_and_static_arrays_of_the_file() { + let test = "#[test]\nfn t() {\n assert!(NAMES.iter().all(|n| valid(n)));\n}\n"; + for decl in [ + "const NAMES: [&str; 2] = [\"a\", \"b\"];\n", + "static NAMES: [u8; N] = [0; N];\nconst N: usize = 4;\n", + "pub(crate) static mut NAMES: [u8; 1] = [0];\n", + ] { + let src = format!("{decl}{test}"); + assert_eq!(hits(&src), [], "{decl}"); + } + for decl in ["const NAMES: [&str; 0] = [];\n", "const NAMES: &[&str] = &[\"a\"];\n", "fn my_const() {}\nlet NAMES: [u8; 2] = f();\n", ""] { + let src = format!("{decl}{test}"); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [(line, "all-unguarded")], "{decl}"); + } + let shadowed = "const NAMES: [&str; 2] = [\"a\", \"b\"];\n#[test]\nfn t() {\n let NAMES = items();\n assert!(NAMES.iter().all(|n| valid(n)));\n}\n"; + assert_eq!(hits(shadowed), [(5, "all-unguarded")], "a local of the same name"); + for (other_type, other_value, found) in [("[u8; 0]", "[]", true), ("&[u8]", "&[]", true), ("[u8; 3]", "[0; 3]", false)] { + for (first_type, first_value, second_type, second_value) in + [("[u8; 2]", "[0; 2]", other_type, other_value), (other_type, other_value, "[u8; 2]", "[0; 2]")] + { + let src = format!( + "mod a {{ const CASES: {first_type} = {first_value}; }}\nmod b {{\nconst CASES: {second_type} = {second_value};\n#[test]\nfn t() {{\n assert!(CASES.iter().all(|n| valid(n)));\n}}\n}}\n" + ); + let want: &[(usize, &str)] = if found { &[(6, "all-unguarded")] } else { &[] }; + assert_eq!(hits(&src), want, "{first_type} and {second_type}"); + } + } + } + + #[test] + fn all_windows_need_as_many_items_as_their_size() { + for (array, method, found) in [ + ("[a, b, c, d]", "windows(2)", false), + ("[a, b]", "windows(2)", false), + ("[a]", "windows(2)", true), + ("[a, b]", "windows(k)", true), + ("[a]", "chunks(3)", false), + ("[a, b]", "chunks_exact(3)", true), + ("[a, b, c]", "chunks_exact(3)", false), + ] { + let src = + format!("#[test]\nfn t() {{\n let xs = {array}.map(|s| node(s));\n assert!(xs.{method}.all(|w| w[0].y == w[1].y));\n}}\n"); + let want: &[(usize, &str)] = if found { &[(4, "all-unguarded")] } else { &[] }; + assert_eq!(hits(&src), want, "{array}.{method}"); + } + } + + #[test] + fn all_guards_accept_asserted_locals_that_count() { + let src = "#[test]\nfn t() {\n let row = cards.iter().filter(|c| first_row(c)).count();\n assert_eq!(row, 4, \"four cards\");\n assert!(cards.iter().all(|c| c.x < 10));\n}\n"; + assert_eq!(hits(src), []); + let summed = src.replace(".count()", ".map(|c| c.w).sum::()"); + assert_eq!(hits(&summed), [(5, "all-unguarded")], "a sum does not count items"); + let message = src.replace("assert_eq!(row, 4, \"four cards\")", "assert_eq!(a, b, \"{}\", row)"); + assert_eq!(hits(&message), [(5, "all-unguarded")], "a count in a failure message checks nothing"); + let unused = src.replace(" assert_eq!(row, 4, \"four cards\");\n", ""); + assert_eq!(hits(&unused), [(4, "all-unguarded")], "a count no assertion reads checks nothing"); + for change in ["let row = 4;", "row = 4;", "reset(&mut row);"] { + let changed = src.replace(" assert_eq!(row", &format!(" {change}\n assert_eq!(row")); + assert_eq!(hits(&changed), [(6, "all-unguarded")], "{change} before the assertion"); + } + let later = src.replace(" assert_eq!(row, 4, \"four cards\");\n", " assert_eq!(row, 4);\n let row = 4;\n"); + assert_eq!(hits(&later), [], "the count reaches the assertion before it is bound again"); + } + + #[test] + fn all_respects_condition_polarity() { + for condition in [ + "!xs.iter().all(|x| *x > 0)", + "!(xs.iter().all(|x| *x > 0))", + "ready() && !xs.iter().all(|x| *x > 0)", + "!xs.iter().all(|x| *x > 0) && ready()", + "xs.iter().all(|x| *x > 0) == false", + "ready() && (xs.iter().all(|x| *x > 0) == false)", + "false == xs.iter().all(|x| *x > 0)", + ] { + let good = format!("#[test]\nfn t() {{\n assert!({condition});\n}}\n"); + assert_eq!(hits(&good), [], "{condition}"); + let bad = format!("#[test]\nfn t() {{\n assert!(({condition}) && ys.iter().all(|y| *y > 0));\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "a positive operand beside {condition}"); + } + } + + #[test] + fn all_reports_positive_boolean_operands() { + for condition in [ + "xs.iter().all(|x| *x > 0)", + "ready() && xs.iter().all(|x| *x > 0)", + "xs.iter().all(|x| *x > 0) && ready()", + "ready() || xs.iter().all(|x| *x > 0)", + "xs.iter().all(|x| *x > 0) || ready()", + "!!xs.iter().all(|x| *x > 0)", + "!xs.iter().all(|x| *x > 0) == false", + "!(xs.iter().all(|x| *x > 0) == false)", + ] { + let bad = format!("#[test]\nfn t() {{\n assert!({condition});\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "{condition}"); + let good = bad.replace(" assert!", " assert_eq!(xs.len(), 3);\n assert!"); + assert_eq!(hits(&good), [], "a length check guards {condition}"); + } + } + + #[test] + fn all_guards_use_assertion_operands_and_skip_messages() { + for name in ["assert", "debug_assert", "prop_assert"] { + let good = format!("#[test]\nfn t() {{\n {name}!(xs.len() > 0);\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{name} condition"); + let bad = format!("#[test]\nfn t() {{\n {name}!(ready(), \"length {{}}\", xs.len());\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "{name} message"); + } + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + for (left, right) in [("xs.len()", "3"), ("3", "xs.len()")] { + let good = format!("#[test]\nfn t() {{\n {name}!({left}, {right});\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{name} operands"); + } + let bad = format!("#[test]\nfn t() {{\n {name}!(a, b, \"length {{}}\", xs.len());\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "{name} message"); + } + } + + #[test] + fn all_guards_require_checks_of_collection_properties() { + for expr in ["xs.len()", "xs.is_empty()", "xs.iter().count()", "xs.first()", "xs.iter().any(|x| *x > 0)", "xs.iter().next()", "xs.last()"] { + let bad = format!("#[test]\nfn t() {{\n let _ = {expr};\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "unused {expr}"); + let good = format!("#[test]\nfn t() {{\n assert_eq!({expr}, expected);\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "checked {expr}"); + } + } + + #[test] + fn all_guards_accept_first_item_access_that_fails_when_empty() { + for expr in ["xs[0]", "xs.first().unwrap()", "xs.first().expect(\"item\")", "xs.iter().next().unwrap()", "xs.iter().next().expect(\"item\")"] + { + let good = format!("#[test]\nfn t() {{\n let _ = {expr};\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{expr} fails when empty"); + let inner = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| {expr} > 0));\n}}\n"); + assert_eq!(hits(&inner), [(3, "all-unguarded")], "{expr} inside the predicate"); + let message = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| *x > 0), \"item {{:?}}\", {expr});\n}}\n"); + assert_eq!(hits(&message), [(3, "all-unguarded")], "{expr} inside the message"); + } + let literal = "#[test]\nfn t() {\n let _ = [0];\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(literal), [(4, "all-unguarded")], "an array literal does not access an item"); + } + + #[test] + fn all_guards_accept_panicking_first_item_bindings() { + let good = "#[test]\nfn t() {\n let Some(x) = xs.first() else { panic!(\"empty\") };\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(good), []); + let bad = "#[test]\nfn t() {\n let Some(x) = xs.first() else { skip(); };\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(bad), [(4, "all-unguarded")]); + } + + #[test] + fn all_hits_count_changes_anywhere_in_their_test() { + let src = "#[should_panic]\n#[test]\nfn t() {\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\nfn other() {}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 1); + assert_eq!(found[0].line, 5); + let guarded = src.replace(" assert!(xs.iter()", " assert!(!xs.is_empty());\n assert!(xs.iter()"); + assert_eq!(hits(&guarded), [], "the guard prevents the finding before deletion"); + for line in [1, 2, 3, 4, 5, 6] { + assert!(touches(&found[0], Some(&[line].into_iter().collect())), "test line {line}"); + } + assert!(!touches(&found[0], Some(&[7].into_iter().collect())), "another function is outside the test"); + let diff = "diff --git a/crates/x/src/tests.rs b/crates/x/src/tests.rs\n--- a/crates/x/src/tests.rs\n+++ b/crates/x/src/tests.rs\n@@ -5 +4,0 @@\n- assert!(!xs.is_empty());\n"; + let changed = parse_diff(diff); + assert!(touches(&found[0], changed["crates/x/src/tests.rs"].as_ref()), "removing a guard changes the test"); + } + + #[test] + fn all_allow_comments_stay_near_the_finding() { + let distant = "#[test]\nfn t() {\n // test-lint: allow all-unguarded empty input is allowed\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(distant), [(5, "all-unguarded")]); + let adjacent = "#[test]\nfn t() {\n let xs = f();\n // test-lint: allow all-unguarded empty input is allowed\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(adjacent), []); + let same = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| *x > 0)); // test-lint: allow all-unguarded empty input is allowed\n}\n"; + assert_eq!(hits(same), []); + } + + #[test] + fn only_weak_checks_are_reported_once_per_test() { + let bad = "#[test]\nfn t() {\n assert!(parse(\"a\").is_ok());\n assert!(!list().is_empty());\n}\n"; + assert_eq!(hits(bad), [(2, "only-weak")]); + let good = "#[test]\nfn t() {\n assert!(parse(\"a\").is_ok());\n assert_eq!(parse(\"a\").unwrap(), 1);\n}\n"; + assert_eq!(hits(good), []); + let refusal = "#[test]\nfn t() {\n assert!(parse(\"\").is_err());\n}\n"; + assert_eq!(hits(refusal), [], "is_err is not on the plan's list"); + let compound = "#[test]\nfn t() {\n assert!(a.is_some() && a == Some(2));\n}\n"; + assert_eq!(hits(compound), []); + for cond in ["(parse(\"x\").is_ok())", "((parse(\"x\").is_ok()))", "!(list().is_empty())", "(!list().is_empty())"] { + let src = format!("#[test]\nfn t() {{\n assert!({cond});\n}}\n"); + assert_eq!(hits(&src), [(2, "only-weak")], "{cond}"); + } + let grouped = "#[test]\nfn t() {\n assert!((a.is_some()) && (a == Some(2)));\n}\n"; + assert_eq!(hits(grouped), [], "parentheses around one side of a comparison stay"); + } + + #[test] + fn functions_declared_in_a_test_count_only_when_called() { + let unused = "#[test]\nfn t() {\n fn unused() {\n assert_eq!(1, 1);\n }\n assert!(parse(\"x\").is_ok());\n}\n"; + assert_eq!(hits(unused), [(2, "only-weak")], "a declared function's assertion does not run"); + let macro_only = "#[test]\nfn t() {\n macro_rules! check {\n () => { assert_eq!(1, 1) };\n }\n f();\n}\n"; + assert_eq!(hits(macro_only), [(2, "no-assertion")], "a declared macro's assertion does not run"); + let called = unused.replace(" assert!(parse", " unused();\n assert!(parse"); + let files = [("crates/x/src/tests.rs".to_owned(), called.clone())]; + let with_helpers = Ctx { helpers: asserting_helpers(&files), ..ctx() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &called, &with_helpers), [], "a call to it checks"); + } + + #[test] + fn should_panic_counts_only_when_applied() { + let weak = "#[test]\nfn t() {\n assert!(parse(\"x\").is_ok());\n}\n"; + for attr in [ + "#[should_panic]", + "#[ should_panic(expected = \"x\") ]", + "#[cfg_attr(test, should_panic)]", + "#[cfg_attr( test , should_panic(expected = \"x\"))]", + ] { + assert_eq!(hits(&format!("{attr}\n{weak}")), [], "{attr}"); + } + for attr in ["#[cfg_attr(any(), should_panic)]", "#[cfg_attr(windows, should_panic)]", "#[doc = \"should_panic\"]", "#[allow(should_panic)]"] + { + assert_eq!(hits(&format!("{attr}\n{weak}")), [(3, "only-weak")], "{attr}"); + } + } + + #[test] + fn self_compare_needs_the_same_plain_expression() { + let bad = "#[test]\nfn t() {\n let x = f();\n assert_eq!(x.len(), x.len());\n assert_eq!(&x, x);\n}\n"; + assert_eq!(hits(bad), [(4, "self-compare"), (5, "self-compare")]); + let good = "#[test]\nfn t() {\n assert_eq!(write(&doc), write(&doc), \"deterministic\");\n assert_eq!(f(\"a\"), f(\"b\"));\n assert_ne!(\"a b\", \"ab\");\n assert_ne!(x /* one */, x.y);\n assert_ne!(' ', ':');\n}\n"; + assert_eq!(hits(good), [], "literal text, including its spaces, is compared"); + } + + #[test] + fn self_compare_counts_changes_through_the_second_operand() { + let src = "#[test]\nfn t() {\n assert_eq!(\n actual,\n actual,\n \"comparison\"\n );\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 1); + let hit = &found[0]; + assert_eq!(hit.rule, Rule::SelfCompare); + assert_eq!((hit.line, hit.first, hit.last), (3, 3, 5)); + for line in [3, 4, 5] { + assert!(touches(hit, Some(&[line].into_iter().collect())), "changed line {line}"); + } + for line in [2, 6, 7] { + assert!(!touches(hit, Some(&[line].into_iter().collect())), "changed line {line}"); + } + assert_eq!(hits(&src.replacen(" actual,", " expected,", 1)), []); + } + + #[test] + fn self_compare_keeps_exemptions_near_the_macro_opening() { + let src = "#[test]\nfn t() {\n assert_eq!( // MARKER\n actual, // OPERAND\n actual\n );\n}\n"; + let allow = "test-lint: allow self-compare checks the lint"; + assert_eq!(hits(&src.replace("MARKER", allow)), []); + assert_eq!(hits(&src.replace(" assert_eq!", &format!(" // {allow}\n assert_eq!"))), []); + assert_eq!(hits(&src.replace("OPERAND", allow)), [(3, "self-compare")]); + } + + #[test] + fn a_process_test_must_read_its_output() { + let bad = "#[test]\nfn t() {\n let out = Command::new(bin()).arg(\"x\").output().unwrap();\n assert!(out.status.success());\n}\n"; + assert_eq!(hits(bad), [(2, "exit-status-only")]); + let good = "#[test]\nfn t() {\n let out = Command::new(bin()).output().unwrap();\n assert!(out.status.success());\n assert_eq!(out.stdout, b\"ok\\n\");\n}\n"; + assert_eq!(hits(good), []); + } + + #[test] + fn process_status_checks_accept_every_comparison_assertion() { + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {name}!(out.status.code(), Some(0), \"{{:?}}\", out.stderr);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{name}"); + let good = bad.replace("Some(0)", "parse_code(&out.stdout)"); + assert_eq!(hits(&good), [], "{name} reads output in its second operand"); + } + } + + #[test] + fn process_status_checks_accept_either_compared_operand() { + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + for (expected, status) in [("Some(0)", "out.status.code()"), ("true", "out.status.success()")] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {name}!({expected}, {status}, \"{{:?}}\", out.stdout);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{name} with {status} on the right"); + let good = bad.replace(expected, "parse_status(&out.stderr)"); + assert_eq!(hits(&good), [], "{name} reads output in its first operand"); + let message = bad.replace(status, "expected_status"); + assert_eq!(hits(&message), [], "{name} has no status check in its operands"); + } + } + } + + #[test] + fn process_output_in_failure_messages_does_not_count_as_reading() { + for assertion in ["assert!(out.status.success()", "debug_assert!(out.status.success()", "prop_assert!(out.status.success()"] { + let bad = + format!("#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {assertion}, \"{{:?}}\", out.stderr);\n}}\n"); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{assertion}"); + let good = bad.replace("out.status.success()", "out.status.success() && out.stdout == expected"); + assert_eq!(hits(&good), [], "output in the condition of {assertion}"); + } + for assertion in ["assert_eq", "assert_ne"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {assertion}!(out.status.code(), f::(), \"{{:?}}\", out.stderr);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{assertion}"); + let good = bad.replace("f::()", "from_slice(&out.stdout)"); + assert_eq!(hits(&good), [], "output in the second operand of {assertion}"); + } + } + + #[test] + fn stream_configuration_does_not_count_as_reading_output() { + for stream in ["stdout", "stderr", "stdin"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).{stream}(Stdio::piped()).output().unwrap();\n assert!(out.status.success());\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{stream} configuration"); + let good = bad.replace(" assert!", " let _ = out.stderr;\n assert!"); + assert_eq!(hits(&good), [], "reading a field after {stream} configuration"); + } + let bad = "#[test]\nfn t() {\n let out = Command::new(bin()).stdout (std::process::Stdio::piped()).output().unwrap();\n assert!(out.status.success());\n}\n"; + assert_eq!(hits(bad), [(2, "exit-status-only")]); + let good = bad.replace("std::process::Stdio::piped()", "output.stdout"); + assert_eq!(hits(&good), [], "a field read in a builder argument counts"); + } + + #[test] + fn output_inspection_counts_outside_failure_messages() { + for read in [ + "out.stdout", + "out.stderr", + "String::from_utf8(out.stdout)", + "fs::read(path)", + "read_to_string(path)", + "from_slice(data)", + "from_str(text)", + "text.contains(needle)", + ] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n assert!(out.status.success(), \"{{:?}}\", {read});\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{read} in a message"); + let good = bad.replace(" assert!", &format!(" let _ = {read};\n assert!")); + assert_eq!(hits(&good), [], "{read} outside a message"); + } + } + + #[test] + fn failure_messages_are_removed_for_every_standard_assertion() { + for name in [ + "assert", + "debug_assert", + "prop_assert", + "assert_eq", + "assert_ne", + "debug_assert_eq", + "debug_assert_ne", + "prop_assert_eq", + "prop_assert_ne", + ] { + let operands = if guard_arg_count(name) == 1 { "true" } else { "left, right" }; + let bad = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| *x > 0));\n {name}!({operands}, \"{{:?}}\", xs[0]);\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "{name} message"); + let good = bad.replace(" assert!", " let _ = xs[0];\n assert!"); + assert_eq!(hits(&good), [], "access outside the {name} message"); + } + } + + #[test] + fn assertion_arguments_keep_turbofish_groups_and_split_comparisons() { + for operand in ["f::()", "f::>()", "f :: ()"] { + let src = format!("{operand}, expected, message"); + let m = mask(&src); + let args: Vec<&str> = split_args(&m, 0, m.len()).into_iter().map(|(from, to)| src[from..to].trim()).collect(); + assert_eq!(args, [operand, "expected", "message"], "{operand}"); + let comparison = format!("a < b, {operand} > c, message"); + let m = mask(&comparison); + let args: Vec<&str> = split_args(&m, 0, m.len()).into_iter().map(|(from, to)| comparison[from..to].trim()).collect(); + assert_eq!(args, ["a < b", &format!("{operand} > c"), "message"], "comparisons around {operand}"); + } + } + + #[test] + fn a_test_needs_an_assertion_or_an_asserting_helper() { + let bad = "#[test]\nfn t() {\n let d = open(\"x\").unwrap();\n d.save();\n}\n"; + assert_eq!(hits(bad), [(2, "no-assertion")]); + let panics = "fn f() {}\n/// Panics.\n#[should_panic(expected = \"x\")]\n#[test]\nfn p() {\n f();\n}\n"; + assert_eq!(hits(panics), [], "#[should_panic] before #[test]"); + let src = "fn same(a: u8, b: u8) {\n assert_eq!(a, b);\n}\nfn twice(a: u8) {\n same(a, a);\n}\n#[test]\nfn t() {\n twice(f());\n}\n#[test]\n#[should_panic]\nfn p() {\n f();\n}\n#[test]\nfn q() {\n check_round_trip(f());\n}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); + assert!(helpers["crates/x"].contains("twice"), "{helpers:?}"); + let ctx = Ctx { helpers, ci_env: HashSet::new() }; + assert_eq!(hits_in("crates/x/tests/it.rs", src, &ctx), []); + assert_eq!(hits_in("crates/y/tests/it.rs", src, &ctx), [(8, "no-assertion")], "another crate's helper does not count"); + let kit = asserting_helpers(&[("crates/testkit/src/lib.rs".to_owned(), src.to_owned()), ("crates/y/src/lib.rs".to_owned(), String::new())]); + assert!(kit["crates/y"].contains("twice"), "testkit helpers count in every crate: {kit:?}"); + assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers: HashMap::new(), ci_env: HashSet::new() }), [(8, "no-assertion")]); + } + + #[test] + fn generic_asserting_calls_count_for_functions_and_methods() { + for call in ["check_round_trip::()", "check_round_trip::>(x)", "value.check::()", "value.check :: >> ()"] { + let src = format!("#[test]\nfn t() {{\n {call};\n}}\n"); + assert_eq!(hits(&src), [], "{call}"); + } + for expression in ["check_round_trip::", "value.check::", "round_trip::()", "value.round_trip::()"] { + let src = format!("#[test]\nfn t() {{\n let _ = {expression};\n}}\n"); + assert_eq!(hits(&src), [(2, "no-assertion")], "{expression}"); + } + } + + #[test] + fn generic_crate_helpers_count_through_other_helpers() { + let defs = "fn same(a: T, b: T) { assert_eq!(a, b); }\nfn twice(a: T) { same::(a, a); }\nfn idle() {}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/helpers.rs".to_owned(), defs.to_owned())]); + assert!(helpers["crates/x"].contains("same")); + assert!(helpers["crates/x"].contains("twice")); + assert!(!helpers["crates/x"].contains("idle")); + let ctx = Ctx { helpers, ci_env: HashSet::new() }; + for call in ["same::(a, b)", "twice::>>(x)"] { + let src = format!("#[test]\nfn t() {{\n {call};\n}}\n"); + assert_eq!(hits_in("crates/x/tests/it.rs", &src, &ctx), [], "{call}"); + assert_eq!(hits_in("crates/y/tests/it.rs", &src, &ctx), [(2, "no-assertion")], "{call} in another crate"); + } + for expression in ["idle::()", "same::", "value.same::()"] { + let src = format!("#[test]\nfn t() {{\n let _ = {expression};\n}}\n"); + assert_eq!(hits_in("crates/x/tests/it.rs", &src, &ctx), [(2, "no-assertion")], "{expression}"); + } + } + + #[test] + fn early_returns_on_values_are_reported_and_resource_skips_are_not() { + let bad = "#[test]\nfn t() {\n let Some(n) = find() else { return };\n assert_eq!(n, 2);\n}\n"; + assert_eq!(hits(bad), [(3, "early-return")]); + let fonts = "#[test]\nfn t() {\n let Some(face) = installed_family(\"Kufi\") else { return; };\n assert_eq!(face.n, 2);\n}\n"; + assert_eq!(hits(fonts), []); + let closure = "#[test]\nfn t() {\n let f = |x: u8| { if x == 0 { return; } g(x) };\n assert_eq!(f(1), ());\n}\n"; + assert_eq!(hits(closure), []); + let last = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n if g() { return; }\n}\n"; + assert_eq!(hits(last), []); + let value = "#[test]\nfn t() -> Result<(), String> {\n if f()? == 0 { return Ok(()); }\n assert_eq!(g(), 1);\n Ok(())\n}\n"; + assert_eq!(hits(value), [(3, "early-return")]); + let checked = "#[test]\nfn t() {\n for _ in 0..9 {\n if g() == 1 {\n assert_eq!(f(), 2);\n return;\n }\n }\n panic!(\"never stable\");\n}\n"; + assert_eq!(hits(checked), [], "a return after an assertion in its block"); + let said = "#[test]\nfn t() {\n if !link(\"a\") {\n eprintln!(\"skipped: no links here\");\n return;\n }\n assert_eq!(f(), 2);\n}\n"; + assert_eq!(hits(said), [], "a return after a printed skip note"); + let commented = "#[test]\nfn t() {\n let Some(w) = width() else { return }; // no wide font here\n assert_eq!(w, 2);\n}\n"; + assert_eq!(hits(commented), [], "a return whose line says why"); + let quiet = "#[test]\nfn t() {\n if !link(\"a\") {\n return;\n }\n assert_eq!(f(), 2);\n}\n"; + assert_eq!(hits(quiet), [(4, "early-return")]); + } + + #[test] + fn ignore_needs_a_reason() { + let bad = "#[test]\n#[ignore]\nfn t() {\n assert_eq!(f(), 1);\n}\n#[ignore = \" \"]\n#[test]\nfn u() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(bad), [(2, "ignore-without-reason"), (6, "ignore-without-reason")]); + let good = "#[test]\n#[ignore = \"a benchmark: run with --ignored\"]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(good), []); + } + + #[test] + fn ignore_accepts_non_empty_raw_string_reasons() { + for hashes in ["", "#", "##", "########"] { + for reason in ["requires an external service", " service ", r"service \ path"] { + let literal = format!("r{hashes}\"{reason}\"{hashes}"); + let src = format!("#[test]\n#[ignore = {literal}]\nfn t() {{ assert_eq!(f(), 1); }}\n"); + assert_eq!(hits(&src), [], "{literal}"); + } + for reason in ["", " ", "\t\n"] { + let literal = format!("r{hashes}\"{reason}\"{hashes}"); + let src = format!("#[test]\n#[ignore = {literal}]\nfn t() {{ assert_eq!(f(), 1); }}\n"); + assert_eq!(hits(&src), [(2, "ignore-without-reason")], "{literal}"); + } + } + } + + #[test] + fn env_gates_need_a_variable_ci_sets() { + let bad = "#[test]\nfn t() {\n let Ok(dir) = std::env::var(\"MY_SAMPLES\") else { return };\n assert_eq!(count(&dir), 3);\n}\n"; + assert_eq!(hits(bad), [(3, "env-gate-unset")]); + let ci = "#[test]\nfn t() {\n if std::env::var(\"SET_IN_CI\").is_ok() { assert_eq!(f(), 1); }\n assert_eq!(std::env::var(\"CARGO_PKG_NAME\").unwrap(), \"x\");\n}\n"; + assert_eq!(hits(ci), []); + let child = "const CHILD: &str = \"X_TEST_CHILD\";\n#[test]\nfn t() {\n if std::env::var_os(\"X_TEST_CHILD\").is_some() { assert_eq!(f(), 1); }\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(child), []); + } + + #[test] + fn env_gates_ignore_commented_out_setters() { + for setter in ["cmd.env(\"MY_SAMPLES\", dir);", "std::env::set_var(\"MY_SAMPLES\", \"x\");", "const X: &str = \"MY_SAMPLES\";"] { + for comment in [format!("// {setter}"), format!("/* {setter} */"), format!("/* outer /* {setter} */ end */")] { + let src = + format!("{comment}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [(4, "env-gate-unset")], "{comment}"); + } + } + } + + #[test] + fn env_gates_keep_code_setters_and_literal_contents() { + for setter in [ + "cmd . env ( \"MY_SAMPLES\", dir);", + "std::env::set_var ( \"MY_SAMPLES\", \"x\");", + "set_var(\"MY_SAMPLES\", \"x\");", + "use std::env::set_var; fn setup() { set_var(\"MY_SAMPLES\", \"x\"); }", + "cmd.set_var(\"MY_SAMPLES\", \"x\");", + "const X: &str = \"MY_SAMPLES\";", + "cmd.env(/* name */ \"MY_SAMPLES\", dir);", + ] { + let src = format!("{setter}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [], "{setter}"); + assert_eq!(hits(&src.replacen("MY_SAMPLES", "OTHER_SAMPLES", 1)), [(4, "env-gate-unset")], "{setter}"); + } + let src = "let a = \"https://host/*path*/\"; /* removed */ let b = r#\"// kept /* kept */\"#; // removed\nlet c = '/';"; + let masked = String::from_utf8(mask_parts(src, true, false)).unwrap(); + assert!(masked.contains("\"https://host/*path*/\"")); + assert!(masked.contains("r#\"// kept /* kept */\"#")); + assert!(masked.contains("let c = '/';")); + assert!(!masked.contains("removed")); + } + + #[test] + fn env_gates_require_setter_call_boundaries() { + for reader in [ + "read_env(\"MY_SAMPLES\");", + "cmd.read_env(\"MY_SAMPLES\");", + "env(\"MY_SAMPLES\", dir);", + "my_set_var(\"MY_SAMPLES\", \"x\");", + "std::env::my_set_var(\"MY_SAMPLES\", \"x\");", + "cmd.my_set_var(\"MY_SAMPLES\", \"x\");", + ] { + let src = format!("{reader}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [(4, "env-gate-unset")], "{reader}"); + } + } + + #[test] + fn sleep_in_test_code_is_reported() { + let bad = "fn wait() {\n std::thread::sleep(Duration::from_millis(5));\n}\n#[test]\nfn t() {\n thread::sleep(D);\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(bad), [(2, "sleep"), (6, "sleep")]); + let good = "fn sleep(d: D) {}\n#[test]\nfn t() {\n run(\"$.sleep(250)\");\n clock.sleep(D);\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(good), []); + let shipped = "pub fn wait() {\n std::thread::sleep(D);\n}\n#[cfg(test)]\nmod tests {}\n"; + assert_eq!(hits_in("crates/x/src/lib.rs", shipped, &ctx()), [], "code before #[cfg(test)] is not test code"); + assert_eq!(hits_in("xtask/src/test_lint.rs", shipped, &ctx()), [], "a name that only starts with test is not a test file"); + let after = "#[cfg(test)]\nmod tests {\n fn w() { thread::sleep(D); }\n}\npub fn later() {\n thread::sleep(D);\n}\n"; + assert_eq!(hits_in("crates/x/src/lib.rs", after, &ctx()), [(3, "sleep")], "code after a #[cfg(test)] module is not test code"); + for gate in ["all(test, windows)", "all( test , not(target_arch = \"wasm32\") )", "all(feature = \"x\", all(unix, test))"] { + let gated = format!("#[cfg({gate})]\nmod tests {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); + assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [(3, "sleep")], "{gate} holds only in tests"); + } + for attr in ["#[ cfg(all(test, unix))]", "#[/* test-only */cfg(test)]", "# [cfg (test)]"] { + let gated = format!("{attr}\nmod tests {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); + assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [(3, "sleep")], "{attr}"); + } + for gate in ["any(test, feature = \"x\")", "not(test)", "all(unix, not(test))", "feature = \"test\""] { + let gated = format!("#[cfg({gate})]\nmod helpers {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); + assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [], "{gate} also holds outside tests"); + } + for test_file in [ + "crates/x/src/tests.rs", + "crates/x/src/tests_wheel.rs", + "crates/x/src/widget_tests.rs", + "crates/x/tests/it/a.rs", + "crates/testkit/src/lib.rs", + ] { + assert_eq!(hits_in(test_file, shipped, &ctx()), [(2, "sleep")], "{test_file}"); + } + } + + #[test] + fn reading_rust_source_is_reported_outside_the_audits() { + let bad = "#[test]\nfn t() {\n let src = include_str!(\"../lib.rs\");\n assert_eq!(src.matches(\"x\").count(), 1);\n}\n"; + assert_eq!(hits(bad), [(3, "reads-source")]); + let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(\".rs\")).count();\n assert_eq!(n, 4);\n}\n"; + assert_eq!(hits(walk), [(3, "reads-source")]); + assert_eq!(hits_in(SOURCE_AUDITS[0], bad, &ctx()), []); + let data = "#[test]\nfn t() {\n let s = include_str!(\"fixtures/a.svg\");\n assert_eq!(s.len(), 4);\n}\n"; + assert_eq!(hits(data), []); + } + + #[test] + fn allow_comments_need_the_rule_and_a_reason() { + let src = "#[test]\nfn t() {\n // test-lint: allow sleep the file clock has a 2 ms step\n thread::sleep(D);\n thread::sleep(D); // test-lint: allow sleep same\n assert_eq!(f(), 1);\n thread::sleep(D); // test-lint: allow sleep\n thread::sleep(D); // test-lint: allow early-return wrong rule\n}\n// test-lint: allow no-assertion a smoke test of the panic-free reader\n#[test]\nfn u() {\n let _ = read(b\"junk\");\n}\n"; + assert_eq!(hits(src), [(7, "sleep"), (8, "sleep")], "an allow covers its own line and the next, and needs a reason"); + let strings = "#[test]\nfn t() {\n let s = \"test-lint: allow sleep in a string\"; thread::sleep(D);\n let r = r#\"test-lint: allow sleep raw\"#; thread::sleep(D);\n /* test-lint: allow sleep a block comment */ thread::sleep(D);\n assert_eq!(s, r);\n}\n"; + assert_eq!(hits(strings), [(3, "sleep"), (4, "sleep")], "a marker in a literal is not an exemption"); + } + + #[test] + fn comments_and_strings_are_not_code() { + let src = "#[test]\nfn t() {\n // assert!(x.iter().all(|y| y))\n let s = \"thread::sleep(d); #[ignore]\";\n let r = r#\"env::var(\"NOPE\")\"#;\n let c = '\"';\n assert_eq!(s, r);\n}\n"; + assert_eq!(hits(src), []); + } + + #[test] + fn tests_are_found_by_their_attributes() { + let src = "#[cfg(test)]\nmod tests {\n #[tokio::test]\n async fn a() {}\n #[test_case(1)]\n fn b(n: u8) {}\n proptest! {\n #[test]\n fn c(x in 0..9u8) {}\n }\n #[test]\n fn d() -> Result<(), String> { Ok(()) }\n fn not_a_test() {}\n}\n"; + let names: Vec = tests_in(&mask(src)).into_iter().map(|t| t.name).collect(); + assert_eq!(names, ["a", "b", "c", "d"]); + } + + #[test] + fn changed_lines_come_from_the_new_side_of_each_hunk() { + let diff = "diff --git a/crates/x/src/a.rs b/crates/x/src/a.rs\nindex 1..2 100644\n--- a/crates/x/src/a.rs\n+++ b/crates/x/src/a.rs\n@@ -3,0 +4,2 @@ fn f() {\n+a\n+b\n@@ -10 +12 @@\n-c\n+d\n@@ -20,2 +21,0 @@\n-e\ndiff --git a/crates/x/src/n.rs b/crates/x/src/n.rs\nnew file mode 100644\n--- /dev/null\n+++ b/crates/x/src/n.rs\n@@ -0,0 +1,3 @@\n"; + let got = parse_diff(diff); + assert_eq!(got.len(), 2); + assert_eq!(got["crates/x/src/a.rs"], Some([4, 5, 12, 21, 22].into_iter().collect())); + assert_eq!(got["crates/x/src/n.rs"], None); + } + + #[test] + fn deleting_the_first_attribute_changes_the_remaining_test() { + let path = "crates/x/src/tests.rs"; + for (prefix, anchor) in [("", 0), ("fn before() {}\n", 1)] { + let src = format!("{prefix}#[test]\nfn t() {{}}\n#[test]\nfn other() {{}}\n"); + let before = src.replacen("#[test]", "#[should_panic]\n#[test]", 1); + assert!(lint_file(path, &before, &ctx()).iter().all(|h| h.test != "t"), "the attribute prevents the finding"); + let found = lint_file(path, &src, &ctx()); + assert_eq!(found.len(), 2); + let old = anchor + 1; + let diff = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -{old} +{anchor},0 @@\n-#[should_panic]\n"); + let changed = parse_diff(&diff); + let expected = if anchor == 0 { vec![1] } else { vec![anchor, anchor + 1] }; + assert_eq!(changed[path], Some(expected.into_iter().collect())); + assert_eq!(found[0].rule, Rule::NoAssertion); + assert_eq!(found[0].test, "t"); + assert!(touches(&found[0], changed[path].as_ref()), "the deletion changes the remaining test"); + assert!(!touches(&found[1], changed[path].as_ref()), "the following test is unchanged"); + } + } + + #[test] + fn only_hits_on_changed_lines_count() { + let src = "#[test]\nfn old() {\n f();\n}\n#[test]\nfn new() {\n g();\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 2); + let changed: BTreeSet = [7].into_iter().collect(); + let counted: Vec<&str> = found.iter().filter(|h| touches(h, Some(&changed))).map(|h| h.test.as_str()).collect(); + assert_eq!(counted, ["new"]); + assert_eq!(found.iter().filter(|h| touches(h, None)).count(), 2); + assert_eq!(found.iter().filter(|h| touches(h, Some(&BTreeSet::new()))).count(), 0); + } + + #[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"]); + 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 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_eq!(finish(&[], 3, 1, "base"), Ok(())); + } + + #[test] + fn options_reject_unknown_and_repeated_arguments() { + assert_eq!(Options::parse(&[]), Ok(Options::default())); + assert_eq!(Options::parse(&["--base", "abc"]), Ok(Options { all: false, base: Some("abc".into()) })); + assert_eq!(Options::parse(&["--all"]), Ok(Options { all: true, base: None })); + for bad in [&["--base"][..], &["--base", "--all"], &["--all", "--all"], &["--fix"], &["--all", "--base", "x"]] { + assert!(Options::parse(bad).unwrap_err().starts_with("test-lint:"), "{bad:?}"); + } + } + + #[test] + fn workflow_variables_count_as_set() { + let names: Vec = upper_words("env:\n AFFINITY_CORPUS_REQUIRED: 1\n run: X=1 cargo test # A\n").collect(); + assert_eq!(names, ["AFFINITY_CORPUS_REQUIRED", "X"]); + assert!(set_by_system("CARGO_MANIFEST_DIR") && set_by_system("HOME") && !set_by_system("MY_SAMPLES")); + } + + #[test] + fn workflow_mapping_keys_count_without_reads_or_comments() { + let assigned: Vec = upper_words("env:\n MY_SAMPLES: fixtures\n - OTHER_SAMPLES: fixtures\n EMPTY_SAMPLES:\n").collect(); + assert_eq!(assigned, ["MY_SAMPLES", "OTHER_SAMPLES", "EMPTY_SAMPLES"]); + let reads = "# MY_SAMPLES: fixtures\nif: env.MY_SAMPLES != ''\nrun: echo $OTHER_SAMPLES ${EMPTY_SAMPLES}\nvalue: ${{ env.MY_SAMPLES }}\n"; + assert_eq!(upper_words(reads).collect::>(), Vec::::new()); + } + + #[test] + fn workflow_script_assignments_count_without_reads_or_comments() { + for assignment in [ + " MY_SAMPLES=value", + " export MY_SAMPLES=value", + " run: MY_SAMPLES=value cargo test", + " echo \"MY_SAMPLES=value\" >> \"$GITHUB_ENV\"", + " echo 'MY_SAMPLES=value' >> \"$GITHUB_ENV\"", + " MY_SAMPLES=value # OTHER_SAMPLES=value", + " MY_SAMPLES=\"#value\"", + " MY_SAMPLES=", + " - MY_SAMPLES=value", + ] { + assert_eq!(upper_words(assignment).collect::>(), ["MY_SAMPLES"], "{assignment}"); + let commented = format!("# {assignment}"); + assert_eq!(upper_words(&commented).collect::>(), Vec::::new(), "{commented}"); + } + let reads = "env.MY_SAMPLES=value\n${{ env.MY_SAMPLES }}\n$MY_SAMPLES\n${MY_SAMPLES}\nMY_SAMPLES==value\n"; + assert_eq!(upper_words(reads).collect::>(), Vec::::new()); + } + + #[test] + fn workflow_mentions_do_not_suppress_unset_gates() { + let src = "#[test]\nfn t() {\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; + for workflow in ["if: env.MY_SAMPLES != ''", "run: echo $MY_SAMPLES", "# MY_SAMPLES=value"] { + let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [(3, "env-gate-unset")], "{workflow}"); + } + for workflow in ["env:\n MY_SAMPLES: fixtures", "run: |\n export MY_SAMPLES=fixtures", "with:\n env: |\n MY_SAMPLES=fixtures"] { + let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [], "{workflow}"); + } + } + + #[test] + fn printed_workflow_assignments_do_not_count() { + for line in + ["run: echo \"MY_SAMPLES=fixtures\"", " echo MY_SAMPLES=fixtures", " printf 'MY_SAMPLES=x\\n'", " true && echo \"MY_SAMPLES=x\""] + { + assert_eq!(upper_words(line).collect::>(), Vec::::new(), "{line}"); + } + for line in [" echo hi; MY_SAMPLES=x cargo test", " printf 'MY_SAMPLES=x\\n' >> \"$GITHUB_ENV\""] { + assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); + } + } + + #[test] + fn patch_labels_are_decoded_before_filtering() { + let diff = "diff --git a/crates/x/tests/two words.rs b/crates/x/tests/two words.rs\n--- a/crates/x/tests/two words.rs\t\n+++ b/crates/x/tests/two words.rs\t\n@@ -1 +1 @@\n-a\n+b\ndiff --git \"a/crates/x/tests/q\\\"t.rs\" \"b/crates/x/tests/q\\\"t.rs\"\n--- \"a/crates/x/tests/q\\\"t.rs\"\n+++ \"b/crates/x/tests/q\\\"t.rs\"\n@@ -2 +2 @@\n-a\n+b\ndiff --git \"a/crates/x/tests/caf\\303\\251.rs\" \"b/crates/x/tests/caf\\303\\251.rs\"\n--- \"a/crates/x/tests/caf\\303\\251.rs\"\n+++ \"b/crates/x/tests/caf\\303\\251.rs\"\n@@ -3 +3 @@\n-a\n+b\n"; + let got = parse_diff(diff); + assert_eq!(got.get("crates/x/tests/two words.rs"), Some(&Some([1].into_iter().collect())), "{got:?}"); + assert_eq!(got.get("crates/x/tests/q\"t.rs"), Some(&Some([2].into_iter().collect())), "{got:?}"); + assert_eq!(got.get("crates/x/tests/caf\u{e9}.rs"), Some(&Some([3].into_iter().collect())), "{got:?}"); + assert!(got.keys().all(|p| is_scanned(p)), "{got:?}"); + } + + #[test] + fn test_case_arguments_and_inner_attributes_do_not_hide_tests() { + let cases = "#[test_case(1; \"one\")]\n#[test_case(2; \"two\")]\nfn t(n: u8) {}\n"; + assert_eq!(hits(cases), [(3, "no-assertion")]); + let inner = "#![allow(dead_code)]\n\n#[should_panic]\n#[test]\nfn t() {\n f();\n}\n#[test]\nfn u() {\n g();\n}\n"; + let found = lint_file("crates/x/src/tests.rs", &inner.replace("#[should_panic]\n", ""), &ctx()); + assert_eq!(found.iter().map(|h| (h.first, h.last)).collect::>(), [(3, 6), (7, 10)], "{found:?}"); + assert_eq!(hits(inner), [(9, "no-assertion")], "#[should_panic] before #[test] still belongs to the test"); + } + + #[test] + fn helpers_with_a_shared_name_count_only_when_each_asserts() { + let src = "mod a {\n pub fn exercise() { assert_eq!(f(), 1); }\n}\nmod b {\n pub fn exercise() { f(); }\n}\n#[test]\nfn t() {\n b::exercise();\n}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); + assert!(!helpers["crates/x"].contains("exercise"), "{helpers:?}"); + assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers, ci_env: HashSet::new() }), [(8, "no-assertion")]); + let both = src.replace("{ f(); }", "{ assert!(f()); }"); + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), both.clone())]); + assert_eq!(hits_in("crates/x/tests/it.rs", &both, &Ctx { helpers, ci_env: HashSet::new() }), []); + } + + #[test] + fn a_changed_collection_loses_its_equality_guard() { + let src = "#[test]\nfn t() {\n let mut xs = f();\n assert_eq!(xs, vec![1]);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + for change in ["xs.clear();", "xs.retain(|x| *x > 5);", "xs = vec![];"] { + let changed = src.replace("\n assert!", &format!("\n {change}\n assert!")); + assert_eq!(hits(&changed), [(6, "all-unguarded")], "{change}"); + } + } + + #[test] + fn stream_redirection_to_any_target_is_configuration() { + let bad = "#[test]\nfn t() {\n let status = Command::new(bin()).stdout(file).stderr(log.try_clone().unwrap()).status().unwrap();\n assert!(status.success());\n}\n"; + assert_eq!(hits(bad), [(2, "exit-status-only")]); + let good = bad.replace(" assert!", " assert_eq!(fs::read(path).unwrap(), b\"ok\");\n assert!"); + assert_eq!(hits(&good), []); + } + + #[test] + fn async_blocks_end_their_own_returns() { + let src = "#[test]\nfn t() {\n block_on(async { if missing() { return; } work().await; });\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(src), []); + assert_eq!(hits(&src.replace("async {", "async move {")), []); + let own = "#[tokio::test]\nasync fn t() {\n if missing() { return; }\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(own), [(3, "early-return")], "a return from the test's own body"); + } + + #[test] + fn env_setters_in_literals_do_not_count_and_spans_reach_the_name() { + let src = "#[test]\nfn t() {\n let _example = r#\"cmd.env(\"MY_SAMPLES\", dir)\"#;\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; + assert_eq!(hits(src), [(4, "env-gate-unset")]); + let constant = "const X: &str = r#\"= \"MY_SAMPLES\";\"#;\n#[test]\nfn t() {\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; + assert_eq!(hits(constant), [(4, "env-gate-unset")]); + let multiline = "#[test]\nfn t() {\n let dir = std::env::var(\n \"MY_SAMPLES\",\n );\n assert_eq!(f(dir), 3);\n}\n"; + let found = lint_file("crates/x/src/tests.rs", multiline, &ctx()); + assert_eq!(found.iter().map(|h| (h.rule, h.line, h.first, h.last)).collect::>(), [(Rule::EnvGateUnset, 3, 3, 4)]); + assert!(touches(&found[0], Some(&[4].into_iter().collect())), "a change to the name alone"); + } + + #[test] + fn sleep_needs_the_thread_function() { + let local = "fn sleep() -> u8 { 42 }\n#[test]\nfn t() {\n assert_eq!(sleep(), 42);\n}\n"; + assert_eq!(hits(local), []); + for import in ["use std::thread::sleep;", "use std::thread::{self, sleep};"] { + let src = format!("{import}\n#[test]\nfn t() {{\n sleep(D);\n assert_eq!(f(), 42);\n}}\n"); + assert_eq!(hits(&src), [(4, "sleep")], "{import}"); + } + assert_eq!(hits("#[test]\nfn t() {\n std :: thread :: sleep(D);\n assert_eq!(f(), 1);\n}\n"), [(3, "sleep")]); + } + + #[test] + fn raw_include_str_paths_are_checked() { + for literal in ["r\"../lib.rs\"", "r#\"../lib.rs\"#", "r##\"../lib.rs\"##"] { + let src = format!("#[test]\nfn t() {{\n let src = include_str!({literal});\n assert_eq!(src.len(), 1);\n}}\n"); + assert_eq!(hits(&src), [(3, "reads-source")], "{literal}"); + assert_eq!(hits(&src.replace(".rs", ".svg")), [], "{literal} with a fixture"); + assert_eq!(hits_in(SOURCE_AUDITS[0], &src, &ctx()), [], "{literal} in an audit"); + } + let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(r#\".rs\"#)).count();\n assert_eq!(n, 4);\n}\n"; + assert_eq!(hits(walk), [(3, "reads-source")]); + } + + #[test] + fn single_letter_variables_set_in_ci_count() { + let src = "#[test]\nfn t() {\n let dir = std::env::var(\"X\");\n assert_eq!(f(dir), 3);\n}\n"; + assert_eq!(hits(src), [(3, "env-gate-unset")]); + let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words("env:\n X: 1\n").collect() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), []); + } + + #[test] + fn tests_with_non_ascii_names_are_checked() { + let src = "#[test]\nfn échec() {\n assert!(f().is_ok());\n}\n"; + assert_eq!(lint_file("crates/x/src/tests.rs", src, &ctx()).iter().map(|h| (h.line, h.test.as_str())).collect::>(), [(2, "échec")]); + } + + #[test] + fn block_comment_allows_need_a_reason_before_the_closing_delimiter() { + let bare = "#[test]\nfn t() {\n thread::sleep(D); /* test-lint: allow sleep */\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(bare), [(3, "sleep")]); + assert_eq!(hits(&bare.replace("sleep */", "sleep the clock has a 2 ms step */")), []); + } + + #[test] + fn bindings_out_of_scope_do_not_guard_all() { + let src = "#[test]\nfn t() {\n let xs: Vec = vec![];\n {\n let xs = vec![1];\n use_it(&xs);\n }\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), [(8, "all-unguarded")]); + let inside = "#[test]\nfn t() {\n let xs: Vec = vec![];\n {\n let xs = vec![1];\n assert!(xs.iter().all(|x| *x > 0));\n }\n use_it(&xs);\n}\n"; + assert_eq!(hits(inside), []); + } + + #[test] + fn constants_with_several_values_are_unknown() { + let src = "mod a { const START: usize = 0; }\nmod b {\nconst START: usize = 2;\nconst END: usize = 2;\n#[test]\nfn t() {\n let xs: Vec = (START..END).collect();\n assert!(xs.iter().all(|x| *x > 0));\n}\n}\n"; + assert_eq!(hits(src), [(8, "all-unguarded")]); + assert_eq!(hits(&src.replace("mod a { const START: usize = 0; }\n", "").replace("END: usize = 2", "END: usize = 4")), []); + } + + #[test] + fn a_count_stops_guarding_when_its_collection_changes() { + let src = + "#[test]\nfn t() {\n let mut xs = f();\n let n = xs.len();\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + let cleared = src.replace(" assert_eq!(n, 1);", " xs.clear();\n assert_eq!(n, 1);"); + assert_eq!(hits(&cleared), [(7, "all-unguarded")]); + } + + #[test] + fn checks_in_failure_messages_do_not_end_only_weak() { + let src = "#[test]\nfn t() {\n assert!(parse(input).is_ok(), \"{:?}\", probe().unwrap_err());\n}\n"; + assert_eq!(hits(src), [(2, "only-weak")]); + assert_eq!(hits(&src.replace(" assert!", " let _ = probe().unwrap_err();\n assert!")), []); + } + + #[test] + fn advancing_calls_are_not_self_comparisons() { + for operand in ["it.next()", "q.pop_front()", "rx.recv()"] { + let src = format!("#[test]\nfn t() {{\n assert_ne!({operand}, {operand});\n}}\n"); + assert_eq!(hits(&src), [], "{operand}"); + } + assert_eq!(hits("#[test]\nfn t() {\n assert_eq!(x.len(), x.len());\n}\n"), [(3, "self-compare")]); + } + + #[test] + fn ignore_spans_reach_a_reason_on_the_next_line() { + let src = "#[test]\n#[ignore =\n \"\"]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.iter().map(|h| (h.rule, h.line, h.first, h.last)).collect::>(), [(Rule::IgnoreWithoutReason, 2, 2, 3)]); + assert!(touches(&found[0], Some(&[3].into_iter().collect())), "a change to the reason alone"); + } +}