mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 12:35:48 -05:00
A path string that continues on the next line with a backslash now decodes to the joined file name, so the conditional route is kept. A range argument with two fixed bounds (1..4, 1..=4) no longer counts as an input, so the round-trip census diagnostic stays; a range with a variable bound still suppresses it. Adds a test for a bracket in a cfg_attr path filename keeping its sibling cfg gate.
9110 lines
473 KiB
Rust
9110 lines
473 KiB
Rust
//! `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. Left
|
|
//! out: the pause of a `while` or `loop` that checks a condition (its condition or body calls a
|
|
//! function or method besides reading the clock), also under an `if` or `match` inside that
|
|
//! loop, and the delay inside a closure passed to `spawn` whose thread handle the test drops;
|
|
//! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file,
|
|
//! `read_to_string` of a path with a `.rs` literal, or a `.ends_with(".rs")` check that selects
|
|
//! files from a listing, is in a function that reads a file or stream, or is in a function that
|
|
//! calls a function defined in the file whose body reads one, regardless of the receiver or
|
|
//! arguments), outside the source audits in [`SOURCE_AUDITS`];
|
|
//! * `census`: a test that loops over a whole table (a `SCREAMING_CASE` constant, `Type::ALL`,
|
|
//! `Type::iter()`, or a call named `all`, `catalog`, `registry`, `presets`, `swatches`,
|
|
//! `entries`, `variants`, `commands`, `builtins` or `palette`, or ending or starting with one of
|
|
//! those after `_`) where every assertion in the loop only checks presence (`is_some`, `is_ok`,
|
|
//! `is_empty`, `contains`, `starts_with`, `is_finite`, `len() > 0`) or compares with a lookup or
|
|
//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table. A loop that
|
|
//! passes the entry to a call together with other state (a command run, a file written, a
|
|
//! render) is a table of behavior cases and is not reported;
|
|
//! * `mirror`: `assert_eq!(f(a), f(b) <op> …)`, where the expected side derives its value from a
|
|
//! second call of the same function (same path) with arithmetic, so a fault in `f` moves both
|
|
//! sides; builders and conversions (`new`, `from`, `to_string` …) are left out, as are the same
|
|
//! arithmetic on both sides and two reads that differ only in the entry they name (a string or
|
|
//! integer literal, a local or an indexed element);
|
|
//! * `constant-echo`: every assertion of the test compares only constants, literals and enum
|
|
//! variants;
|
|
//! * `fixture-only`: every assertion reads only constants, literals and immutable locals of the
|
|
//! test bound (in scope) to such values, so nothing the code under test returned is checked;
|
|
//! * `never-run`: a test that the `cfg` attributes on it, on the items around it or on the `mod`
|
|
//! declarations above its file leave out of every target CI runs tests on (Linux and FreeBSD on
|
|
//! x86_64, and Windows for the app and the UI crate's print tests). A test that still builds on
|
|
//! macOS or Windows is listed without failing the check: it tests code or behavior of that
|
|
//! platform and runs locally there;
|
|
//! * `exact-pixel`: in a file that uses egui, an assertion that a screen rect (an identifier `rect`,
|
|
//! `rect_…` or `…_rect`, whole or through a corner, edge or size) equals numbers written out.
|
|
//!
|
|
//! 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 <rule> <reason>` 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`, `sleep`,
|
|
//! `reads-source` and `never-run` (except a test that builds on macOS or Windows) in the lines and
|
|
//! tests changed since a base, and lists the other rules' hits there without failing. The base is `--base <rev>` 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, RefCell};
|
|
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,
|
|
Census,
|
|
Mirror,
|
|
ConstantEcho,
|
|
FixtureOnly,
|
|
NeverRun,
|
|
ExactPixel,
|
|
}
|
|
|
|
impl Rule {
|
|
pub const ALL: [Rule; 16] = [
|
|
Rule::AllUnguarded,
|
|
Rule::OnlyWeak,
|
|
Rule::SelfCompare,
|
|
Rule::ExitStatusOnly,
|
|
Rule::NoAssertion,
|
|
Rule::EarlyReturn,
|
|
Rule::IgnoreWithoutReason,
|
|
Rule::EnvGateUnset,
|
|
Rule::Sleep,
|
|
Rule::ReadsSource,
|
|
Rule::Census,
|
|
Rule::Mirror,
|
|
Rule::ConstantEcho,
|
|
Rule::FixtureOnly,
|
|
Rule::NeverRun,
|
|
Rule::ExactPixel,
|
|
];
|
|
|
|
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",
|
|
Rule::Census => "census",
|
|
Rule::Mirror => "mirror",
|
|
Rule::ConstantEcho => "constant-echo",
|
|
Rule::FixtureOnly => "fixture-only",
|
|
Rule::NeverRun => "never-run",
|
|
Rule::ExactPixel => "exact-pixel",
|
|
}
|
|
}
|
|
|
|
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",
|
|
Rule::Census => "test one or a few representative entries and the edge cases (or generate inputs), not every entry of the table",
|
|
Rule::Mirror => "compare with an expected value written out, not with a second call of the same function",
|
|
Rule::ConstantEcho => "assert what the code under test returns, not a constant or literal the test or crate states",
|
|
Rule::FixtureOnly => "assert on what the code under test returns or changes, not on the input the test built",
|
|
Rule::NeverRun => "make the test build on a target CI runs (Linux, FreeBSD), or run it in a CI leg for its target",
|
|
Rule::ExactPixel => {
|
|
"assert relationships (inside its container, not overlapping, order, gap at least a spacing token), not a rect equal to numbers"
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Whether a hit on a changed line fails the command. The other rules only report.
|
|
pub fn fails(self) -> bool {
|
|
matches!(self, Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep | Rule::ReadsSource | Rule::NeverRun)
|
|
}
|
|
|
|
fn from_id(id: &str) -> Option<Rule> {
|
|
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`, through the call's `)` for `reads-source`, 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,
|
|
/// Lines outside `first..=last` that also count as changes to the hit: the enclosing `cfg`
|
|
/// attributes of a `never-run` test, and the loop or spawn statement around a `sleep`. An
|
|
/// allow comment there does not exempt it.
|
|
pub gates: Vec<usize>,
|
|
/// A `never-run` hit on a test that builds on macOS or Windows, which CI does not test on: it is
|
|
/// listed with the report-only rules.
|
|
pub report_only: bool,
|
|
}
|
|
|
|
impl Hit {
|
|
/// Whether the hit fails the check when it is on a changed line.
|
|
fn fails(&self) -> bool {
|
|
self.rule.fails() && !self.report_only
|
|
}
|
|
|
|
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, the variables CI sets, and
|
|
/// the `cfg` predicates each file's module inherits from the `mod` declarations above it.
|
|
#[derive(Default)]
|
|
pub struct Ctx {
|
|
pub helpers: HashMap<String, HashSet<String>>,
|
|
pub ci_env: HashSet<String>,
|
|
pub module_cfgs: HashMap<String, Vec<String>>,
|
|
}
|
|
|
|
/// Whether a parent file's changed lines touch a `mod` declaration or `cfg` attribute that `gates`
|
|
/// came from.
|
|
fn gate_changed(gates: Option<&Gates>, changed: &BTreeMap<String, Option<BTreeSet<usize>>>) -> bool {
|
|
gates
|
|
.into_iter()
|
|
.flat_map(|g| &g.sources)
|
|
.any(|(parent, lines)| changed.get(parent).is_some_and(|c| c.as_ref().is_none_or(|set| lines.iter().any(|l| set.contains(l)))))
|
|
}
|
|
|
|
/// Whether a change touches the declarations that gate the module file `path` now
|
|
/// ([`gate_changed`]), or any file that declared it at the base: an edit there can remove a way for
|
|
/// its tests to run, and the base lines may no longer match.
|
|
fn route_gate_changed(
|
|
path: &str,
|
|
gates: Option<&Gates>,
|
|
base_gates: Option<&Gates>,
|
|
base_overrides: &Overrides,
|
|
changed: &BTreeMap<String, Option<BTreeSet<usize>>>,
|
|
) -> bool {
|
|
gate_changed(gates, changed)
|
|
|| base_gates.is_some_and(|g| g.sources.iter().any(|(parent, _)| changed.contains_key(parent)))
|
|
|| base_overrides.get(path).is_some_and(|routes| routes.iter().any(|(parent, _)| changed.contains_key(parent)))
|
|
}
|
|
|
|
/// A source file read from the work tree, or `None` when it is missing or larger than [`MAX_FILE`].
|
|
fn read_small(root: &Path, path: &str) -> Option<String> {
|
|
let full = root.join(path);
|
|
(std::fs::metadata(&full).ok()?.len() <= MAX_FILE).then(|| std::fs::read_to_string(full).ok()).flatten()
|
|
}
|
|
|
|
/// The scanned files of the tree at `base`, or `None` when Git cannot list it.
|
|
fn base_files(root: &Path, base: &str) -> Option<Vec<String>> {
|
|
let list = git(root, &["ls-tree", "-r", "-z", "--name-only", base]).ok()?;
|
|
Some(list.split('\0').filter(|p| !p.is_empty() && is_scanned(p)).map(str::to_owned).collect())
|
|
}
|
|
|
|
/// Cache successful and missing reads for one source tree.
|
|
fn cached_read(read: impl Fn(&str) -> Option<String>) -> impl Fn(&str) -> Option<String> {
|
|
let cache = RefCell::new(HashMap::<String, Option<String>>::new());
|
|
move |path| cache.borrow_mut().entry(path.to_owned()).or_insert_with(|| read(path)).clone()
|
|
}
|
|
|
|
pub fn run(root: &Path, args: &[&str]) -> Result<(), String> {
|
|
let opts = Options::parse(args)?;
|
|
let read_work = cached_read(|p| read_small(root, p));
|
|
let repo = crate::repo_files(root)?;
|
|
let ci_env = ci_env(root, &repo)?;
|
|
let files: Vec<String> = repo.into_iter().filter(|p| is_scanned(p)).collect();
|
|
if opts.all {
|
|
let sources = read_all(root, &files)?;
|
|
let overrides = with_root_routes(path_overrides(sources.iter().map(|(p, s)| (p.as_str(), s.as_str()))), &files);
|
|
let module_cfgs = module_cfgs(&files, &read_work, &overrides);
|
|
let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs };
|
|
let hits: Vec<Hit> = 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<String, Option<BTreeSet<usize>>> = changed.into_iter().filter(|(p, _)| is_scanned(p)).collect();
|
|
let crates: BTreeSet<String> = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect();
|
|
let helper_files: Vec<String> = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect();
|
|
let present: Vec<String> = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect();
|
|
// Files that load a module through `#[path]`, found with `git grep` (untracked files included)
|
|
// instead of reading the tree, and the target roots beside a shared `tests/<dir>/mod.rs`.
|
|
let overrides = with_root_routes(discover_path_overrides(root, None, &read_work), &files);
|
|
let read_base = cached_read(|p| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE));
|
|
// The base's target roots come from the base tree: a root the change deleted still loaded the
|
|
// shared module beside it.
|
|
let base_overrides =
|
|
with_root_routes(discover_path_overrides(root, Some(&base), &read_base), &base_files(root, &base).unwrap_or_else(|| files.clone()));
|
|
// Files a changed file loads, directly or through other modules: a `cfg` added to their `mod`
|
|
// declaration can turn their tests off without a change to them.
|
|
// Deleted files seed the walk too: a module they loaded at the base may have lost its only CI route.
|
|
let seeds: Vec<String> = changed.keys().cloned().collect();
|
|
let below: Vec<String> =
|
|
descendants(&seeds, &files, &overrides, &base_overrides, &read_work, &read_base).into_iter().filter(|p| !changed.contains_key(p)).collect();
|
|
let gated: Vec<String> = present.iter().chain(&below).cloned().collect();
|
|
let gates = module_gates(&gated, &read_work, &overrides);
|
|
let mut module_cfgs: HashMap<String, Vec<String>> = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect();
|
|
// A file that a crate target loaded at the base and no longer loads is compiled out: `any()`
|
|
// holds on no target.
|
|
let lost = lost_routes(&gated, &read_work, &overrides, &read_base, &base_overrides);
|
|
for path in lost.keys() {
|
|
module_cfgs.insert(path.clone(), vec!["any()".to_owned()]);
|
|
}
|
|
let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs };
|
|
// The gates the parent declarations gave at the base: a parent edit counts against a child's
|
|
// test only when the test ran in CI before it.
|
|
let base_gates = module_gates(&gated, &read_base, &base_overrides);
|
|
let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect();
|
|
let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs };
|
|
// The base's `never-run` hits on the file as it was at the base (the current source when the
|
|
// file is new or moved), computed once per file on its first parent-attributed hit.
|
|
let base_off: RefCell<HashMap<String, (String, Vec<Hit>)>> = RefCell::new(HashMap::new());
|
|
let newly_off = |path: &str, src: &str, hit: &Hit| {
|
|
let mut cache = base_off.borrow_mut();
|
|
let (base_src, off) = cache.entry(path.to_owned()).or_insert_with(|| {
|
|
let base_src = read_base(path).unwrap_or_else(|| src.to_owned());
|
|
let off = lint_file(path, &base_src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).collect();
|
|
(base_src, off)
|
|
});
|
|
!already_off(off, base_src, src, hit)
|
|
};
|
|
let route_changed = |path: &str| {
|
|
route_gate_changed(path, gates.get(path), base_gates.get(path), &base_overrides, &changed)
|
|
|| lost.get(path).is_some_and(|parents| parents.iter().any(|p| changed.contains_key(p)))
|
|
};
|
|
let (mut counted, mut older) = (vec![], 0usize);
|
|
for (path, src) in read_all(root, &present)? {
|
|
let parent_changed = route_changed(&path);
|
|
for hit in lint_file(&path, &src, &ctx) {
|
|
if touches(&hit, changed.get(&path).and_then(Option::as_ref))
|
|
|| (hit.rule == Rule::NeverRun && parent_changed && newly_off(&path, &src, &hit))
|
|
{
|
|
counted.push(hit);
|
|
} else {
|
|
older += 1;
|
|
}
|
|
}
|
|
}
|
|
for path in below.iter().filter(|p| route_changed(p)) {
|
|
let Some(src) = read_work(path) else { continue };
|
|
counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h)));
|
|
}
|
|
finish(&counted, older, present.len(), &base)
|
|
}
|
|
|
|
/// Whether `base`, the hits of `base_src` under the base's gates, has a `never-run` hit for the test
|
|
/// of `hit` in `src`. A test is matched by its name, the inline modules around it and its place
|
|
/// among the tests of that name in those modules, so lines that moved still match and tests of one
|
|
/// name in different inline modules stay apart, even when a change removes one of the modules.
|
|
fn already_off(base: &[Hit], base_src: &str, src: &str, hit: &Hit) -> bool {
|
|
let place = test_place(src, &hit.test, hit.line);
|
|
base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test).any(|h| match &place {
|
|
Some(place) => test_place(base_src, &h.test, h.line).as_ref() == Some(place),
|
|
None => h.line == hit.line,
|
|
})
|
|
}
|
|
|
|
/// The inline modules around the test `name` whose `fn` is on `line` in `src` (outermost first),
|
|
/// and its index among the tests of that name in the same modules.
|
|
fn test_place(src: &str, name: &str, line: usize) -> Option<(Vec<String>, usize)> {
|
|
let lines = Lines::new(src);
|
|
let m = mask(src);
|
|
let named: Vec<(Vec<String>, usize)> =
|
|
tests_in(&m).iter().filter(|t| t.name == name).map(|t| (inline_modules(&m, t.fn_at), lines.of(t.fn_at))).collect();
|
|
let (scope, _) = named.iter().find(|(_, l)| *l == line)?;
|
|
let index = named.iter().filter(|(s, _)| s == scope).position(|(_, l)| *l == line)?;
|
|
Some((scope.clone(), index))
|
|
}
|
|
|
|
/// The names of the inline `mod <name> { … }` blocks around `at` in the masked text `m`, outermost
|
|
/// first.
|
|
fn inline_modules(m: &[u8], at: usize) -> Vec<String> {
|
|
let mut open: Vec<Option<String>> = vec![];
|
|
for (i, &c) in m.iter().enumerate().take(at) {
|
|
match c {
|
|
b'{' => {
|
|
let head = m[..i].trim_ascii_end();
|
|
let name = head.iter().rev().take_while(|&&c| is_ident(c)).count();
|
|
let before = head[..head.len() - name].trim_ascii_end();
|
|
let keyword = name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident);
|
|
open.push(keyword.then(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned()));
|
|
}
|
|
b'}' => {
|
|
open.pop();
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
open.into_iter().flatten().collect()
|
|
}
|
|
|
|
/// The directory holding the modules that the file `p` declares by name: its own directory for
|
|
/// `mod.rs`, `lib.rs`, `main.rs` and crate roots ([`owns_its_dir`]), and the directory named after
|
|
/// it otherwise.
|
|
fn module_dir(p: &str) -> String {
|
|
let dir = p.rsplit_once('/').map_or("", |(d, _)| d);
|
|
if owns_its_dir(p) { format!("{dir}/") } else { format!("{}/", p.trim_end_matches(".rs")) }
|
|
}
|
|
|
|
/// The files of `files` that the files `start` load, directly or through modules in between: the
|
|
/// files under their module directories and the files their current or base `#[path]` declarations load.
|
|
/// A file loaded through `#[path]` also loads the modules it declares by name from its own directory
|
|
/// (`mod child;` in `impl/platform.rs` loads `impl/child.rs`), read through `read` and, for the
|
|
/// declarations a change removed, through `read_base`.
|
|
fn descendants(
|
|
start: &[String],
|
|
files: &[String],
|
|
overrides: &Overrides,
|
|
base_overrides: &Overrides,
|
|
read: &dyn Fn(&str) -> Option<String>,
|
|
read_base: &dyn Fn(&str) -> Option<String>,
|
|
) -> Vec<String> {
|
|
let mut seen: BTreeSet<String> = start.iter().cloned().collect();
|
|
let mut frontier: Vec<String> = start.to_vec();
|
|
let mut out = vec![];
|
|
while !frontier.is_empty() {
|
|
let beside = |p: &String| -> Vec<String> {
|
|
if owns_its_dir(p) || !(overrides.contains_key(p) || base_overrides.contains_key(p)) {
|
|
return vec![];
|
|
}
|
|
let dir = p.rsplit_once('/').map_or("", |(d, _)| d);
|
|
[read(p), read_base(p)]
|
|
.into_iter()
|
|
.flatten()
|
|
.flat_map(|src| declared_names(&src))
|
|
.flat_map(|n| [format!("{dir}/{n}.rs"), format!("{dir}/{n}/")])
|
|
.collect()
|
|
};
|
|
let dirs: Vec<String> = frontier.iter().map(|p| module_dir(p)).chain(frontier.iter().flat_map(beside)).collect();
|
|
let next: Vec<String> = files
|
|
.iter()
|
|
.filter(|p| !seen.contains(*p))
|
|
.filter(|p| {
|
|
dirs.iter().any(|d| p.starts_with(d.as_str()))
|
|
|| overrides.get(*p).into_iter().chain(base_overrides.get(*p)).flatten().any(|(parent, _)| frontier.contains(parent))
|
|
})
|
|
.cloned()
|
|
.collect();
|
|
seen.extend(next.iter().cloned());
|
|
out.extend(next.iter().cloned());
|
|
frontier = next;
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The names of the modules `src` declares, by file (`mod child;`) or inline (`mod platform { … }`).
|
|
fn declared_names(src: &str) -> Vec<String> {
|
|
let m = mask(src);
|
|
words(&m, b"mod", 0, m.len())
|
|
.into_iter()
|
|
.filter_map(|at| {
|
|
let start = skip_ws(&m, at + 3);
|
|
let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count();
|
|
(end > start && matches!(m.get(skip_ws(&m, end)), Some(b';' | b'{'))).then(|| String::from_utf8_lossy(&m[start..end]).into_owned())
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// The command line: `--all`, `--base <rev>`.
|
|
#[derive(Debug, Default, PartialEq)]
|
|
struct Options {
|
|
all: bool,
|
|
base: Option<String>,
|
|
}
|
|
|
|
impl Options {
|
|
fn parse(args: &[&str]) -> Result<Options, String> {
|
|
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 <rev>])")),
|
|
}
|
|
}
|
|
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.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}<rule> <reason>`):\n {}",
|
|
failing.len(),
|
|
listing(&failing).join("\n ")
|
|
))
|
|
}
|
|
|
|
/// Each hit, then the advice for each rule they break.
|
|
fn listing(hits: &[&Hit]) -> Vec<String> {
|
|
let mut out: Vec<String> = hits.iter().map(|h| h.show()).collect();
|
|
let rules: BTreeSet<Rule> = 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<String, BTreeMap<Rule, usize>> = 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<String> = 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/<name>` or `apps/<name>` 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<Vec<(String, String)>, 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<String, String> {
|
|
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<String>) -> Result<String, String> {
|
|
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 <rev> 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<BTreeMap<String, Option<BTreeSet<usize>>>, String> {
|
|
let diff = git(
|
|
root,
|
|
&[
|
|
"-c",
|
|
"core.quotepath=off",
|
|
"diff",
|
|
"-U0",
|
|
"--inter-hunk-context=0",
|
|
"--no-color",
|
|
"--no-ext-diff",
|
|
// A rename shows as a deletion and an addition, so both paths count as changed.
|
|
"--no-renames",
|
|
"--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<String, Option<BTreeSet<usize>>> {
|
|
let mut out: BTreeMap<String, Option<BTreeSet<usize>>> = BTreeMap::new();
|
|
let mut current: Option<String> = 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);
|
|
let mut old: Option<String> = None;
|
|
for line in diff.lines() {
|
|
if line.starts_with("diff --git ") {
|
|
(header, new_file, old) = (true, false, None);
|
|
} else if header && line.starts_with("new file mode") {
|
|
new_file = true;
|
|
} else if let Some(path) = line.strip_prefix("--- ").filter(|_| header) {
|
|
old = patch_path(path).and_then(|p| p.strip_prefix("a/").map(str::to_owned));
|
|
} else if let Some(path) = line.strip_prefix("+++ ").filter(|_| header) {
|
|
current = patch_path(path).and_then(|p| p.strip_prefix("b/").map(str::to_owned));
|
|
if let Some(p) = ¤t {
|
|
out.insert(p.clone(), if new_file { None } else { Some(BTreeSet::new()) });
|
|
} else if let Some(p) = old.take().filter(|_| path == "/dev/null") {
|
|
// A deleted file is kept, wholly changed: it may have been a route that loaded a module.
|
|
out.insert(p, None);
|
|
}
|
|
} 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<String> {
|
|
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<usize>>) -> bool {
|
|
changed.is_none_or(|lines| lines.range(hit.first..=hit.last).next().is_some() || hit.gates.iter().any(|l| lines.contains(l)))
|
|
}
|
|
|
|
// ---- What CI sets ----
|
|
|
|
fn ci_env(root: &Path, files: &[String]) -> Result<HashSet<String>, String> {
|
|
let mut names: HashSet<String> = 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<Item = String> + '_ {
|
|
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<u8> {
|
|
mask_with(src, true)
|
|
}
|
|
|
|
/// [`mask`], keeping comments when `comments` is false.
|
|
fn mask_with(src: &str, comments: bool) -> Vec<u8> {
|
|
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<u8> {
|
|
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<u8> = 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<usize> {
|
|
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<usize> {
|
|
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<usize> {
|
|
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::<Vec<u8>>()).into_owned()
|
|
}
|
|
|
|
/// [`norm`], except that whitespace between two identifier characters becomes one space, so
|
|
/// `k as usize` stays three words and `kasusize` stays one. Removing the spaces gives [`norm`].
|
|
fn norm_words(b: &[u8]) -> String {
|
|
let mut out = vec![];
|
|
let mut gap = false;
|
|
for &c in b {
|
|
if c.is_ascii_whitespace() {
|
|
gap = true;
|
|
continue;
|
|
}
|
|
if gap && is_ident(c) && out.last().copied().is_some_and(is_ident) {
|
|
out.push(b' ');
|
|
}
|
|
gap = false;
|
|
out.push(c);
|
|
}
|
|
String::from_utf8_lossy(&out).into_owned()
|
|
}
|
|
|
|
/// Line starts, to turn byte offsets into 1-based lines.
|
|
struct Lines(Vec<usize>);
|
|
|
|
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<TestFn> {
|
|
let mut out: Vec<TestFn> = 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<TestFn> {
|
|
// 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<MacroCall> {
|
|
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)> {
|
|
calls_at(m, from, to).into_iter().map(|(_, name, method)| (name, method)).collect()
|
|
}
|
|
|
|
/// [`calls`] with the index where each name starts.
|
|
fn calls_at(m: &[u8], from: usize, to: usize) -> Vec<(usize, 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((i, 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<String>) -> 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!") || rejects(body) || 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<u8> = 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<String>);
|
|
|
|
/// 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<String, HashSet<String>> {
|
|
let mut defs: HashMap<String, Vec<Def>> = 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<Item = &'a Def> + Clone) -> HashSet<String> {
|
|
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<String> = HashSet::new();
|
|
loop {
|
|
let checks = |d: &Def| d.1 || d.2.iter().any(|c| known.contains(c));
|
|
let more: Vec<String> = 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<Def> {
|
|
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<u8>,
|
|
/// [`File::m`] with the functions and macros declared inside each test blanked: declaring
|
|
/// one does not run its body ([`executed`]).
|
|
exec: Vec<u8>,
|
|
lines: Lines,
|
|
tests: Vec<TestFn>,
|
|
/// The test code ([`test_regions`]).
|
|
regions: Vec<(usize, usize)>,
|
|
/// The `cfg` attributes and the items they cover ([`cfg_spans`]).
|
|
cfgs: Vec<CfgSpan>,
|
|
}
|
|
|
|
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, gates: vec![], report_only: false }
|
|
}
|
|
|
|
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<Hit> {
|
|
let m = mask(src);
|
|
let tests = tests_in(&m);
|
|
let regions = test_regions(path, &m, &tests);
|
|
let exec = executed(&m, &tests);
|
|
let cfgs = cfg_spans(&m, src.as_bytes());
|
|
let file = File { path, src: src.as_bytes(), m, exec, lines: Lines::new(src), tests, regions, cfgs };
|
|
let mut hits: Vec<Hit> = 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<u8> {
|
|
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<MacroCall>,
|
|
delegates: bool,
|
|
checks: bool,
|
|
should_panic: bool,
|
|
}
|
|
|
|
fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec<Hit> {
|
|
let m = &file.exec;
|
|
let asserts: Vec<MacroCall> = 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(census(&v, helpers));
|
|
hits.extend(mirrors(&v));
|
|
hits.extend(exact_pixels(&v));
|
|
hits.extend([only_weak(&v), exit_status_only(&v), no_assertion(&v), echoes(&v), never_run(&v, ctx)].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<u8> {
|
|
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<Hit> {
|
|
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()
|
|
}
|
|
|
|
/// A loop over a whole table (`for x in TABLE`, `for c in Color::ALL`, `assert!(presets().iter().all(…))`)
|
|
/// whose assertions only check presence, non-emptiness or a round trip.
|
|
fn census(v: &View, helpers: &HashSet<String>) -> Vec<Hit> {
|
|
let m = &v.file.exec;
|
|
// Failure messages run only after an assertion has failed, so a check there does not count.
|
|
let unmessaged = v.body_without_messages();
|
|
let helpers_in = |from: usize, to: usize| -> Vec<String> {
|
|
calls(&unmessaged, from - v.t.open, to - v.t.open)
|
|
.into_iter()
|
|
.filter(|(n, method)| !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers))
|
|
.map(|(n, _)| n)
|
|
.collect()
|
|
};
|
|
let weak_in = |from: usize, to: usize, var: &str| {
|
|
let inside: Vec<&MacroCall> = v.asserts.iter().filter(|a| a.at > from && a.at < to).collect();
|
|
let body = &unmessaged[from - v.t.open..to - v.t.open];
|
|
// A helper counts only where it runs whenever the assertions pass, not after an `||`.
|
|
let (f, t) = (from + 1 - v.t.open, to - v.t.open);
|
|
let helper_runs = calls_at(&unmessaged, f, t).into_iter().any(|(at, n, method)| {
|
|
!(n.ends_with('!') && is_assert_macro(&n)) && is_helper_call(&n, method, helpers) && runs_with_assertion(&unmessaged, f, t, at)
|
|
});
|
|
!helper_runs
|
|
&& !rejects(body)
|
|
&& !inside.is_empty()
|
|
&& inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm_words(&m[f..t])).collect::<Vec<_>>(), var))
|
|
};
|
|
for at in words(m, b"for", v.t.open, v.t.close) {
|
|
let Some(&kw) = words(m, b"in", at, v.t.close).first() else { continue };
|
|
let Some(open) = loop_open(m, kw + 2, v.t.close) else { continue };
|
|
let Some(close) = matching(m, open) else { continue };
|
|
let pattern = String::from_utf8_lossy(&m[at + 3..kw]);
|
|
let var = pattern.split_whitespace().last().unwrap_or("").trim_start_matches('&');
|
|
// A `break` in the body can end the loop before it reaches every entry.
|
|
// An asserting helper in the loop source runs for every entry, like one in the body.
|
|
if whole_table(&norm(&m[kw + 2..open]))
|
|
&& helpers_in(kw + 2, open).is_empty()
|
|
&& words(m, b"break", open, close).is_empty()
|
|
&& weak_in(open, close, var)
|
|
&& !feeds_entry(&unmessaged, &pattern, open + 1 - v.t.open, close - v.t.open)
|
|
{
|
|
return vec![v.whole(Rule::Census, "loops over every entry of a table and checks only presence or a round trip".into())];
|
|
}
|
|
}
|
|
for a in v.asserts.iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())) {
|
|
let called = a.args.first().map(|&(f, t)| helpers_in(f, t)).unwrap_or_default();
|
|
if census_condition(&v.first_arg(a), 0, &called) == (true, true) {
|
|
return vec![v.whole(Rule::Census, "checks .all(…) over every entry of a table for presence only".into())];
|
|
}
|
|
}
|
|
vec![]
|
|
}
|
|
|
|
/// Calls that read or look up a value rather than compute one, so passing the entry to one of them
|
|
/// together with other state does not make the loop a behavior table.
|
|
const LOOKUPS: &[&str] = &[
|
|
"contains",
|
|
"contains_key",
|
|
"starts_with",
|
|
"ends_with",
|
|
"get",
|
|
"get_mut",
|
|
"iter",
|
|
"into_iter",
|
|
"any",
|
|
"find",
|
|
"position",
|
|
"binary_search",
|
|
"eq",
|
|
"ne",
|
|
"find_map",
|
|
];
|
|
|
|
/// The lowercase names a `for` or `let` pattern binds. A field label (`Row { c: other }`) binds
|
|
/// the name after it.
|
|
fn pattern_names(pattern: &str) -> impl Iterator<Item = String> + '_ {
|
|
let b = pattern.as_bytes();
|
|
pattern
|
|
.match_indices(|c: char| c.is_ascii_alphanumeric() || c == '_')
|
|
.filter(move |&(at, _)| at == 0 || !is_ident(b[at - 1]))
|
|
.map(move |(at, _)| (at, at + b[at..].iter().take_while(|&&c| is_ident(c)).count()))
|
|
.filter(move |&(at, end)| {
|
|
// Inside braces, `name:` labels a field; outside them it starts a type (`let x: u32`).
|
|
let in_braces = b[..at].iter().filter(|&&c| c == b'{').count() > b[..at].iter().filter(|&&c| c == b'}').count();
|
|
let next = end + b[end..].iter().take_while(|c| c.is_ascii_whitespace()).count();
|
|
!in_braces || b.get(next) != Some(&b':') || b.get(next + 1) == Some(&b':')
|
|
})
|
|
.map(move |(at, end)| &pattern[at..end])
|
|
.filter(|w| !matches!(*w, "" | "_" | "mut" | "ref") && w.starts_with(|c: char| c.is_ascii_lowercase() || c == '_'))
|
|
.map(str::to_owned)
|
|
}
|
|
|
|
/// Whether the body `b[from..to]` of a loop whose pattern is `pattern` feeds the entry into a
|
|
/// computation with other inputs: a call (not one of [`LOOKUPS`], nor a macro) whose receiver and
|
|
/// arguments include a value read from the entry and another value that is not a literal, such as
|
|
/// `app.run("…", json!({"id": id}))`, `export(&doc, &Options { level, .. })` or `check(SCHEMA, ¶ms)`
|
|
/// with `params` bound from the entry inside the loop. Such a loop runs, renders or writes something
|
|
/// for each entry, so it is a table of behavior cases. A call that takes the entry alone (`menu(c)`,
|
|
/// `Kind::from_id(k.id())`) is still a lookup.
|
|
fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool {
|
|
// The names that hold the entry, each from the end of its binding to the end of its block.
|
|
let mut derived: Vec<(String, usize, usize)> = pattern_names(pattern).map(|n| (n, from, to)).collect();
|
|
// Where a binding does not read the entry, the name holds another value until its scope ends.
|
|
let mut shadows: Vec<(String, usize, usize)> = vec![];
|
|
for at in words(b, b"for", from, to) {
|
|
let Some(&kw) = words(b, b"in", at + 3, to).first() else { continue };
|
|
let Some(open) = loop_open(b, kw + 2, to) else { continue };
|
|
let Some(close) = matching(b, open).filter(|&c| c < to) else { continue };
|
|
shadows.extend(pattern_names(&String::from_utf8_lossy(&b[at + 3..kw])).map(|n| (n, open + 1, close)));
|
|
}
|
|
// Simple closure parameters shadow captures in both block and expression bodies.
|
|
for at in from..to {
|
|
if b[at] != b'|' || b.get(at + 1) == Some(&b'|') {
|
|
continue;
|
|
}
|
|
let head = b[from..at].trim_ascii_end();
|
|
let head = head.strip_suffix(b"move").unwrap_or(head).trim_ascii_end();
|
|
if !head.is_empty() && !matches!(head.last(), Some(b'=' | b'(' | b',' | b'{' | b';')) {
|
|
continue;
|
|
}
|
|
let Some(end) = (at + 1..to).find(|&i| b[i] == b'|') else { continue };
|
|
// Parameters may carry types (`|c: Command|`, `|p: &[u8]|`).
|
|
if !b[at + 1..end]
|
|
.iter()
|
|
.all(|&c| is_ident(c) || c.is_ascii_whitespace() || matches!(c, b',' | b'&' | b':' | b'<' | b'>' | b'(' | b')' | b'[' | b']' | b'\''))
|
|
{
|
|
continue;
|
|
}
|
|
let mut until = skip_ws(b, end + 1);
|
|
if b.get(until) == Some(&b'{') {
|
|
until = matching(b, until).unwrap_or(to).min(to);
|
|
} else {
|
|
while until < to && !matches!(b[until], b',' | b';' | b')' | b']' | b'}') {
|
|
until = if matches!(b[until], b'(' | b'[' | b'{') { matching(b, until).unwrap_or(to) + 1 } else { until + 1 };
|
|
}
|
|
}
|
|
// Each parameter binds the names before its type.
|
|
let params = String::from_utf8_lossy(&b[at + 1..end]).into_owned();
|
|
let names: Vec<String> = params.split(',').flat_map(|p| pattern_names(p.split(':').next().unwrap_or_default()).collect::<Vec<_>>()).collect();
|
|
shadows.extend(names.into_iter().map(|n| (n, at + 1, until)));
|
|
}
|
|
// A field access (`options.c`), a path segment (`defaults::c`) or a field label (`Row { c: x }`)
|
|
// names a field or an item, not the binding.
|
|
let is_field = |at: usize, len: usize| {
|
|
b[..at].trim_ascii_end().last() == Some(&b'.') || b[..at].trim_ascii_end().ends_with(b"::") || {
|
|
let next = skip_ws(b, at + len);
|
|
b.get(next) == Some(&b':') && b.get(next + 1) != Some(&b':')
|
|
}
|
|
};
|
|
let live = |f: usize, t: usize, names: &[(String, usize, usize)], shadows: &[(String, usize, usize)]| {
|
|
names.iter().any(|(n, since, until)| {
|
|
words(b, n.as_bytes(), f.max(*since), t.min(*until))
|
|
.into_iter()
|
|
.any(|at| !is_field(at, n.len()) && !shadows.iter().any(|(s, a, z)| s == n && *a <= at && at < *z))
|
|
})
|
|
};
|
|
// Names bound inside the loop from the entry count as the entry.
|
|
for at in words(b, b"let", from, to) {
|
|
let Some(eq) =
|
|
(at + 3..to).find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>'))
|
|
else {
|
|
continue;
|
|
};
|
|
// `if let` and `while let` end their initializer at the conditional's block.
|
|
let conditional = [b"if".as_slice(), b"while"].iter().any(|kw| b[from..at].trim_ascii_end().ends_with(kw));
|
|
let end = if conditional { (eq..to).find(|&i| b[i] == b'{').unwrap_or(to) } else { statement_end(&b[..to], eq) };
|
|
// A block initializer binds the value of its tail (`{ prepare(); c }`).
|
|
let mut value = eq + 1;
|
|
let init = skip_ws(b, value);
|
|
if !conditional && b.get(init) == Some(&b'{') && matching(b, init).is_some_and(|close| b[close + 1..end].trim_ascii().is_empty()) {
|
|
let close = matching(b, init).unwrap_or(end);
|
|
let mut i = init + 1;
|
|
value = i;
|
|
while i < close {
|
|
match b[i] {
|
|
b'(' | b'[' | b'{' => i = matching(b, i).unwrap_or(close),
|
|
b';' => value = i + 1,
|
|
_ => {}
|
|
}
|
|
i += 1;
|
|
}
|
|
}
|
|
let names: Vec<String> = pattern_names(&String::from_utf8_lossy(&b[at + 3..eq])).collect();
|
|
if live(value, end, &derived, &shadows) {
|
|
// Rebinding from the entry suspends earlier shadows until this block ends.
|
|
let until = block_close(b, at).min(to);
|
|
let mut resumed = vec![];
|
|
for s in shadows.iter_mut().filter(|s| names.contains(&s.0) && s.1 <= at && at < s.2) {
|
|
if until < s.2 {
|
|
resumed.push((s.0.clone(), until, s.2));
|
|
}
|
|
s.2 = end;
|
|
}
|
|
shadows.extend(resumed);
|
|
derived.extend(names.into_iter().map(|n| (n, end, until)));
|
|
} else {
|
|
let until = block_close(b, at).min(to);
|
|
shadows.extend(names.into_iter().filter(|n| derived.iter().any(|(d, _, _)| d == n)).map(|n| (n, end, until)));
|
|
}
|
|
}
|
|
let reads = |f: usize, t: usize| live(f, t, &derived, &shadows);
|
|
let literal = |s: &[u8]| {
|
|
let s = norm(s);
|
|
let s = s.trim_start_matches(['&', '*']);
|
|
// String, byte and raw literals keep their prefix after masking (`r"…"`, `b'…'`, `br#"…"#`).
|
|
let s = match s.find(['"', '\'']) {
|
|
Some(q) if q <= 3 && s[..q].bytes().all(|c| matches!(c, b'b' | b'c' | b'r' | b'#')) => &s[q..],
|
|
_ => s,
|
|
};
|
|
// A closure only shapes the call on the entry (`.map(|x| …)`); it is not another input.
|
|
// A minus sign makes a literal only in front of a number (`-2`, not `-offset`).
|
|
let s = s.strip_prefix('-').unwrap_or(s);
|
|
let mut start = 0;
|
|
let mut operands = 0;
|
|
let mut numeric = true;
|
|
for (i, c) in s.char_indices().chain([(s.len(), '+')]) {
|
|
let range = c == '.' && (s.as_bytes().get(i + 1) == Some(&b'.') || s[..i].ends_with('.')) || c == '=' && s[..i].ends_with("..");
|
|
if !range && !matches!(c, '+' | '-' | '*' | '/' | '%' | '<' | '>' | '&' | '|' | '^' | '(' | ')') {
|
|
continue;
|
|
}
|
|
let head = &s[start..i];
|
|
if i < s.len()
|
|
&& matches!(c, '+' | '-')
|
|
&& head
|
|
.strip_suffix(['e', 'E'])
|
|
.is_some_and(|n| n.starts_with(|c: char| c.is_ascii_digit()) && n.bytes().all(|c| c.is_ascii_digit() || matches!(c, b'_' | b'.')))
|
|
{
|
|
continue;
|
|
}
|
|
if !head.is_empty() {
|
|
operands += 1;
|
|
numeric &= numeric_literal(head);
|
|
}
|
|
start = i + c.len_utf8();
|
|
}
|
|
let numeric = numeric && operands > 0;
|
|
s.is_empty() || s.starts_with(['"', '\'', '|']) || s.starts_with("move|") || numeric || matches!(s, "true" | "false" | "None")
|
|
};
|
|
(from..to).filter_map(|i| (b[i] == b'(' && i > from).then(|| call_name_end(b, from, i)).flatten().map(|e| (i, e))).any(|(open, name_end)| {
|
|
let mut start = name_end;
|
|
while start > from && is_ident(b[start - 1]) {
|
|
start -= 1;
|
|
}
|
|
let name = String::from_utf8_lossy(&b[start..name_end]);
|
|
if start == name_end || LOOKUPS.contains(&name.as_ref()) || b[start].is_ascii_digit() || !runs_with_assertion(b, from, to, start) {
|
|
return false;
|
|
}
|
|
let Some(close) = matching(b, open).filter(|&c| c < to) else { return false };
|
|
let args = split_args(b, open + 1, close);
|
|
let mut inputs = args.clone();
|
|
if start > from && b[start - 1] == b'.' {
|
|
// The receiver: the chain of names, calls and indexing before the dot.
|
|
let mut r = start - 1;
|
|
while r > from {
|
|
match b[r - 1] {
|
|
c if is_ident(c) || c == b'.' => r -= 1,
|
|
// A chain rustfmt splits over lines continues with a `.` after the line break.
|
|
c if c.is_ascii_whitespace() && b[r..start].iter().find(|c| !c.is_ascii_whitespace()) == Some(&b'.') => r -= 1,
|
|
b')' | b']' => match (from..r - 1).rev().find(|&o| matching(b, o) == Some(r - 1)) {
|
|
Some(o) => r = o,
|
|
None => break,
|
|
},
|
|
_ => break,
|
|
}
|
|
}
|
|
inputs.push((r, start - 1));
|
|
}
|
|
let fed = inputs.iter().any(|&(f, t)| reads(f, t));
|
|
// A lookup or parse on a table (`registry.lookup(k)`) takes the table as its receiver; only
|
|
// another argument (`u.parse(&text)`) makes it a computation.
|
|
let others = if ROUND_TRIP.contains(&name.as_ref()) { &args } else { &inputs };
|
|
let other = others.iter().any(|&(f, t)| !literal(&b[f..t]) && !reads(f, t));
|
|
fed && other
|
|
})
|
|
}
|
|
|
|
/// Whether the whitespace-free `s` is one numeric literal (`1`, `0x1F`, `2.5f32`, `1_000`, `1e-3`), not
|
|
/// an expression that starts with one (`1+offset`, `1..limit`).
|
|
fn numeric_literal(s: &str) -> bool {
|
|
let b = s.as_bytes();
|
|
let radix = match b.get(..2) {
|
|
Some(b"0x") => 16,
|
|
Some(b"0o") => 8,
|
|
Some(b"0b") => 2,
|
|
_ => 10,
|
|
};
|
|
let mut i = if radix == 10 { 0 } else { 2 };
|
|
let mut digits = 0;
|
|
while let Some(&c) = b.get(i) {
|
|
if (c as char).is_digit(radix) {
|
|
digits += 1;
|
|
} else if c != b'_' {
|
|
break;
|
|
}
|
|
i += 1;
|
|
}
|
|
if digits == 0 || !b.first().is_some_and(u8::is_ascii_digit) {
|
|
return false;
|
|
}
|
|
if radix == 10 {
|
|
if b.get(i) == Some(&b'.') {
|
|
i += 1;
|
|
if i < b.len() && !b[i].is_ascii_digit() {
|
|
return false;
|
|
}
|
|
while b.get(i).is_some_and(|c| c.is_ascii_digit() || *c == b'_') {
|
|
i += 1;
|
|
}
|
|
}
|
|
if matches!(b.get(i), Some(b'e' | b'E')) {
|
|
i += 1;
|
|
if matches!(b.get(i), Some(b'+' | b'-')) {
|
|
i += 1;
|
|
}
|
|
let mut digits = 0;
|
|
while let Some(&c) = b.get(i) {
|
|
if c.is_ascii_digit() {
|
|
digits += 1;
|
|
} else if c != b'_' {
|
|
break;
|
|
}
|
|
i += 1;
|
|
}
|
|
if digits == 0 {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
matches!(&s[i..], "" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "f32" | "f64")
|
|
}
|
|
|
|
/// Where the name of a call whose `(` is at `open` ends: right before the `(`, or before the
|
|
/// `::<…>` of a turbofish (`app.run::<Mode>(c)`). `None` when no name precedes the `(`.
|
|
fn call_name_end(b: &[u8], from: usize, open: usize) -> Option<usize> {
|
|
// Masked comments leave spaces between the name and the `(` (`app.run /* note */ (c)`).
|
|
let before = from + b[from..open].trim_ascii_end().len();
|
|
if before > from && is_ident(b[before - 1]) {
|
|
// A keyword before a parenthesized expression (`if (a)`, `return (x)`) is not a call.
|
|
let mut start = before;
|
|
while start > from && is_ident(b[start - 1]) {
|
|
start -= 1;
|
|
}
|
|
const KEYWORDS: [&[u8]; 15] =
|
|
[b"if", b"else", b"match", b"while", b"for", b"in", b"return", b"break", b"let", b"mut", b"move", b"async", b"await", b"as", b"loop"];
|
|
let keyword = KEYWORDS.contains(&&b[start..before]);
|
|
return (before == open || !keyword).then_some(before);
|
|
}
|
|
if before == from || b[before - 1] != b'>' {
|
|
return None;
|
|
}
|
|
let mut depth = 0usize;
|
|
for i in (from..before).rev() {
|
|
match b[i] {
|
|
b'>' if i == 0 || b[i - 1] != b'-' => depth += 1,
|
|
b'<' => {
|
|
depth = depth.checked_sub(1)?;
|
|
if depth == 0 {
|
|
let head = b[from..i].trim_ascii_end();
|
|
let end = head.strip_suffix(b"::")?.trim_ascii_end().len();
|
|
return (end > 0 && is_ident(b[from + end - 1])).then_some(from + end);
|
|
}
|
|
}
|
|
b';' | b'{' | b'}' => return None,
|
|
_ => {}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// Whether a call starting at `start` in the loop body `b[from..to]` runs whenever the loop's
|
|
/// assertions pass. A call after `||` in its statement may not run (`menu(c).is_some() || app.run(c)`,
|
|
/// also with a block as the right operand); the right side of `&&` has to run only in an asserted
|
|
/// condition. A call inside a closure bound with `let` runs only when the loop calls
|
|
/// that closure.
|
|
fn runs_with_assertion(b: &[u8], from: usize, to: usize, start: usize) -> bool {
|
|
runs_with_assertion_within(b, from, to, start, &[])
|
|
}
|
|
|
|
/// [`runs_with_assertion`], where `active` holds the calls whose check is in progress, so a closure
|
|
/// that calls itself does not recurse without end.
|
|
fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool {
|
|
if active.contains(&start) {
|
|
return false;
|
|
}
|
|
let mut active = active.to_vec();
|
|
active.push(start);
|
|
if in_uncalled_closure(b, from, to, start, &active) {
|
|
return false;
|
|
}
|
|
// Check enclosing blocks independently of the call's statement: an earlier semicolon inside
|
|
// a conditional block does not make its later statements run unconditionally.
|
|
for open in (from..start).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)) {
|
|
let mut head = open;
|
|
while head > from {
|
|
head -= 1;
|
|
match b[head] {
|
|
b')' | b']' => {
|
|
let Some(back) = (from..head).rev().find(|&i| matching(b, i) == Some(head)) else { return false };
|
|
head = back;
|
|
}
|
|
b';' | b'{' | b'}' => {
|
|
head += 1;
|
|
break;
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
let prefix = b[head..open].trim_ascii();
|
|
if prefix.ends_with(b"||") || prefix.ends_with(b"&&") {
|
|
if !runs_with_assertion_within(b, from, to, open, &active) {
|
|
return false;
|
|
}
|
|
} else if !prefix.ends_with(b"|")
|
|
&& !(prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace))
|
|
&& (prefix.ends_with(b"=>")
|
|
|| [b"async".as_slice(), b"async move"]
|
|
.iter()
|
|
.any(|kw| prefix.ends_with(kw) && !prefix[..prefix.len() - kw.len()].last().copied().is_some_and(is_ident))
|
|
|| [b"if".as_slice(), b"else", b"match", b"while"].iter().any(|kw| !words(prefix, kw, 0, prefix.len()).is_empty())
|
|
|| (!words(prefix, b"loop", 0, prefix.len()).is_empty()
|
|
&& matching(b, open).is_some_and(|close| !words(b, b"break", open + 1, close).is_empty())))
|
|
{
|
|
// A nested `for` body is taken to run, like the loop body itself; [`feeds_entry`] keeps
|
|
// its own bindings apart.
|
|
return false;
|
|
}
|
|
}
|
|
// The statement starts after a `;` or an unmatched brace, except for the `{` of a block that is
|
|
// the operand of `||` or `&&`.
|
|
let mut stmt = from;
|
|
let mut braces = 0usize;
|
|
for i in (from..start).rev() {
|
|
match b[i] {
|
|
// A block that ends before the call closes an earlier statement (`if a || b {} app.run(c)`)
|
|
// unless an operator joins the call's expression to it.
|
|
b'}' if braces == 0 && {
|
|
let after = b[i + 1..start].trim_ascii_start();
|
|
!(after.starts_with(b"||") || after.starts_with(b"&&") || after.starts_with(b".") || after.starts_with(b"?"))
|
|
} =>
|
|
{
|
|
stmt = i + 1;
|
|
break;
|
|
}
|
|
b'}' => braces += 1,
|
|
b'{' if braces > 0 => braces -= 1,
|
|
b'{' => {
|
|
let before = b[from..i].trim_ascii_end();
|
|
if !(before.ends_with(b"||") || before.ends_with(b"&&")) {
|
|
stmt = i + 1;
|
|
break;
|
|
}
|
|
}
|
|
b';' if braces == 0 => {
|
|
stmt = i + 1;
|
|
break;
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
// Only an operator at the call's own nesting level or an enclosing one counts, not one inside
|
|
// an earlier group (`(a || b) && app.run(c)`). A logical OR follows an operand;
|
|
// otherwise the pipes open a zero-argument closure, optionally preceded by `move` or `async`.
|
|
// Earlier sibling elements cannot skip the call, but guards around their group still can.
|
|
let mut depth = 0usize;
|
|
let params = (stmt..start).find_map(|pipe| {
|
|
if b[pipe] != b'|' {
|
|
return None;
|
|
}
|
|
let head = b[stmt..pipe].trim_ascii();
|
|
let head = head.strip_suffix(b"move").or_else(|| head.strip_suffix(b"async")).unwrap_or(head).trim_ascii_end();
|
|
if !head.ends_with(b"=") || !head.starts_with(b"let") || !head.get(3).is_some_and(u8::is_ascii_whitespace) {
|
|
return None;
|
|
}
|
|
(pipe + 1..start).find(|&end| b[end] == b'|').map(|end| (pipe, end))
|
|
});
|
|
let mut closure = params.map(|(pipe, _)| pipe);
|
|
let mut sibling = false;
|
|
for i in (stmt + 1..start).rev() {
|
|
if params.is_some_and(|(pipe, end)| pipe <= i && i <= end) {
|
|
continue;
|
|
}
|
|
match b[i] {
|
|
b')' | b']' | b'}' => depth += 1,
|
|
b'(' | b'[' | b'{' if depth == 0 => sibling = false,
|
|
b'(' | b'[' | b'{' => depth -= 1,
|
|
_ => {}
|
|
}
|
|
if depth != 0 {
|
|
continue;
|
|
}
|
|
if b[i] == b',' {
|
|
sibling = true;
|
|
}
|
|
if sibling {
|
|
continue;
|
|
}
|
|
if b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>') {
|
|
break;
|
|
}
|
|
if b[i] == b'&'
|
|
&& b[i - 1] == b'&'
|
|
&& b[stmt..i - 1].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}'))
|
|
&& !asserted_conjunction(b, from, to, i - 1)
|
|
{
|
|
return false;
|
|
}
|
|
if b[i] == b'|' && b[i - 1] == b'|' {
|
|
let end = (stmt..i - 1).rev().find(|&j| !b[j].is_ascii_whitespace()).map_or(stmt, |j| j + 1);
|
|
let prefix = &b[stmt..end];
|
|
let moved = prefix.ends_with(b"move") && (prefix.len() == 4 || !is_ident(prefix[prefix.len() - 5]));
|
|
let asynchronous = prefix.ends_with(b"async") && (prefix.len() == 5 || !is_ident(prefix[prefix.len() - 6]));
|
|
if !moved
|
|
&& !asynchronous
|
|
&& prefix.last().is_some_and(|&c| is_ident(c) || c.is_ascii_digit() || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}'))
|
|
{
|
|
return false;
|
|
}
|
|
closure = Some(stmt + prefix.len());
|
|
}
|
|
}
|
|
// `let run = || app.run(c);`: the closure's body runs only where the loop calls `run`.
|
|
let Some(end) = closure else { return true };
|
|
let head = String::from_utf8_lossy(&b[stmt..end]);
|
|
let head = head.trim();
|
|
let head = head.strip_suffix("move").or_else(|| head.strip_suffix("async")).unwrap_or(head).trim_end();
|
|
let Some(binding) = head.strip_suffix('=').map(str::trim).and_then(|h| h.strip_prefix("let")) else { return true };
|
|
let Some(name) = pattern_names(binding).last() else { return true };
|
|
words(b, name.as_bytes(), end, to).into_iter().any(|at| {
|
|
// `other.run()` calls a method, not the closure.
|
|
b[..at].trim_ascii_end().last() != Some(&b'.')
|
|
&& b.get(skip_ws(b, at + name.len())) == Some(&b'(')
|
|
&& runs_with_assertion_within(b, from, to, at, &active)
|
|
})
|
|
}
|
|
|
|
/// Whether an `&&` is at the top level of an assertion's first argument.
|
|
fn asserted_conjunction(b: &[u8], from: usize, to: usize, at: usize) -> bool {
|
|
macro_calls(b, from, to).iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())).any(|a| {
|
|
let Some(&(mut f, mut t)) = a.args.first() else { return false };
|
|
loop {
|
|
f += b[f..t].len() - b[f..t].trim_ascii_start().len();
|
|
t = f + b[f..t].trim_ascii_end().len();
|
|
if b.get(f) != Some(&b'(') || matching(b, f) != t.checked_sub(1) {
|
|
break;
|
|
}
|
|
f += 1;
|
|
t -= 1;
|
|
}
|
|
// A top-level `||` lets the assertion pass without the conjunction.
|
|
let cond = String::from_utf8_lossy(&b[f..t]);
|
|
f <= at && at < t && top_level_at(&cond, "||").is_empty() && top_level_at(&cond, "&&").contains(&(at - f))
|
|
})
|
|
}
|
|
|
|
/// Whether `start` lies in the block body of a closure bound with `let` in
|
|
/// `b[from..to]` (`let run = || { … };`, also `move` or `async`) that the loop never calls.
|
|
fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool {
|
|
let mut depth = 0usize;
|
|
for i in (from..start).rev() {
|
|
match b[i] {
|
|
b')' | b']' | b'}' => depth += 1,
|
|
b'(' | b'[' if depth > 0 => depth -= 1,
|
|
b'{' if depth > 0 => depth -= 1,
|
|
b'{' => {
|
|
let Some(params) = b[from..i].trim_ascii_end().strip_suffix(b"|") else { continue };
|
|
let Some(pipe) = params.iter().rposition(|&c| c == b'|') else { continue };
|
|
let head = params[..pipe].trim_ascii_end();
|
|
let head = String::from_utf8_lossy(head);
|
|
let head = head.trim_end();
|
|
let head = head.strip_suffix("move").or_else(|| head.strip_suffix("async")).unwrap_or(head).trim_end();
|
|
let Some(binding) = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { continue };
|
|
let Some(name) = pattern_names(binding).last() else { continue };
|
|
let close = matching(b, i).unwrap_or(to);
|
|
if !words(b, name.as_bytes(), close, to).into_iter().any(|at| {
|
|
b[..at].trim_ascii_end().last() != Some(&b'.')
|
|
&& b.get(skip_ws(b, at + name.len())) == Some(&b'(')
|
|
&& runs_with_assertion_within(b, from, to, at, active)
|
|
}) {
|
|
return true;
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
false
|
|
}
|
|
|
|
/// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and
|
|
/// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while
|
|
/// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions
|
|
/// nested deeper than 64 operators are not judged. An operand that calls one of `helpers` (asserting
|
|
/// helpers called in the condition) is not a presence check, and a weak right side of an `||` does
|
|
/// not count when the left side always calls one ([`always_calls`]).
|
|
fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool) {
|
|
let or = top_level_at(cond, "||").first().copied();
|
|
if depth > 64 || !cond.contains(".all(") {
|
|
(false, false)
|
|
} else if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) {
|
|
census_condition(&cond[1..cond.len() - 1], depth + 1, helpers)
|
|
} else if let Some(at) = or.or_else(|| top_level_at(cond, "&&").first().copied()) {
|
|
let side = |s: &str| {
|
|
if s.contains(".all(") {
|
|
census_condition(s, depth + 1, helpers)
|
|
} else {
|
|
(weak_predicate(s) && !calls_any(s, helpers) && !rejects(s.as_bytes()), false)
|
|
}
|
|
};
|
|
let (l, r) = (side(&cond[..at]), side(&cond[at + 2..]));
|
|
let r = if or.is_some() && (always_calls(&cond[..at], helpers, depth) || rejects(&cond.as_bytes()[..at])) { (false, false) } else { r };
|
|
if or.is_none() {
|
|
(l.0 && r.0, l.1 || r.1)
|
|
} else if l == (true, true) || r == (true, true) {
|
|
(true, true)
|
|
} else {
|
|
(l.0 || r.0, false)
|
|
}
|
|
} else {
|
|
let table = weak_table_all(cond, helpers);
|
|
(table || weak_predicate(cond) && !calls_any(cond, helpers), table)
|
|
}
|
|
}
|
|
|
|
/// Whether evaluating the (whitespace-free) condition `s` always calls one of `helpers`: a call
|
|
/// behind a top-level `&&` or `||` runs only on one outcome of the operand before it, so only the
|
|
/// first operand of either counts.
|
|
fn always_calls(s: &str, helpers: &[String], depth: usize) -> bool {
|
|
if depth > 64 {
|
|
false
|
|
} else if s.starts_with('(') && matching(s.as_bytes(), 0) == Some(s.len() - 1) {
|
|
always_calls(&s[1..s.len() - 1], helpers, depth + 1)
|
|
} else if let Some(at) = top_level_at(s, "||").first().copied().or_else(|| top_level_at(s, "&&").first().copied()) {
|
|
always_calls(&s[..at], helpers, depth + 1)
|
|
} else if let Some(&at) = top_level_at(s, "{").first()
|
|
&& let Some(cond) = s[..at].strip_prefix("if").or_else(|| s[..at].strip_prefix("match"))
|
|
{
|
|
// An `if` or `match` always runs only its condition or scrutinee, the text before its
|
|
// first block; a call inside one arm may be skipped. Without whitespace the keyword runs
|
|
// into the condition (`ifverify()`); the text before the block is also checked whole, for
|
|
// a name that only starts with the keyword.
|
|
always_calls(cond, helpers, depth + 1) || always_calls(&s[..at], helpers, depth + 1)
|
|
} else if s.starts_with('{') && matching(s.as_bytes(), 0) == Some(s.len() - 1) {
|
|
// A plain block runs each of its statements in order.
|
|
block_statements(&s[1..s.len() - 1]).into_iter().any(|st| always_calls(st, helpers, depth + 1))
|
|
} else {
|
|
calls_any(s, helpers)
|
|
}
|
|
}
|
|
|
|
/// The statements of a (whitespace-free) block body: split at each top-level `;` and after each
|
|
/// top-level `}` that no `else` follows (`if a{x();}y();` is two statements).
|
|
fn block_statements(body: &str) -> Vec<&str> {
|
|
let b = body.as_bytes();
|
|
let (mut out, mut depth, mut start) = (vec![], 0i32, 0);
|
|
for (i, &c) in b.iter().enumerate() {
|
|
match c {
|
|
b'(' | b'[' | b'{' => depth += 1,
|
|
b')' | b']' | b'}' => depth -= 1,
|
|
_ => {}
|
|
}
|
|
let end = depth == 0 && (c == b';' || c == b'}' && !body[i + 1..].starts_with("else"));
|
|
if end {
|
|
out.push(&body[start..=i]);
|
|
start = i + 1;
|
|
}
|
|
}
|
|
out.push(&body[start..]);
|
|
out.into_iter().filter(|s| !s.is_empty()).collect()
|
|
}
|
|
|
|
/// Whether `s` calls a function or method named in `names`, with or without a turbofish.
|
|
fn calls_any(s: &str, names: &[String]) -> bool {
|
|
names.iter().any(|n| {
|
|
[format!("{n}("), format!("{n}::<")]
|
|
.iter()
|
|
.any(|call| s.match_indices(call.as_str()).any(|(at, _)| at == 0 || !is_ident(s.as_bytes()[at - 1])))
|
|
})
|
|
}
|
|
|
|
/// Whether a (whitespace-free) `.all(…)` predicate checks only presence. A predicate that calls one
|
|
/// of `helpers` is weak only when a presence check can pass without the helper running: a weak left
|
|
/// side of an `||`, a weak right side after a left side that calls no helper, or weak operands on
|
|
/// both sides of an `&&`.
|
|
fn presence_only(pred: &str, helpers: &[String], depth: usize) -> bool {
|
|
let body = pred.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(pred, |(_, body)| body);
|
|
let (or, and) = (top_level_at(body, "||").first().copied(), top_level_at(body, "&&").first().copied());
|
|
if !calls_any(pred, helpers) {
|
|
weak_predicate(pred)
|
|
} else if depth > 64 {
|
|
false
|
|
} else if body.starts_with('(') && matching(body.as_bytes(), 0) == Some(body.len() - 1) {
|
|
presence_only(&body[1..body.len() - 1], helpers, depth + 1)
|
|
} else if let Some(at) = or {
|
|
let left = &body[..at];
|
|
presence_only(left, helpers, depth + 1) || !calls_any(left, helpers) && presence_only(&body[at + 2..], helpers, depth + 1)
|
|
} else if let Some(at) = and {
|
|
presence_only(&body[..at], helpers, depth + 1) && presence_only(&body[at + 2..], helpers, depth + 1)
|
|
} else {
|
|
false
|
|
}
|
|
}
|
|
|
|
/// Whether a (whitespace-free) operand is exactly `TABLE.iter().all(…)` with a presence-only predicate.
|
|
fn weak_table_all(op: &str, helpers: &[String]) -> bool {
|
|
let Some(&i) = top_level_at(op, ".all(").last() else { return false };
|
|
let receiver = op[..i].trim_end_matches(".iter()").trim_end_matches(".into_iter()");
|
|
let rest = &op[i + ".all(".len()..];
|
|
let end = arg_end(rest);
|
|
// A rejection call checks something only on the branches that run it, like an asserting helper.
|
|
let checks: Vec<String> = helpers.iter().cloned().chain(["unwrap_err".into(), "expect_err".into()]).collect();
|
|
rest[end..] == *")" && whole_table(receiver) && !calls_any(&op[..i], helpers) && presence_only(&rest[..end], &checks, 0)
|
|
}
|
|
|
|
/// Whether `body` calls `.unwrap_err()` or `.expect_err(`, with any whitespace inside the call.
|
|
fn rejects(body: &[u8]) -> bool {
|
|
let tight: Vec<u8> = body.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect();
|
|
contains(&tight, b".unwrap_err()") || contains(&tight, b".expect_err(")
|
|
}
|
|
|
|
/// The `{` that opens a `for` loop's body: the first one outside brackets after `from`.
|
|
fn loop_open(m: &[u8], from: usize, to: usize) -> Option<usize> {
|
|
let mut i = from;
|
|
while i < to {
|
|
match m[i] {
|
|
b'{' => return Some(i),
|
|
b'(' | b'[' => i = matching(m, i)? + 1,
|
|
b';' => return None,
|
|
_ => i += 1,
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// Calls whose name says they return a whole table.
|
|
const TABLE_CALLS: &[&str] = &["all", "catalog", "registry", "presets", "swatches", "entries", "variants", "commands", "builtins", "palette"];
|
|
|
|
/// Whether a (whitespace-free) loop source names a whole table: a `SCREAMING_CASE` constant, an
|
|
/// `ALL`, `all()`, `iter()` or `variants()` on a type, or a call named like a catalog.
|
|
fn whole_table(src: &str) -> bool {
|
|
let src = src.trim_start_matches('&');
|
|
let head: &str = src.split(['.', '(', '[']).next().unwrap_or("");
|
|
let restricted = [
|
|
".take(",
|
|
".skip(",
|
|
".filter(",
|
|
".filter_map(",
|
|
".take_while(",
|
|
".skip_while(",
|
|
".map_while(",
|
|
".step_by(",
|
|
".nth(",
|
|
".first(",
|
|
".last(",
|
|
".rev().take(",
|
|
"[",
|
|
];
|
|
let chain = &src[head.len()..];
|
|
// A `zip` stops at its shorter side and a `flat_map` yields what its closure's iterator yields,
|
|
// so a restricted iterator inside either bounds the loop too, as does a range zipped in.
|
|
let bounded_inside = [".zip(", ".flat_map("].iter().any(|adapter| {
|
|
top_level_at(chain, adapter).into_iter().any(|at| {
|
|
let open = at + adapter.len() - 1;
|
|
matching(chain.as_bytes(), open).is_none_or(|close| {
|
|
let inner = &chain[open + 1..close];
|
|
let range = unparenthesized(inner.trim_end_matches(','));
|
|
restricted.iter().any(|r| inner.contains(r))
|
|
|| *adapter == ".zip(" && top_level_at(range, "..").first().is_some_and(|&at| !range[at + 2..].trim_start_matches('=').is_empty())
|
|
})
|
|
})
|
|
});
|
|
if bounded_inside || restricted.iter().any(|r| top_level_contains(chain, r)) {
|
|
return false;
|
|
}
|
|
let last = head.rsplit("::").next().unwrap_or("");
|
|
let screaming = last.len() > 1
|
|
&& last.bytes().any(|c| c.is_ascii_uppercase())
|
|
&& last.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_');
|
|
let segments: Vec<&str> = head.split("::").collect();
|
|
let on_type = segments.len() > 1 && segments[segments.len() - 2].starts_with(|c: char| c.is_ascii_uppercase());
|
|
let type_table = on_type && matches!(last, "ALL" | "all" | "iter" | "variants" | "VARIANTS" | "value_variants");
|
|
let named = src[head.len()..].starts_with("()")
|
|
&& TABLE_CALLS.iter().any(|n| last == *n || last.ends_with(&format!("_{n}")) || last.starts_with(&format!("{n}_")));
|
|
screaming || type_table || named
|
|
}
|
|
|
|
/// Whether `pat` starts at a position of `s` outside every bracket, so an adapter inside a closure
|
|
/// does not count as one on the outer iterator chain.
|
|
fn top_level_contains(s: &str, pat: &str) -> bool {
|
|
!top_level_at(s, pat).is_empty()
|
|
}
|
|
|
|
/// The byte offsets where `pat` starts in `s` outside every bracket.
|
|
fn top_level_at(s: &str, pat: &str) -> Vec<usize> {
|
|
let (s, pat) = (s.as_bytes(), pat.as_bytes());
|
|
let mut depth = 0i32;
|
|
let mut found = vec![];
|
|
for (i, c) in s.iter().enumerate() {
|
|
if depth == 0 && s[i..].starts_with(pat) {
|
|
found.push(i);
|
|
}
|
|
depth += match c {
|
|
b'(' | b'[' | b'{' => 1,
|
|
b')' | b']' | b'}' => -1,
|
|
_ => 0,
|
|
};
|
|
}
|
|
found
|
|
}
|
|
|
|
/// Predicates and comparisons that every entry passes by construction.
|
|
const PRESENCE: &[&str] = &[".is_some()", ".is_ok()", ".is_empty()", ".contains(", ".contains_key(", ".len()>0", ".starts_with(", ".is_finite()"];
|
|
|
|
/// Calls on one side of an equality that turn an entry back into itself.
|
|
const ROUND_TRIP: &[&str] = &["parse", "from_str", "from_id", "from_name", "from_key", "by_id", "by_name", "lookup", "find"];
|
|
|
|
/// Whether every operand of a (whitespace-free) condition or closure is a presence check alone.
|
|
fn weak_predicate(pred: &str) -> bool {
|
|
weak_predicate_within(pred, 0)
|
|
}
|
|
|
|
/// [`weak_predicate`] for at most 64 levels of nesting; deeper conditions are not judged, as in
|
|
/// [`census_condition`].
|
|
fn weak_predicate_within(pred: &str, depth: usize) -> bool {
|
|
if depth > 64 {
|
|
return false;
|
|
}
|
|
let pred = pred.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(pred, |(_, body)| body);
|
|
if pred.starts_with('(') && matching(pred.as_bytes(), 0) == Some(pred.len() - 1) {
|
|
return weak_predicate_within(&pred[1..pred.len() - 1], depth + 1);
|
|
}
|
|
if let Some(at) = boolean_split(pred) {
|
|
return weak_predicate_within(&pred[..at], depth + 1) && weak_predicate_within(&pred[at + 2..], depth + 1);
|
|
}
|
|
let negated = (pred.len() - pred.trim_start_matches('!').len()) % 2 == 1;
|
|
let pred = pred.trim_start_matches('!');
|
|
// A negated check is a presence check only for `!….is_empty()`; `!….is_ok()` checks a rejection.
|
|
if negated && !pred.ends_with(".is_empty()") {
|
|
return false;
|
|
}
|
|
if let Some(list) = pred.strip_suffix(".len()>0") {
|
|
return !list.contains(['=', '<', '>']);
|
|
}
|
|
let compares = pred.contains("==") || pred.contains("!=") || pred.contains(['<', '>']) && !pred.contains("::<");
|
|
!compares
|
|
&& PRESENCE.iter().any(|p| match p.strip_suffix('(') {
|
|
Some(call) => pred.rfind(p).is_some_and(|at| matching(pred.as_bytes(), at + call.len()) == Some(pred.len() - 1)),
|
|
None => pred.ends_with(p),
|
|
})
|
|
}
|
|
|
|
/// Whether an assertion in a loop over entries bound to `var` checks only presence, or compares
|
|
/// a lookup or parse with the entry itself. `args` are written as [`norm_words`] gives them.
|
|
fn weak_census_check(name: &str, args: &[String], var: &str) -> bool {
|
|
match guard_arg_count(name) {
|
|
1 => args.first().is_some_and(|a| weak_predicate(&a.replace(' ', ""))),
|
|
2 if name.ends_with("_ne") => false,
|
|
2 => match args {
|
|
[a, b, ..] => (round_trip_call(a, var) && is_entry(b, var)) || (round_trip_call(b, var) && is_entry(a, var)),
|
|
_ => false,
|
|
},
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
/// Whether an operand ([`norm_words`]) is the result of one of [`ROUND_TRIP`], called by its whole
|
|
/// name with only a path or receiver before it (no arithmetic) and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so
|
|
/// the operand is the parsed or looked-up entry itself and not a value derived from it. The call's
|
|
/// arguments (`Kind::from_id(k.id())`) or its receiver (`k.parse()`) must read the loop entry `var`;
|
|
/// a lookup of a fixed key is not a round trip of the entry.
|
|
fn round_trip_call(op: &str, var: &str) -> bool {
|
|
let mut op = op.trim_start_matches(['&', '*']);
|
|
loop {
|
|
let wraps = |w: &&str| op.starts_with(*w) && matching(op.as_bytes(), w.len() - 1) == Some(op.len() - 1);
|
|
let inner = ["Some(", "Ok(", "("].iter().find(|w| wraps(w)).map(|w| &op[w.len()..op.len() - 1]);
|
|
match inner {
|
|
Some(inner) => op = inner.trim_start_matches(['&', '*']),
|
|
None => break,
|
|
}
|
|
}
|
|
ROUND_TRIP.iter().any(|r| {
|
|
op.match_indices(&format!("{r}(")).any(|(at, _)| {
|
|
let open = at + r.len();
|
|
!op.as_bytes()[..at].last().copied().is_some_and(is_ident)
|
|
&& !op[..at].contains(['+', '-', '*', '/', '%', '^', '|', '!', '=', ',', '&'])
|
|
&& matching(op.as_bytes(), open).is_some_and(|close| {
|
|
// The entry is read in the arguments (`Kind::from_id(k.id())`) or is the receiver (`k.parse()`).
|
|
let receiver = op[..at].strip_suffix('.').is_some_and(|r| reads_ident(r, var));
|
|
only_unwraps(&op[close + 1..]) && (receiver || reads_ident(&op[open + 1..close], var))
|
|
})
|
|
})
|
|
})
|
|
}
|
|
|
|
/// Whether `s`, written as [`norm_words`] gives it, reads the binding `var`: a whole word that is not
|
|
/// a field or path segment (`config.k`, `m::k`), alone or cast (`k as usize`). `kasusize` is one word.
|
|
fn reads_ident(s: &str, var: &str) -> bool {
|
|
let b = s.as_bytes();
|
|
!var.is_empty()
|
|
&& s.match_indices(var).any(|(at, _)| {
|
|
let end = at + var.len();
|
|
let field = at > 0 && b[at - 1] == b'.' && !(at > 1 && b[at - 2] == b'.');
|
|
let path = at > 1 && &b[at - 2..at] == b"::";
|
|
!(at > 0 && is_ident(b[at - 1])) && !field && !path && !b.get(end).copied().is_some_and(is_ident)
|
|
})
|
|
}
|
|
|
|
/// Whether a (whitespace-free) call suffix only unwraps or copies the call's result.
|
|
fn only_unwraps(mut rest: &str) -> bool {
|
|
const UNWRAPS: &[&str] = &[".unwrap()", ".ok()", ".copied()", ".cloned()", ".clone()", ".as_ref()", ".as_deref()", "?"];
|
|
loop {
|
|
let next = match UNWRAPS.iter().find_map(|s| rest.strip_prefix(s)) {
|
|
Some(r) => Some(r),
|
|
None if rest.starts_with(".expect(") => matching(rest.as_bytes(), ".expect".len()).map(|close| &rest[close + 1..]),
|
|
None => None,
|
|
};
|
|
match next {
|
|
_ if rest.is_empty() => break true,
|
|
Some(r) => rest = r,
|
|
None => break false,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Whether an operand is the loop entry itself: `x`, `*x`, `&x`, `Some(x)`, `Ok(x)` or `x.clone()`.
|
|
fn is_entry(op: &str, var: &str) -> bool {
|
|
let mut op = op.trim_start_matches(['&', '*']);
|
|
for wrap in ["Some(", "Ok("] {
|
|
if let Some(inner) = op.strip_prefix(wrap).and_then(|r| r.strip_suffix(')')) {
|
|
op = inner.trim_start_matches(['&', '*']);
|
|
}
|
|
}
|
|
!var.is_empty() && op.trim_end_matches(".clone()") == var
|
|
}
|
|
|
|
/// 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<usize> {
|
|
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<String, (bool, usize)> = 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>) -> 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<usize> {
|
|
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<usize> {
|
|
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<usize> {
|
|
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<usize> = 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<HashMap<String, usize>>,
|
|
}
|
|
|
|
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<usize> {
|
|
int_literal(text).or_else(|| self.consts.get_or_init(|| file_consts(self.file)).get(text).copied())
|
|
}
|
|
}
|
|
|
|
fn int_literal(text: &str) -> Option<usize> {
|
|
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 = <integer literal>;` 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<String, usize> {
|
|
// `None` for a name declared with a value that is not a literal or with different values.
|
|
let mut out: HashMap<String, Option<usize>> = 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<u8>,
|
|
end: usize,
|
|
counts: bool,
|
|
/// The local whose method the initializer calls (`xs` in `let n = xs.len()`).
|
|
source: Option<Vec<u8>>,
|
|
}
|
|
|
|
/// Every `let` of a plain name in `body`, in order.
|
|
fn bindings(body: &[u8]) -> Vec<Binding> {
|
|
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<Hit> {
|
|
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!") || rejects(&body);
|
|
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<Hit> {
|
|
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<Hit> {
|
|
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<Hit> {
|
|
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<Hit> {
|
|
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<usize> {
|
|
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<bool> = 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<Hit> {
|
|
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<Item = usize> + '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<Hit> {
|
|
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<u8> = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect();
|
|
let end = find(src, &close, body)?;
|
|
src.get(body..end)
|
|
}
|
|
|
|
/// What the file's `use` items bring in for a `thread::spawn` call.
|
|
#[derive(Clone, Copy)]
|
|
struct Imports {
|
|
/// `spawn` names `std::thread::spawn`.
|
|
spawn: bool,
|
|
/// `thread` names `std::thread`.
|
|
thread: bool,
|
|
}
|
|
|
|
fn sleep_hits(file: &File) -> Vec<Hit> {
|
|
let m = &file.m;
|
|
// A bare `sleep(…)` counts only where a `use` brings in `thread::sleep`.
|
|
let imported = thread_import(m, "sleep");
|
|
let imports = Imports { spawn: thread_import(m, "spawn"), thread: std_thread_import(m) };
|
|
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);
|
|
let thread_sleep = 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"),
|
|
};
|
|
thread_sleep && !polls_or_releases(m, at, imports)
|
|
})
|
|
.map(|at| {
|
|
let mut hit = file.hit(at, Rule::Sleep, file.test_at(at), "sleeps in test code".into());
|
|
// An edit to the loop or spawn around the sleep can remove what exempted it.
|
|
if let Some((name, _)) = expression_closure_call(m, at).filter(|&(name, end)| &m[name..end] == b"spawn") {
|
|
let end = spawn_statement_end(m, name).unwrap_or(m.len().saturating_sub(1));
|
|
hit.gates.extend(file.lines.of(name)..=file.lines.of(end));
|
|
} else if let Some(WaitBlock { start, open, through_other }) = wait_block(m, at) {
|
|
let head_at = start + (m[start..open].len() - m[start..open].trim_ascii_start().len());
|
|
if !through_other || closure_head(m[start..open].trim_ascii()) {
|
|
let close = matching(m, open).unwrap_or(m.len().saturating_sub(1));
|
|
// A spawn's span runs through the statement, which holds the use of its handle.
|
|
let close = closure_spawn(m, start, open).and_then(|s| spawn_statement_end(m, s)).map_or(close, |end| end.max(close));
|
|
hit.gates.extend(file.lines.of(head_at)..=file.lines.of(close));
|
|
}
|
|
}
|
|
hit
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Whether a `use` brings in `std::thread::<name>` under its own name, alone or in a `thread::{…}`
|
|
/// list. An alias (`thread::spawn as spawn_thread`) brings in another name, and `crate::thread`
|
|
/// is not the standard library's module.
|
|
fn thread_import(m: &[u8], name: &str) -> bool {
|
|
let path = format!("thread::{name}");
|
|
let alias = format!("as{name}");
|
|
words(m, b"use", 0, m.len()).into_iter().any(|u| {
|
|
// `norm` drops spaces, so `spawn as s` reads `spawnass`.
|
|
let item = norm(&m[u..statement_end(m, u)]);
|
|
let named = |i: usize| {
|
|
let rest = &item[i + path.len()..];
|
|
let rest = rest.strip_prefix(alias.as_str()).unwrap_or(rest);
|
|
!item.as_bytes()[..i].last().copied().is_some_and(is_ident) && !rest.bytes().next().is_some_and(is_ident)
|
|
};
|
|
item.match_indices(&path).any(|(i, _)| named(i) && under_std(&item[..i]))
|
|
|| item.match_indices("thread::{").any(|(i, _)| {
|
|
let list = &item[i + "thread::{".len()..];
|
|
let list = &list[..list.find('}').unwrap_or(list.len())];
|
|
under_std(&item[..i]) && !words(list.as_bytes(), name.as_bytes(), 0, list.len()).is_empty()
|
|
})
|
|
})
|
|
}
|
|
|
|
/// Whether a member of a `use` item whose normalized text before the member is `pre` sits directly
|
|
/// under `std`: right after `use std::`, or a top-level member of a `use std::{…}` list.
|
|
fn under_std(pre: &str) -> bool {
|
|
let pre = pre.strip_prefix("use").unwrap_or(pre);
|
|
let pre = pre.strip_prefix("::").unwrap_or(pre);
|
|
let Some(rest) = pre.strip_prefix("std::") else { return false };
|
|
rest.is_empty() || (rest.starts_with('{') && rest.ends_with(['{', ',']) && rest.matches('{').count() == 1 + rest.matches('}').count())
|
|
}
|
|
|
|
/// Whether a `use` binds the name `thread` to `std::thread`: `use std::thread;`,
|
|
/// `use std::{thread, …};` or `use std::thread::{self, …};`.
|
|
fn std_thread_import(m: &[u8]) -> bool {
|
|
words(m, b"use", 0, m.len()).into_iter().any(|u| {
|
|
let item = norm(&m[u..statement_end(m, u)]);
|
|
words(item.as_bytes(), b"thread", 0, item.len()).into_iter().any(|i| {
|
|
let after = &item[i + "thread".len()..];
|
|
// `{self as worker}` binds another name.
|
|
let self_member =
|
|
after.strip_prefix("::{").is_some_and(|list| list[..list.find('}').unwrap_or(list.len())].split(',').any(|x| x == "self"));
|
|
under_std(&item[..i]) && (after.is_empty() || after.starts_with([';', ',', '}']) || self_member)
|
|
})
|
|
})
|
|
}
|
|
|
|
/// Calls that pass a value through without reading any state, such as the `unwrap` of
|
|
/// `elapsed().checked_sub(D).unwrap()`.
|
|
const PASS_THROUGH_CALLS: &[&str] = &["unwrap", "expect", "unwrap_or", "unwrap_or_default", "unwrap_or_else"];
|
|
|
|
/// Macros that print or log their arguments, such as the `println!("{}", t0.elapsed())` of a
|
|
/// wait on the clock.
|
|
const LOG_MACROS: &[&str] = &["print!", "println!", "eprint!", "eprintln!", "trace!", "debug!", "info!", "warn!", "error!", "log!"];
|
|
|
|
/// Calls that only read or build a time, which a wait on the clock alone makes.
|
|
const TIME_CALLS: &[&str] = &[
|
|
"sleep",
|
|
"now",
|
|
"elapsed",
|
|
"duration_since",
|
|
"saturating_duration_since",
|
|
"checked_sub",
|
|
"checked_add",
|
|
"from_millis",
|
|
"from_secs",
|
|
"from_micros",
|
|
"from_nanos",
|
|
"from_secs_f32",
|
|
"from_secs_f64",
|
|
"as_secs",
|
|
"as_millis",
|
|
"as_micros",
|
|
"as_nanos",
|
|
"as_secs_f32",
|
|
"as_secs_f64",
|
|
"subsec_millis",
|
|
"subsec_micros",
|
|
"subsec_nanos",
|
|
"mul_f32",
|
|
"mul_f64",
|
|
];
|
|
|
|
/// The enclosing block's opening brace and the start of the statement that opens it.
|
|
fn enclosing_block(m: &[u8], at: usize) -> Option<(usize, usize)> {
|
|
let mut depth = 0usize;
|
|
let open = (0..at).rev().find(|&j| match m[j] {
|
|
b'}' => {
|
|
depth += 1;
|
|
false
|
|
}
|
|
b'{' if depth == 0 => true,
|
|
b'{' => {
|
|
depth -= 1;
|
|
false
|
|
}
|
|
_ => false,
|
|
})?;
|
|
// The statement that opens the block starts after the last `;`, `{` or `}` outside brackets, so
|
|
// a condition such as `json!({}) != 1` stays whole. A block in the condition (`while { … } {`)
|
|
// belongs to the statement too.
|
|
let mut nest = 0usize;
|
|
let mut j = open;
|
|
let start = loop {
|
|
let Some(k) = j.checked_sub(1) else { break 0 };
|
|
j = k;
|
|
match m[j] {
|
|
b')' | b']' => nest += 1,
|
|
b'}' if nest > 0 => nest += 1,
|
|
b'(' | b'[' => nest = nest.saturating_sub(1),
|
|
b'{' if nest > 0 => nest -= 1,
|
|
b'}' => match opening_brace(m, j).filter(|&o| condition_block(&m[..o])) {
|
|
Some(o) => j = o,
|
|
None => break j + 1,
|
|
},
|
|
b';' if nest == 0 => break j + 1,
|
|
b'{' => break j + 1,
|
|
_ => {}
|
|
}
|
|
};
|
|
Some((open, start))
|
|
}
|
|
|
|
/// The `{` that the `}` at `close` closes.
|
|
fn opening_brace(m: &[u8], close: usize) -> Option<usize> {
|
|
let mut depth = 0usize;
|
|
(0..close).rev().find(|&j| match m[j] {
|
|
b'}' => {
|
|
depth += 1;
|
|
false
|
|
}
|
|
b'{' if depth == 0 => true,
|
|
b'{' => {
|
|
depth -= 1;
|
|
false
|
|
}
|
|
_ => false,
|
|
})
|
|
}
|
|
|
|
/// Whether a block whose `{` follows `before` is an operand in a condition: it follows `while`,
|
|
/// `if`, `match`, `&&`, `||`, `!` or a comparison.
|
|
fn condition_block(before: &[u8]) -> bool {
|
|
let before = before.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]));
|
|
// A `!` after a name is a macro's (`m! { … }`), not a negation.
|
|
let not = before.strip_suffix(b"!").is_some_and(|b| !b.trim_ascii_end().last().copied().is_some_and(is_ident));
|
|
// `||` after an operand is an `or`; after `(`, `,`, `=`, `move` or `return` it starts a closure.
|
|
let or = before.strip_suffix(b"||").map(<[u8]>::trim_ascii_end).is_some_and(|b| {
|
|
let ends_word = |w: &[u8]| b.ends_with(w) && !b.len().checked_sub(w.len() + 1).is_some_and(|j| is_ident(b[j]));
|
|
b.last().copied().is_some_and(|c| is_ident(c) || matches!(c, b')' | b']' | b'}' | b'?')) && !ends_word(b"move") && !ends_word(b"return")
|
|
});
|
|
// A comparison or shift has a space before `<` or `>` (`0 < { … }`); a generic (`Option<u8> {`),
|
|
// `->` and `=>` do not.
|
|
let angles = before.iter().rev().take_while(|&&c| c == b'<' || c == b'>').count();
|
|
let compares = (1..=2).contains(&angles) && before.len().checked_sub(angles + 1).is_some_and(|j| before[j].is_ascii_whitespace());
|
|
keyword(b"while") || keyword(b"if") || keyword(b"match") || before.ends_with(b"&&") || or || not || compares || before.ends_with(b"=")
|
|
}
|
|
|
|
/// `head` without a leading loop label (`'outer:`).
|
|
fn strip_label(head: &[u8]) -> &[u8] {
|
|
if head.first() == Some(&b'\'') {
|
|
let n = 1 + head[1..].iter().take_while(|&&c| is_ident(c)).count();
|
|
if let Some(rest) = head[n..].trim_ascii_start().strip_prefix(b":") {
|
|
return rest.trim_ascii_start();
|
|
}
|
|
}
|
|
head
|
|
}
|
|
|
|
/// Whether `head` opens the body of a closure without parameters: `|| {`, or `|| -> T {` with a return type.
|
|
fn closure_head(head: &[u8]) -> bool {
|
|
head.ends_with(b"||") || head.windows(2).rposition(|w| w == b"||").is_some_and(|p| head[p + 2..].trim_ascii_start().starts_with(b"->"))
|
|
}
|
|
|
|
/// Keywords that cannot be a path segment before `spawn`, such as the `return` of `return ::std::thread::spawn(…);`.
|
|
const NOT_PATH: &[&[u8]] = &[
|
|
b"return", b"break", b"yield", b"let", b"else", b"in", b"as", b"move", b"match", b"if", b"while", b"loop", b"for", b"box", b"unsafe", b"async",
|
|
b"await", b"const", b"static", b"mut", b"ref", b"dyn", b"impl",
|
|
];
|
|
|
|
/// The block that decides whether the sleep at `at` waits: the nearest `while` or `loop`, or the
|
|
/// nearest closure without parameters, around it.
|
|
struct WaitBlock {
|
|
open: usize,
|
|
start: usize,
|
|
/// The walk passed a block other than an `if`, `else`, `match` or match arm, such as a `let`
|
|
/// initializer. Only a closure exempts the sleep then.
|
|
through_other: bool,
|
|
}
|
|
|
|
/// The [`WaitBlock`] around `at`. The walk stops at a function.
|
|
fn wait_block(m: &[u8], at: usize) -> Option<WaitBlock> {
|
|
let mut at = at;
|
|
let mut through_other = false;
|
|
loop {
|
|
let (open, start) = enclosing_block(m, at)?;
|
|
let head = m[start..open].trim_ascii();
|
|
let labeled = strip_label(head);
|
|
let keyword = |w: &[u8]| head.starts_with(w) && !head.get(w.len()).copied().is_some_and(is_ident);
|
|
let starts_while = labeled.starts_with(b"while") && !labeled.get(5).copied().is_some_and(is_ident);
|
|
// A `loop` can be the value of a `let` (`let p = loop { … };`), so it ends the head.
|
|
let ends_loop = labeled.ends_with(b"loop") && !labeled.len().checked_sub(5).is_some_and(|j| is_ident(labeled[j]));
|
|
if starts_while || ends_loop || closure_head(head) {
|
|
return Some(WaitBlock { open, start, through_other });
|
|
}
|
|
if !words(head, b"fn", 0, head.len()).is_empty() {
|
|
return None;
|
|
}
|
|
if !head.is_empty() && !keyword(b"if") && !keyword(b"else") && !keyword(b"match") && !head.ends_with(b"=>") {
|
|
through_other = true;
|
|
}
|
|
at = open;
|
|
}
|
|
}
|
|
|
|
/// Whether the `while` loop with head `head` counts its own passes: its condition compares a name
|
|
/// with `<`, `<=`, `>`, `>=` or `!=` and nothing else, and its body adds to or subtracts from it.
|
|
fn counted_while(m: &[u8], head: &[u8], open: usize, close: usize) -> bool {
|
|
let Some(cond) = head.strip_prefix(b"while") else { return false };
|
|
let cond = cond.trim_ascii_start();
|
|
let n = cond.iter().take_while(|&&c| is_ident(c)).count();
|
|
if n == 0 || cond[0].is_ascii_digit() || cond.windows(2).any(|w| w == b"&&" || w == b"||") {
|
|
return false;
|
|
}
|
|
let op = cond[n..].trim_ascii_start();
|
|
let compares = (op.starts_with(b"<") && !op.starts_with(b"<<")) || (op.starts_with(b">") && !op.starts_with(b">>")) || op.starts_with(b"!=");
|
|
let name = &cond[..n];
|
|
compares
|
|
&& words(m, name, open, close).into_iter().any(|w| {
|
|
let after = skip_ws(m, w + n);
|
|
if matches!(m.get(after..after + 2), Some(b"+=" | b"-=")) {
|
|
return true;
|
|
}
|
|
// `n = n + 1` or `n = n - 1`.
|
|
if m.get(after) != Some(&b'=') || m.get(after + 1) == Some(&b'=') {
|
|
return false;
|
|
}
|
|
let value = skip_ws(m, after + 1);
|
|
m.get(value..value + n) == Some(name)
|
|
&& !m.get(value + n).copied().is_some_and(is_ident)
|
|
&& matches!(m.get(skip_ws(m, value + n)), Some(b'+' | b'-'))
|
|
})
|
|
}
|
|
|
|
/// Whether the sleep at `at` is the pause of a loop that checks a condition, or the delay of a
|
|
/// spawned thread's fallback release. A `while` or `loop` around it polls when its condition or
|
|
/// body calls a function or method other than [`TIME_CALLS`] and [`PASS_THROUGH_CALLS`] (a
|
|
/// flag's `load`, a `poll`, a progress read). A macro such as `println!`, a call inside the
|
|
/// arguments of `stringify!`, of a [`LOG_MACROS`] macro or of the sleep itself, a nested `fn` name
|
|
/// and `Duration::new` do not count. A closure passed directly to a `thread::spawn` call whose
|
|
/// handle is dropped runs beside the test, which does not wait for it. In `while n < bound` with
|
|
/// `n += 1`, `n -= 1`, `n = n + 1` or `n = n - 1` in the body, the loop counts its own passes, so
|
|
/// only calls in the body count.
|
|
fn polls_or_releases(m: &[u8], at: usize, imports: Imports) -> bool {
|
|
if let Some((name, end)) = expression_closure_call(m, at) {
|
|
return &m[name..end] == b"spawn" && dropped_spawn(m, name, imports);
|
|
}
|
|
let Some(WaitBlock { open, start, through_other }) = wait_block(m, at) else { return false };
|
|
let head = m[start..open].trim_ascii();
|
|
if closure_head(head) {
|
|
return closure_spawn(m, start, open).is_some_and(|s| dropped_spawn(m, s, imports));
|
|
}
|
|
// A sleep inside another block, such as a `let` initializer, in the loop is reported.
|
|
if through_other {
|
|
return false;
|
|
}
|
|
let close = matching(m, open).unwrap_or(m.len());
|
|
let from = if counted_while(m, strip_label(head), open, close) { open } else { start };
|
|
let found = calls_at(m, from, close);
|
|
// The arguments of `stringify!`, of a logging macro and of a sleep are not polling work.
|
|
let skipped: Vec<(usize, usize)> = found
|
|
.iter()
|
|
.filter(|(_, name, _)| name == "stringify!" || name == "sleep" || LOG_MACROS.contains(&name.as_str()))
|
|
.filter_map(|(p, name, _)| {
|
|
let o = skip_ws(m, p + name.len());
|
|
matching(m, o).map(|c| (o, c))
|
|
})
|
|
.collect();
|
|
let before = |p: usize| m[..p].trim_ascii_end();
|
|
// `new` builds a time only as `Duration::new`, with `Duration` as a whole path segment.
|
|
let duration_new = |p: usize| {
|
|
before(p)
|
|
.strip_suffix(b"::")
|
|
.map(<[u8]>::trim_ascii_end)
|
|
.is_some_and(|q| q.ends_with(b"Duration") && !q.len().checked_sub(9).is_some_and(|j| is_ident(q[j])))
|
|
};
|
|
// A nested `fn` item's name is a declaration, not a call.
|
|
let declared = |p: usize| {
|
|
let b = before(p);
|
|
b.ends_with(b"fn") && !b.len().checked_sub(3).is_some_and(|j| is_ident(b[j]))
|
|
};
|
|
found.iter().any(|&(p, ref name, method)| {
|
|
!name.ends_with('!')
|
|
&& !TIME_CALLS.contains(&name.as_str())
|
|
&& !PASS_THROUGH_CALLS.contains(&name.as_str())
|
|
&& !skipped.iter().any(|&(o, c)| o < p && p < c)
|
|
&& !(name == "new" && !method && duration_new(p))
|
|
&& !(!method && declared(p))
|
|
})
|
|
}
|
|
|
|
/// The start of the name of the `spawn(…)` call that takes the closure whose head is `m[start..open]`
|
|
/// as its argument directly (`spawn(|| {`, `spawn(move || {`), not through another call such as
|
|
/// `spawn(prepare(|| {`.
|
|
fn closure_spawn(m: &[u8], start: usize, open: usize) -> Option<usize> {
|
|
let head = &m[start..open];
|
|
words(head, b"spawn", 0, head.len()).into_iter().rev().find_map(|s| {
|
|
let paren = skip_ws(head, s + "spawn".len());
|
|
if head.get(paren) != Some(&b'(') {
|
|
return None;
|
|
}
|
|
let arg = head[paren + 1..].trim_ascii_start();
|
|
let arg = match arg.strip_prefix(b"move") {
|
|
Some(rest) if !rest.first().copied().is_some_and(is_ident) => rest.trim_ascii_start(),
|
|
_ => arg,
|
|
};
|
|
arg.starts_with(b"||").then_some(start + s)
|
|
})
|
|
}
|
|
|
|
/// The offset of the `;` that ends the statement holding the `spawn(…)` call whose name starts at
|
|
/// `at`, so an edit that keeps or joins the handle (`).join().unwrap();`) falls in the hit's span.
|
|
fn spawn_statement_end(m: &[u8], at: usize) -> Option<usize> {
|
|
let close = matching(m, skip_ws(m, at + "spawn".len()))?;
|
|
Some(statement_end(m, close + 1).min(m.len().saturating_sub(1)))
|
|
}
|
|
|
|
/// For a sleep that is the whole body of a closure without braces (`spawn(|| thread::sleep(D))`),
|
|
/// the start and end of the name of the call that takes the closure.
|
|
fn expression_closure_call(m: &[u8], at: usize) -> Option<(usize, usize)> {
|
|
// The `(` of the call, or the `,` before the argument, that starts the argument holding `at`.
|
|
let argument_start = |from: usize, comma: bool| {
|
|
let mut depth = 0usize;
|
|
let mut j = from;
|
|
loop {
|
|
j = j.checked_sub(1)?;
|
|
match m[j] {
|
|
b')' | b']' | b'}' => depth += 1,
|
|
b'(' | b'[' | b'{' if depth > 0 => depth -= 1,
|
|
b'(' if depth == 0 => return Some(j),
|
|
b',' if depth == 0 && comma => return Some(j),
|
|
b'[' | b'{' | b';' if depth == 0 => return None,
|
|
_ => {}
|
|
}
|
|
}
|
|
};
|
|
let stop = argument_start(at, true)?;
|
|
let arg = m[stop + 1..at].trim_ascii();
|
|
let arg = match arg.strip_prefix(b"move") {
|
|
Some(rest) if !rest.first().copied().is_some_and(is_ident) => rest.trim_ascii_start(),
|
|
_ => arg,
|
|
};
|
|
let params = arg.strip_prefix(b"|")?;
|
|
let body = ¶ms[params.iter().position(|&c| c == b'|')? + 1..];
|
|
if !body.iter().all(|&c| is_ident(c) || c == b':' || c.is_ascii_whitespace()) {
|
|
return None;
|
|
}
|
|
let paren = if m[stop] == b'(' { stop } else { argument_start(stop, false)? };
|
|
let end = m[..paren].trim_ascii_end().len();
|
|
let name = m[..end].iter().rposition(|&c| !is_ident(c)).map_or(0, |j| j + 1);
|
|
(name < end).then_some((name, end))
|
|
}
|
|
|
|
/// Whether the `spawn(…)` call whose name starts at `at` starts a thread and drops its handle.
|
|
/// The call is the whole statement: `std::thread::` before it (or `thread::` where a `use` binds
|
|
/// `thread` to `std::thread`, or no path where a `use` brings in `std::thread::spawn`) and a `;` after
|
|
/// it. A `let`, an assignment, an argument or a chained `.join()` keeps the handle, and a test
|
|
/// that joins it waits for the sleep.
|
|
fn dropped_spawn(m: &[u8], at: usize, imports: Imports) -> bool {
|
|
let from = m[..at].iter().rposition(|&c| !(is_ident(c) || c == b':' || c.is_ascii_whitespace())).map_or(0, |j| j + 1);
|
|
if !matches!(m[..from].last().copied(), None | Some(b';' | b'{' | b'}')) {
|
|
return false;
|
|
}
|
|
let path = m[from..at].trim_ascii();
|
|
let path = path.strip_prefix(b"::").map_or(path, <[u8]>::trim_ascii_start);
|
|
let mut segments: Vec<&[u8]> = vec![];
|
|
let mut i = 0;
|
|
while i < path.len() {
|
|
if !is_ident(path[i]) || path[i].is_ascii_digit() {
|
|
return false;
|
|
}
|
|
let segment = i;
|
|
while i < path.len() && is_ident(path[i]) {
|
|
i += 1;
|
|
}
|
|
let last = &path[segment..i];
|
|
if NOT_PATH.contains(&last) {
|
|
return false;
|
|
}
|
|
segments.push(last);
|
|
i = skip_ws(path, i);
|
|
if path.get(i..i + 2) != Some(&b"::"[..]) {
|
|
return false;
|
|
}
|
|
i = skip_ws(path, i + 2);
|
|
}
|
|
// A `thread::` path names the standard library's module only where a `use` binds it.
|
|
let thread = match segments[..] {
|
|
[] => imports.spawn,
|
|
[b"thread"] => imports.thread,
|
|
[b"std", b"thread"] => true,
|
|
_ => false,
|
|
};
|
|
let paren = skip_ws(m, at + "spawn".len());
|
|
thread && matching(m, paren).is_some_and(|close| m.get(skip_ws(m, close + 1)) == Some(&b';'))
|
|
}
|
|
|
|
fn reads_source_hits(file: &File) -> Vec<Hit> {
|
|
if SOURCE_AUDITS.contains(&file.path) {
|
|
return vec![];
|
|
}
|
|
let m = &file.m;
|
|
// The source with comments blanked and literals kept: a path in a comment is not read.
|
|
let code = mask_parts(&String::from_utf8_lossy(file.src), true, false);
|
|
let mut out = vec![];
|
|
let words_and_notes = [
|
|
(&b"include_str"[..], "includes a .rs file as text"),
|
|
(&b"ends_with"[..], "keeps files ending in .rs"),
|
|
(&b"read_to_string"[..], "reads a .rs file as text"),
|
|
];
|
|
for (word, note) in words_and_notes {
|
|
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(&code[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 = match word {
|
|
// A suffix check alone may test a generated name; it counts when it selects files
|
|
// from a listing, its function reads a file or stream, or its function calls a
|
|
// function defined in this file whose body reads one, with any arguments.
|
|
b"ends_with" => literal == "\".rs\"" && (selects(m, at) || reads_checked(file, at)),
|
|
// The final path step names the file read: the last literal of `root.join("src/lib.rs")`
|
|
// or `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`; the
|
|
// extension of a final `.with_extension("json")`. A final step whose argument is not a
|
|
// literal (`.join(name)`, `.with_extension(ext)`) names an unknown file. Only steps on
|
|
// the outer path count: a `.join` inside another step's argument does not.
|
|
b"read_to_string" => {
|
|
// Grouping around the whole argument hides no step: `(root.join(…))`.
|
|
let arg = ungroup(arg.strip_suffix(',').unwrap_or(&arg));
|
|
let step = |s: &'static str| {
|
|
rfind_outer(arg, s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close])))
|
|
};
|
|
match [".join(", ".with_file_name(", ".with_extension("].map(step).into_iter().flatten().max_by_key(|&(at, _, _)| at) {
|
|
Some((_, ".with_extension(", ext)) => file_literal(ext) == Some("\"rs\""),
|
|
Some((_, _, last)) => file_literal(last).is_some_and(|l| l.ends_with(".rs\"")),
|
|
None => file_literal(arg).is_some_and(|l| l.ends_with(".rs\"")),
|
|
}
|
|
}
|
|
_ => arg.trim_end_matches('#').ends_with(".rs\""),
|
|
};
|
|
if rs {
|
|
let mut hit = file.hit(at, Rule::ReadsSource, file.test_at(at), note.into());
|
|
// The span runs through the argument, so a change to a path on a later line counts.
|
|
hit.last = file.lines.of(close);
|
|
out.push(hit);
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Words that name a file listing in an iterator chain or a loop source.
|
|
const LISTINGS: &[&str] = &["read_dir", "files", "listing", "walk", "walkdir", "glob", "entries", "paths", "sources"];
|
|
|
|
/// Whether `text` names a listing ([`LISTINGS`]), as a whole word or as the end of one (`rust_files`).
|
|
fn names_listing(text: &str) -> bool {
|
|
text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).any(|w| LISTINGS.iter().any(|l| w == *l || w.ends_with(&format!("_{l}"))))
|
|
}
|
|
|
|
/// Whether the call at `at` picks entries out of a listing: it sits in the closure of a `filter`,
|
|
/// `filter_map`, `find`, `any`, `all`, `position` or `retain` call on an iterator whose chain names
|
|
/// a listing (`read_dir`, `files`, `listing`, `walk` and the like), or in the body of a `for` loop
|
|
/// over one.
|
|
fn selects(m: &[u8], at: usize) -> bool {
|
|
const PICKS: &[&[u8]] = &[b"filter", b"filter_map", b"find", b"find_map", b"any", b"all", b"position", b"retain"];
|
|
let in_loop = words(m, b"for", 0, at).into_iter().any(|f| {
|
|
let Some(&kw) = words(m, b"in", f, at).first() else { return false };
|
|
loop_open(m, kw + 2, at)
|
|
.is_some_and(|open| matching(m, open).is_none_or(|close| close > at) && names_listing(&String::from_utf8_lossy(&m[kw + 2..open])))
|
|
});
|
|
// The parentheses that enclose `at`, innermost first.
|
|
let mut depth = 0usize;
|
|
let mut enclosing = m[..at].iter().enumerate().rev().filter_map(move |(i, &c)| match c {
|
|
b')' => {
|
|
depth += 1;
|
|
None
|
|
}
|
|
b'(' if depth > 0 => {
|
|
depth -= 1;
|
|
None
|
|
}
|
|
b'(' => Some(i),
|
|
_ => None,
|
|
});
|
|
in_loop
|
|
|| enclosing.any(|open| {
|
|
let head = m[..open].trim_ascii_end();
|
|
let name = head.iter().rev().take_while(|&&c| is_ident(c)).count();
|
|
if !PICKS.contains(&&head[head.len() - name..]) {
|
|
return false;
|
|
}
|
|
// The receiver chain: back from the pick to the start of its statement.
|
|
let start = head[..head.len() - name].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}' | b'=')).map_or(0, |p| p + 1);
|
|
names_listing(&String::from_utf8_lossy(&head[start..head.len() - name]))
|
|
})
|
|
}
|
|
|
|
/// File and stream reading calls, including directory listings and file opens.
|
|
const READS: &[&[u8]] = &[b"read_to_string", b"read_to_end", b"read_dir", b"include_str", b"read", b"open"];
|
|
|
|
/// The argument spans `(open, close)` of the reading calls anywhere in the file.
|
|
fn read_calls(file: &File) -> Vec<(usize, usize)> {
|
|
let m = &file.m;
|
|
let mut out = vec![];
|
|
for w in READS {
|
|
for p in words(m, w, 0, m.len()) {
|
|
// `fn read(…)` declares a function; it does not read.
|
|
if (*w == b"open" && !norm(&m[..p]).ends_with("File::")) || m[..p].trim_ascii_end().ends_with(b"fn") {
|
|
continue;
|
|
}
|
|
let next = skip_ws(m, p + w.len());
|
|
let next = if m.get(next) == Some(&b'!') { skip_ws(m, next + 1) } else { skip_ws(m, skip_turbofish(m, next)) };
|
|
if m.get(next) == Some(&b'(')
|
|
&& let Some(close) = matching(m, next)
|
|
{
|
|
out.push((next, close));
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Whether the function containing the `.ends_with` check reads a file or stream, or calls a
|
|
/// function defined in this file whose body reads one, regardless of the receiver or arguments.
|
|
fn reads_checked(file: &File, at: usize) -> bool {
|
|
let m = &file.m;
|
|
let reads = read_calls(file);
|
|
// The function around the check (the test, or a helper).
|
|
let scope = words(m, b"fn", 0, at)
|
|
.into_iter()
|
|
.rev()
|
|
.find_map(|f| {
|
|
let body = f + m[f..at].iter().position(|&c| c == b'{')?;
|
|
matching(m, body).filter(|&end| end > at).map(|end| (body, end))
|
|
})
|
|
.or_else(|| file.regions.iter().copied().find(|&(from, to)| from <= at && at < to));
|
|
let Some((from, to)) = scope else { return false };
|
|
if reads.iter().any(|&(open, _)| from < open && open < to) {
|
|
return true;
|
|
}
|
|
// Functions whose body holds a reading call and whose name is called in this scope.
|
|
words(m, b"fn", 0, m.len()).into_iter().any(|f| {
|
|
let name_at = skip_ws(m, f + 2);
|
|
let name_len = m[name_at..].iter().take_while(|&&c| is_ident(c)).count();
|
|
let Some(body) = m[name_at..].iter().position(|&c| c == b'{' || c == b';').map(|p| name_at + p).filter(|&b| m[b] == b'{') else {
|
|
return false;
|
|
};
|
|
let Some(end) = matching(m, body) else { return false };
|
|
name_len > 0
|
|
&& reads.iter().any(|&(open, _)| open > body && open < end)
|
|
&& words(m, &m[name_at..name_at + name_len], from, to).into_iter().any(|c| {
|
|
let open = skip_turbofish(m, skip_ws(m, c + name_len));
|
|
c != name_at && m.get(open) == Some(&b'(')
|
|
})
|
|
})
|
|
}
|
|
|
|
/// The offset of the last `pat` in `expr` outside every bracket and string literal.
|
|
fn rfind_outer(expr: &str, pat: &str) -> Option<usize> {
|
|
let b = expr.as_bytes();
|
|
let (mut depth, mut in_str, mut found) = (0usize, false, None);
|
|
let mut i = 0;
|
|
while i < b.len() {
|
|
let c = b[i];
|
|
if in_str {
|
|
if c == b'\\' {
|
|
i += 1;
|
|
} else if c == b'"' {
|
|
in_str = false;
|
|
}
|
|
} else {
|
|
if depth == 0 && b[i..].starts_with(pat.as_bytes()) {
|
|
found = Some(i);
|
|
}
|
|
match c {
|
|
b'"' if !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) => in_str = true,
|
|
b'(' | b'[' | b'{' => depth += 1,
|
|
b')' | b']' | b'}' => depth = depth.saturating_sub(1),
|
|
_ => {}
|
|
}
|
|
}
|
|
i += 1;
|
|
}
|
|
found
|
|
}
|
|
|
|
/// The offset of the `)` that closes the `(` at `open` in `expr`, skipping string literals.
|
|
fn outer_close(expr: &str, open: usize) -> Option<usize> {
|
|
let b = expr.as_bytes();
|
|
let (mut depth, mut in_str) = (0usize, false);
|
|
let mut i = open;
|
|
while i < b.len() {
|
|
let c = b[i];
|
|
if in_str {
|
|
if c == b'\\' {
|
|
i += 1;
|
|
} else if c == b'"' {
|
|
in_str = false;
|
|
}
|
|
} else {
|
|
match c {
|
|
b'"' if !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) => in_str = true,
|
|
b'(' | b'[' | b'{' => depth += 1,
|
|
b')' | b']' | b'}' => {
|
|
depth = depth.saturating_sub(1);
|
|
if depth == 0 {
|
|
return Some(i);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
i += 1;
|
|
}
|
|
None
|
|
}
|
|
|
|
/// A whitespace-free expression without the references and parentheses around all of it:
|
|
/// `&(root.join("a"))` gives `root.join("a")`.
|
|
fn ungroup(mut expr: &str) -> &str {
|
|
loop {
|
|
let inner = expr.trim_start_matches('&');
|
|
match inner.strip_prefix('(') {
|
|
Some(_) if outer_close(inner, 0) == Some(inner.len() - 1) => expr = &inner[1..inner.len() - 1],
|
|
_ => return inner,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// `s` when it is one complete ordinary string literal (`"a.rs"`, not `"a"+"b"`), or the body of
|
|
/// one complete raw string literal in quotes (`r#"a.rs"#` gives `"a.rs"`).
|
|
fn whole_literal(s: &str) -> Option<&str> {
|
|
if s.starts_with('"') {
|
|
return (s.len() > 1 && string_end(s.as_bytes(), 1) == s.len() && s.ends_with('"')).then_some(s);
|
|
}
|
|
let rest = s.strip_prefix('r')?;
|
|
let hashes = rest.len() - rest.trim_start_matches('#').len();
|
|
raw_literal_body(rest).map(|_| &rest[hashes..rest.len() - hashes])
|
|
}
|
|
|
|
/// The literal that names the file of a whitespace-free path expression, quotes included: one
|
|
/// complete string literal, the file literal of a `format!`-family or `concat!` call
|
|
/// ([`last_literal`]), or the same inside `Path::new(…)` or `PathBuf::from(…)`. `None` for any
|
|
/// other expression: `"data.json".trim_end_matches(".rs")` names `data.json`, not its last literal.
|
|
fn file_literal(expr: &str) -> Option<&str> {
|
|
let e = ungroup(expr.strip_suffix(',').unwrap_or(expr));
|
|
if let Some(l) = whole_literal(e) {
|
|
return Some(l);
|
|
}
|
|
let open = e.find('(')?;
|
|
if outer_close(e, open) != Some(e.len() - 1) {
|
|
return None;
|
|
}
|
|
let head = e[..open].trim_start_matches("std::").trim_start_matches("path::");
|
|
match head {
|
|
"format!" | "format_args!" | "concat!" => last_literal(e),
|
|
"Path::new" | "PathBuf::from" => file_literal(&e[open + 1..e.len() - 1]),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// The last string literal in a (whitespace-free) expression, quotes included. Inside a
|
|
/// `format!`-family call, an argument is not the file name, so the format string is returned
|
|
/// instead: `format!("fixtures/{}.txt", "lib.rs")` names a `.txt` file.
|
|
fn last_literal(arg: &str) -> Option<&str> {
|
|
let close = arg.rfind('"')?;
|
|
let open = arg[..close].rfind('"')?;
|
|
let b = arg.as_bytes();
|
|
let mut depth = 0usize;
|
|
for i in (0..open).rev() {
|
|
match b[i] {
|
|
b')' => depth += 1,
|
|
b'(' if depth > 0 => depth -= 1,
|
|
b'(' => {
|
|
let head = arg[..i].strip_suffix('!').unwrap_or("");
|
|
let name = head.rsplit(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).next().unwrap_or("");
|
|
if matches!(name, "format" | "format_args") {
|
|
let first = arg[i + 1..].strip_prefix('"')?;
|
|
let end = first.find('"')?;
|
|
return Some(&arg[i + 1..i + 2 + end + 1]);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
Some(&arg[open..=close])
|
|
}
|
|
|
|
// ---- Mirrors, echoes, never-run tests and exact pixels ----
|
|
|
|
/// Names a `mirror` comparison may call on both sides: builders, conversions and accessors.
|
|
const MIRROR_NEUTRAL: &[&str] = &[
|
|
"new",
|
|
"from",
|
|
"into",
|
|
"default",
|
|
"clone",
|
|
"to_string",
|
|
"to_owned",
|
|
"to_vec",
|
|
"iter",
|
|
"into_iter",
|
|
"collect",
|
|
"unwrap",
|
|
"expect",
|
|
"len",
|
|
"get",
|
|
"as_str",
|
|
"as_ref",
|
|
"as_slice",
|
|
"format",
|
|
"vec",
|
|
"Some",
|
|
"Ok",
|
|
"Err",
|
|
"Box",
|
|
"String",
|
|
"Vec",
|
|
"map",
|
|
"cloned",
|
|
"copied",
|
|
];
|
|
|
|
/// The function a whitespace-free operand starts by calling, with its path: `f` in `f(x).g()`,
|
|
/// `Kind::parse` in `Kind::parse(s)`. A method call on a value (`doc.node(id)`) is not one: two reads of the same
|
|
/// accessor compare two different things.
|
|
fn head_call(op: &str) -> Option<&str> {
|
|
let b = op.as_bytes();
|
|
let mut i = 0;
|
|
loop {
|
|
let end = i + b.get(i..)?.iter().take_while(|&&c| is_ident(c)).count();
|
|
if end == i || b[i].is_ascii_digit() {
|
|
return None;
|
|
}
|
|
match b.get(end) {
|
|
Some(b':') if b.get(end + 1) == Some(&b':') => i = end + 2,
|
|
Some(b'(') => return Some(&op[..end]),
|
|
_ => return None,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The offset of the first top-level `+`, `-`, `*` or `/` in a whitespace-free operand.
|
|
fn first_arithmetic(op: &str) -> Option<usize> {
|
|
["+", "-", "*", "/"].iter().flat_map(|o| top_level_at(op, o)).min()
|
|
}
|
|
|
|
/// The whitespace-free source text of the arguments of the call an operand starts with, read from
|
|
/// `code` (the source with comments blanked and string literals kept), so a comment beside a key
|
|
/// is not part of it.
|
|
fn head_args(f: &File, code: &[u8], (from, to): (usize, usize)) -> Option<Vec<String>> {
|
|
let open = from + f.m.get(from..to)?.iter().position(|&c| c == b'(')?;
|
|
let close = matching(&f.m, open)?;
|
|
Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm_outside_literals(code.get(a..b).unwrap_or(&f.src[a..b]))).collect())
|
|
}
|
|
|
|
/// [`norm`] that keeps whitespace inside string literals: `"A B"` and `"AB"` are different keys.
|
|
fn norm_outside_literals(b: &[u8]) -> String {
|
|
let mut out = Vec::with_capacity(b.len());
|
|
let mut in_str = false;
|
|
let mut i = 0;
|
|
while i < b.len() {
|
|
let c = b[i];
|
|
if in_str {
|
|
out.push(c);
|
|
if c == b'\\' {
|
|
if let Some(&n) = b.get(i + 1) {
|
|
out.push(n);
|
|
i += 1;
|
|
}
|
|
} else if c == b'"' {
|
|
in_str = false;
|
|
}
|
|
} else if c == b'"' && !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) {
|
|
in_str = true;
|
|
out.push(c);
|
|
} else if c == b'r' && !(i > 0 && is_ident(b[i - 1])) && matches!(b[i + 1..].iter().find(|&&h| h != b'#'), Some(b'"')) {
|
|
// A raw literal runs to its own closing delimiter: the `"` in `r#"A" B"#` does not end it.
|
|
let mut sink = vec![];
|
|
let end = after_ident(b, &mut sink, i, false);
|
|
out.extend_from_slice(&b[i..end]);
|
|
i = end;
|
|
continue;
|
|
} else if !c.is_ascii_whitespace() {
|
|
out.push(c);
|
|
}
|
|
i += 1;
|
|
}
|
|
String::from_utf8_lossy(&out).into_owned()
|
|
}
|
|
|
|
/// The contents of a complete raw string literal written after its `r`: `"a"` and `#"a"#` give `a`,
|
|
/// and `#""a""#` gives `"a"`. `None` when `s` is not one whole literal.
|
|
fn raw_literal_body(s: &str) -> Option<&str> {
|
|
let hashes = s.len() - s.trim_start_matches('#').len();
|
|
let close = format!("\"{}", "#".repeat(hashes));
|
|
let body = s[hashes..].strip_prefix('"')?.strip_suffix(close.as_str())?;
|
|
(!body.contains(close.as_str())).then_some(body)
|
|
}
|
|
|
|
/// An argument that names an entry rather than a quantity: a string or integer literal, or a local,
|
|
/// field or indexed element (`"Swatches"`, `3`, `&doc`, `front[0]`).
|
|
fn key_like(arg: &str) -> bool {
|
|
let arg = arg.trim_start_matches("&mut").trim_start_matches('&');
|
|
match arg.as_bytes().first() {
|
|
Some(b'"') => whole_literal(arg).is_some(),
|
|
Some(b'r') if arg[1..].starts_with(['"', '#']) => raw_literal_body(&arg[1..]).is_some(),
|
|
Some(c) if c.is_ascii_digit() => arg.bytes().all(|c| c.is_ascii_digit() || c == b'_'),
|
|
Some(_) => arg.bytes().all(|c| is_ident(c) || matches!(c, b'.' | b'[' | b']' | b':')),
|
|
None => false,
|
|
}
|
|
}
|
|
|
|
/// `assert_eq!(f(a), f(b) <op> …)`: the expected side derives its value from a second call of the
|
|
/// same function with arithmetic, so a fault in `f` can move both sides together. Identical sides
|
|
/// are `self-compare`'s. Left out: the same arithmetic on both sides (`f(a) * v == f(b) * v`
|
|
/// checks that two inputs agree, as a periodicity check does), and two reads at different entries
|
|
/// (`at("B") == at("A") + 1`, `bounds(&s, copy) == bounds(&s, id) + dv`), which relate two entries.
|
|
fn mirrors(v: &View) -> Vec<Hit> {
|
|
let code = std::cell::OnceCell::new();
|
|
v.asserts
|
|
.iter()
|
|
.filter(|a| a.name.ends_with("_eq"))
|
|
.filter_map(|a| {
|
|
let (lr, rr) = (*a.args.first()?, *a.args.get(1)?);
|
|
let (l, r) = (norm(&v.file.m[lr.0..lr.1]), norm(&v.file.m[rr.0..rr.1]));
|
|
let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&'));
|
|
let name = head_call(l)?;
|
|
// Two calls compared as they are check that two inputs agree, which is a real check.
|
|
// Arithmetic on exactly one side, in either order, derives that side from the other call.
|
|
let derived = match (first_arithmetic(l), first_arithmetic(r)) {
|
|
(None, None) => false,
|
|
(Some(i), Some(j)) => l[i..] != r[j..],
|
|
_ => true,
|
|
};
|
|
let last = name.rsplit("::").next().unwrap_or(name);
|
|
if l == r || !derived || head_call(r) != Some(name) || MIRROR_NEUTRAL.contains(&last) {
|
|
return None;
|
|
}
|
|
let code: &Vec<u8> = code.get_or_init(|| mask_parts(&String::from_utf8_lossy(v.file.src), true, false));
|
|
let (la, ra) = (head_args(v.file, code, lr)?, head_args(v.file, code, rr)?);
|
|
let mut differing = la.iter().zip(&ra).filter(|(x, y)| x != y).peekable();
|
|
let entries = la.len() == ra.len() && differing.peek().is_some() && differing.all(|(x, y)| key_like(x) && key_like(y));
|
|
(!entries).then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name)))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Methods that only read a value the test built itself.
|
|
const FIXTURE_READS: &[&str] = &["len", "is_empty", "clone", "to_string", "to_owned", "as_str", "as_ref", "as_slice", "to_vec", "into"];
|
|
|
|
/// Lowercase names that are types or keywords, not locals.
|
|
const PLAIN_NAMES: &[&str] = &[
|
|
"true", "false", "as", "f32", "f64", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "bool", "char",
|
|
"str",
|
|
];
|
|
|
|
fn screaming_or_camel(name: &str) -> bool {
|
|
name.as_bytes().first().is_some_and(u8::is_ascii_uppercase)
|
|
}
|
|
|
|
/// Whether a (whitespace-free, masked) operand reads only literals, constants, enum variants and the
|
|
/// test's own locals bound to such values: `Some(true)` when it reads such a local, `Some(false)`
|
|
/// when it reads none, `None` when it calls or reads anything else.
|
|
fn inert(op: &str, local: &dyn Fn(&str) -> Option<bool>) -> Option<bool> {
|
|
let b = op.as_bytes();
|
|
let mut reads_local = false;
|
|
let mut i = 0;
|
|
while i < b.len() {
|
|
if !is_ident(b[i]) || b[i].is_ascii_digit() || (i > 0 && is_ident(b[i - 1])) {
|
|
// Number suffixes (`1.0f32`, `2_u8`) are part of the literal.
|
|
if b[i].is_ascii_digit() {
|
|
i += b[i..].iter().take_while(|&&c| is_ident(c)).count();
|
|
continue;
|
|
}
|
|
i += 1;
|
|
continue;
|
|
}
|
|
let end = i + b[i..].iter().take_while(|&&c| is_ident(c)).count();
|
|
let name = &op[i..end];
|
|
let after = &op[end..];
|
|
let method = op[..i].ends_with('.') && !op[..i].ends_with("..");
|
|
let path_tail = op[..i].ends_with("::");
|
|
if method {
|
|
if after.starts_with('(') && !FIXTURE_READS.contains(&name) {
|
|
return None;
|
|
}
|
|
} else if after.starts_with("::") || PLAIN_NAMES.contains(&name) {
|
|
} else if after.starts_with('!') && !after.starts_with("!=") {
|
|
// `format!` can read locals inside its string (`"{got:?}"`), which masking hides.
|
|
if name != "vec" {
|
|
return None;
|
|
}
|
|
} else if after.starts_with('(') {
|
|
let builder = ["Some", "Ok", "Err"].contains(&name)
|
|
|| (path_tail && ["Box::new", "String::from", "Vec::new"].iter().any(|p| op[..end].ends_with(p)))
|
|
|| (!path_tail && screaming_or_camel(name));
|
|
if !builder {
|
|
return None;
|
|
}
|
|
} else if after.starts_with(':') || screaming_or_camel(name) {
|
|
// A field name in a struct literal, a constant or a variant.
|
|
} else if path_tail {
|
|
return None;
|
|
} else {
|
|
match local(name) {
|
|
Some(true) => reads_local = true,
|
|
_ => return None,
|
|
}
|
|
}
|
|
i = end;
|
|
}
|
|
Some(reads_local)
|
|
}
|
|
|
|
/// The initializer of the last immutable `let <name> = …;` in `body[..before]`: `None` when there is
|
|
/// none, `Some(None)` when the reaching binding is `mut`, a pattern or has no initializer. The
|
|
/// initializer comes with the offset of its `let`, where the names it reads are resolved.
|
|
fn reaching_init(body: &[u8], name: &str, before: usize) -> Option<Option<(String, usize)>> {
|
|
let found = let_init(body, name, before);
|
|
// A `for` pattern binds its names inside the loop body only, to values the loop produces.
|
|
let loop_at = words(body, b"for", 0, before).into_iter().rev().find(|&at| {
|
|
// `in` is found as a word outside the pattern's brackets, so a line break around it still
|
|
// ends the pattern, and the braces of `for Row { n } in …` are not the loop body.
|
|
let Some(kw) = words(body, b"in", at + 3, before).into_iter().find(|&kw| bracket_depth(&body[at + 3..kw]) == 0) else { return false };
|
|
let Some((open, close)) = block_after(body, kw + 2) else { return false };
|
|
// Words stay apart, so `mut n` binds `n`.
|
|
let pattern = norm_words(&body[at + 3..kw]);
|
|
open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty()
|
|
});
|
|
// A match arm's pattern binds its names inside that arm only, and a closure's parameters
|
|
// inside its body only.
|
|
let inner = loop_at.max(arm_binding(body, name, before)).max(closure_binding(body, name, before));
|
|
match (inner, &found) {
|
|
(Some(l), Some((_, at))) if *at > l => found.map(|(init, _)| init),
|
|
(Some(_), _) => Some(None),
|
|
(None, _) => found.map(|(init, _)| init),
|
|
}
|
|
}
|
|
|
|
/// The offset of the parameter list of the innermost closure whose parameters bind `name` and whose
|
|
/// body holds `before`: `for_each(|n| assert_eq!(n, 1))` binds `n`.
|
|
fn closure_binding(body: &[u8], name: &str, before: usize) -> Option<usize> {
|
|
let mut found = None;
|
|
let mut i = 0;
|
|
while i < before.min(body.len()) {
|
|
if body[i] != b'|' {
|
|
i += 1;
|
|
continue;
|
|
}
|
|
// A closure's `|` follows an opening bracket, a separator, `=` or `move`; `a | b` and
|
|
// `a || b` follow an operand.
|
|
let lead = body[..i].trim_ascii_end();
|
|
let opens = lead.last().is_none_or(|&c| matches!(c, b'(' | b'[' | b'{' | b',' | b'=' | b';')) || lead.ends_with(b"move");
|
|
let Some(close) = body[i + 1..].iter().position(|&c| c == b'|').map(|p| p + i + 1) else { break };
|
|
if !opens || close == i + 1 {
|
|
i = if opens { close + 1 } else { i + 1 };
|
|
continue;
|
|
}
|
|
let params = &body[i + 1..close];
|
|
let from = skip_ws(body, close + 1);
|
|
let end = match body.get(from) {
|
|
Some(b'{') => matching(body, from),
|
|
_ => {
|
|
let mut depth = 0usize;
|
|
(from..body.len()).find(|&k| match body[k] {
|
|
b'(' | b'[' | b'{' => {
|
|
depth += 1;
|
|
false
|
|
}
|
|
b')' | b']' | b'}' if depth == 0 => true,
|
|
b')' | b']' | b'}' => {
|
|
depth -= 1;
|
|
false
|
|
}
|
|
b',' | b';' => depth == 0,
|
|
_ => false,
|
|
})
|
|
}
|
|
};
|
|
if !words(params, name.as_bytes(), 0, params.len()).is_empty() && from <= before && end.is_some_and(|end| before < end) {
|
|
found = Some(i);
|
|
}
|
|
i = close + 1;
|
|
}
|
|
found
|
|
}
|
|
|
|
/// The offset of the `=>` of the innermost match arm whose pattern binds `name` and whose body
|
|
/// holds `before`: `Some(n) => assert_eq!(n, 1)` binds `n`, `None => …` does not.
|
|
fn arm_binding(body: &[u8], name: &str, before: usize) -> Option<usize> {
|
|
let mut found = None;
|
|
for arrow in (0..before.min(body.len().saturating_sub(1))).filter(|&i| &body[i..i + 2] == b"=>") {
|
|
// The pattern runs back to the `{` or `,` that opens the arm.
|
|
let mut depth = 0usize;
|
|
let mut start = arrow;
|
|
while start > 0 {
|
|
match body[start - 1] {
|
|
b')' | b']' | b'}' => depth += 1,
|
|
b'(' | b'[' | b'{' if depth == 0 => break,
|
|
b'(' | b'[' | b'{' => depth -= 1,
|
|
b',' if depth == 0 => break,
|
|
_ => {}
|
|
}
|
|
start -= 1;
|
|
}
|
|
// A guard (`Some(x) if x == n`) reads names; it does not bind them.
|
|
let guard = words(body, b"if", start, arrow).first().copied().unwrap_or(arrow);
|
|
let pattern = norm_words(&body[start..guard]);
|
|
if words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() {
|
|
continue;
|
|
}
|
|
// The arm's body: a block, or an expression up to the `,` or brace that ends the arm.
|
|
let from = skip_ws(body, arrow + 2);
|
|
let end = match body.get(from) {
|
|
Some(b'{') => matching(body, from),
|
|
_ => {
|
|
let mut depth = 0usize;
|
|
(from..body.len()).find(|&i| match body[i] {
|
|
b'(' | b'[' | b'{' => {
|
|
depth += 1;
|
|
false
|
|
}
|
|
b')' | b']' | b'}' if depth == 0 => true,
|
|
b')' | b']' | b'}' => {
|
|
depth -= 1;
|
|
false
|
|
}
|
|
b',' => depth == 0,
|
|
_ => false,
|
|
})
|
|
}
|
|
};
|
|
if end.is_some_and(|end| before < end) {
|
|
found = Some(arrow);
|
|
}
|
|
}
|
|
found
|
|
}
|
|
|
|
/// [`reaching_init`] over `let` bindings alone, with the position of the binding that decides it.
|
|
fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, usize)>, usize)> {
|
|
let mut found = None;
|
|
for at in words(body, b"let", 0, before) {
|
|
let start = skip_ws(body, at + 3);
|
|
let is_mut = body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace);
|
|
let n0 = if is_mut { skip_ws(body, start + 3) } else { start };
|
|
let n1 = n0 + body[n0..].iter().take_while(|&&c| is_ident(c)).count();
|
|
let head = body[..at].trim_ascii_end();
|
|
let keyword =
|
|
[&b"if"[..], b"while"].into_iter().find(|k| head.ends_with(k) && !head[..head.len() - k.len()].last().copied().is_some_and(is_ident));
|
|
if keyword.is_some() {
|
|
// `if let` and `while let` bind the pattern's names inside their body only.
|
|
if let Some((eq, open, close)) = let_body(body, n0) {
|
|
let pattern = norm_words(&body[n0..eq]);
|
|
if open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() {
|
|
found = Some((None, at));
|
|
}
|
|
}
|
|
continue;
|
|
}
|
|
let stop = statement_end(body, n1);
|
|
if stop > before || block_close(body, at) < before {
|
|
continue;
|
|
}
|
|
let rest = norm(&body[n1..stop]);
|
|
let plain = n1 > n0 && (rest.is_empty() || rest.starts_with(':') || rest.starts_with('='));
|
|
if plain && &body[n0..n1] == name.as_bytes() {
|
|
let init = rest.split_once('=').filter(|(ty, _)| ty.is_empty() || ty.starts_with(':')).map(|(_, init)| (init.to_owned(), at));
|
|
found = Some((if is_mut { None } else { init }, at));
|
|
} else if !plain {
|
|
// A pattern that binds the name (`let (a, b) = …`, `let Foo { a, .. } = …`).
|
|
let pattern = norm_words(&body[n0..stop]);
|
|
let pattern = pattern.split_once('=').map_or(pattern.as_str(), |(p, _)| p);
|
|
if !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() {
|
|
found = Some((None, at));
|
|
}
|
|
}
|
|
}
|
|
found
|
|
}
|
|
|
|
/// The `=` that ends the pattern of an `if let` or `while let` starting at `from`, and the braces of
|
|
/// its body after the scrutinee ([`block_after`]). The `=` sits outside every bracket, so the braces
|
|
/// of a struct pattern (`if let Row { n } = …`) are part of the pattern, and it is not part of `==`,
|
|
/// `=>`, `..=`, `<=`, `>=` or `!=`.
|
|
fn let_body(body: &[u8], from: usize) -> Option<(usize, usize, usize)> {
|
|
let mut depth = 0usize;
|
|
for (i, &c) in body.iter().enumerate().skip(from) {
|
|
match c {
|
|
b'(' | b'[' | b'{' => depth += 1,
|
|
b')' | b']' | b'}' if depth == 0 => return None,
|
|
b')' | b']' | b'}' => depth -= 1,
|
|
b';' if depth == 0 => return None,
|
|
b'=' if depth == 0
|
|
&& !matches!(body.get(i + 1), Some(b'=' | b'>'))
|
|
&& !matches!(i.checked_sub(1).map(|j| body[j]), Some(b'=' | b'.' | b'<' | b'>' | b'!')) =>
|
|
{
|
|
return block_after(body, i + 1).map(|(open, close)| (i, open, close));
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// The depth of the brackets left open at the end of `b`.
|
|
fn bracket_depth(b: &[u8]) -> isize {
|
|
b.iter()
|
|
.map(|&c| match c {
|
|
b'(' | b'[' | b'{' => 1,
|
|
b')' | b']' | b'}' => -1,
|
|
_ => 0,
|
|
})
|
|
.sum()
|
|
}
|
|
|
|
/// The braces of the block that follows an expression starting at `from`: the first `{` outside
|
|
/// parentheses and brackets, and its match.
|
|
fn block_after(body: &[u8], from: usize) -> Option<(usize, usize)> {
|
|
let mut depth = 0usize;
|
|
for (i, &c) in body.iter().enumerate().skip(from) {
|
|
match c {
|
|
b'(' | b'[' => depth += 1,
|
|
b')' | b']' => depth = depth.saturating_sub(1),
|
|
b'{' if depth == 0 => return matching(body, i).map(|close| (i, close)),
|
|
b';' | b'}' if depth == 0 => return None,
|
|
_ => {}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// Where the innermost block holding `at` closes: its `}`, or the end of `body`.
|
|
fn block_close(body: &[u8], at: usize) -> usize {
|
|
let mut depth = 0usize;
|
|
for i in (0..at).rev() {
|
|
match body[i] {
|
|
b'}' => depth += 1,
|
|
b'{' if depth == 0 => return matching(body, i).unwrap_or(body.len()),
|
|
b'{' => depth -= 1,
|
|
_ => {}
|
|
}
|
|
}
|
|
body.len()
|
|
}
|
|
|
|
/// `inert` for an operand of the test at `pos`, resolving locals through their initializers.
|
|
fn inert_at(body: &[u8], op: &str, pos: usize, depth: usize) -> Option<bool> {
|
|
let local = |name: &str| -> Option<bool> {
|
|
if depth > 8 {
|
|
return None;
|
|
}
|
|
let (init, at) = reaching_init(body, name, pos)??;
|
|
inert_at(body, &init, at, depth + 1).map(|_| true)
|
|
};
|
|
inert(op, &local)
|
|
}
|
|
|
|
/// `constant-echo` and `fixture-only`: every assertion of the test reads only constants and
|
|
/// literals, or the test's own locals bound to them, so no result of the code under test is checked.
|
|
fn echoes(v: &View) -> Option<Hit> {
|
|
if v.asserts.is_empty() || v.delegates || v.should_panic {
|
|
return None;
|
|
}
|
|
let body = v.body_without_messages();
|
|
if contains(&body, b"panic!") || contains(&body, b".unwrap_err()") || contains(&body, b".expect_err(") {
|
|
return None;
|
|
}
|
|
let mut reads_local = false;
|
|
for a in &v.asserts {
|
|
let n = guard_arg_count(&a.name);
|
|
if n == 0 {
|
|
return None;
|
|
}
|
|
for &(from, to) in a.args.iter().take(n) {
|
|
let op = norm(&body[from - v.t.open..to - v.t.open]);
|
|
reads_local |= inert_at(&body, &op, from - v.t.open, 0)?;
|
|
}
|
|
}
|
|
Some(if reads_local {
|
|
v.whole(Rule::FixtureOnly, "every assertion reads only locals the test bound to literals or constants".into())
|
|
} else {
|
|
v.whole(Rule::ConstantEcho, "every assertion compares only constants and literals".into())
|
|
})
|
|
}
|
|
|
|
/// A target CI builds and runs the tests on.
|
|
struct Target {
|
|
os: &'static str,
|
|
family: &'static str,
|
|
arch: &'static str,
|
|
}
|
|
|
|
/// The shared gate (Linux) and the FreeBSD workflow run every test.
|
|
const CI_TARGETS: &[Target] = &[Target { os: "linux", family: "unix", arch: "x86_64" }, Target { os: "freebsd", family: "unix", arch: "x86_64" }];
|
|
|
|
/// The printing workflow also runs the app's tests and the UI crate's print tests on Windows.
|
|
const WINDOWS_TARGET: Target = Target { os: "windows", family: "windows", arch: "x86_64" };
|
|
|
|
/// Desktop targets that CI does not test on, by name. A test that builds on one of them tests code
|
|
/// or behavior of that platform.
|
|
const PLATFORM_TARGETS: &[(&str, Target)] = &[
|
|
("macOS", Target { os: "macos", family: "unix", arch: "aarch64" }),
|
|
("macOS", Target { os: "macos", family: "unix", arch: "x86_64" }),
|
|
("Windows", Target { os: "windows", family: "windows", arch: "x86_64" }),
|
|
("Windows", Target { os: "windows", family: "windows", arch: "aarch64" }),
|
|
];
|
|
|
|
fn windows_runs(path: &str) -> bool {
|
|
path.starts_with("apps/vectorcraft/") || path == "crates/ui-egui/src/tests/printps.rs"
|
|
}
|
|
|
|
/// The value of the contents of an ordinary Rust string literal: `\x`, `\u{…}` and the single-character
|
|
/// escapes decoded. An escape it cannot read is kept as written.
|
|
fn unescape(s: &str) -> String {
|
|
let mut out = String::with_capacity(s.len());
|
|
let mut chars = s.chars().peekable();
|
|
while let Some(c) = chars.next() {
|
|
if c != '\\' {
|
|
out.push(c);
|
|
continue;
|
|
}
|
|
match chars.next() {
|
|
Some(c @ ('\n' | '\r')) if c == '\n' || chars.peek() == Some(&'\n') => {
|
|
while chars.next_if(|c| matches!(c, ' ' | '\t' | '\n' | '\r')).is_some() {}
|
|
}
|
|
Some('n') => out.push('\n'),
|
|
Some('t') => out.push('\t'),
|
|
Some('r') => out.push('\r'),
|
|
Some('0') => out.push('\0'),
|
|
Some(c @ ('\\' | '"' | '\'')) => out.push(c),
|
|
Some('x') => {
|
|
let hex: String = chars.by_ref().take(2).collect();
|
|
match u8::from_str_radix(&hex, 16) {
|
|
Ok(v) if v < 0x80 => out.push(char::from(v)),
|
|
_ => out.push_str(&format!("\\x{hex}")),
|
|
}
|
|
}
|
|
Some('u') if chars.peek() == Some(&'{') => {
|
|
let body: String = chars.by_ref().take_while(|&c| c != '}').collect();
|
|
match u32::from_str_radix(&body[1..].replace('_', ""), 16).ok().and_then(char::from_u32) {
|
|
Some(v) => out.push(v),
|
|
None => out.push_str(&format!("\\u{body}}}")),
|
|
}
|
|
}
|
|
Some(other) => {
|
|
out.push('\\');
|
|
out.push(other);
|
|
}
|
|
None => out.push('\\'),
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The offsets of the commas in an attribute's argument list `s` that separate its arguments:
|
|
/// outside brackets and outside string literals, so `target_os = "("` and `path = "a,b.rs"` stay
|
|
/// whole.
|
|
fn attr_commas(s: &str) -> Vec<usize> {
|
|
let b = s.as_bytes();
|
|
let (mut depth, mut i, mut out) = (0i32, 0, vec![]);
|
|
while i < b.len() {
|
|
match b[i] {
|
|
b'"' => {
|
|
// A raw string (`r#"…"#`) ends at a quote followed by as many `#` as it opened with,
|
|
// and has no escapes.
|
|
let hashes = b[..i].iter().rev().take_while(|&&c| c == b'#').count();
|
|
let raw = b[..i - hashes].last() == Some(&b'r');
|
|
let close: Vec<u8> = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', if raw { hashes } else { 0 })).collect();
|
|
i += 1;
|
|
while i < b.len() && !b[i..].starts_with(&close) {
|
|
i += if !raw && b[i] == b'\\' { 2 } else { 1 };
|
|
}
|
|
i += close.len();
|
|
continue;
|
|
}
|
|
b'(' | b'[' | b'{' => depth += 1,
|
|
b')' | b']' | b'}' => depth -= 1,
|
|
b',' if depth == 0 => out.push(i),
|
|
_ => {}
|
|
}
|
|
i += 1;
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Whether a (whitespace-free) `cfg` predicate holds on `t`: `None` when it depends on something
|
|
/// else (a feature, `debug_assertions`, an unknown key).
|
|
fn cfg_value(p: &str, t: &Target) -> Option<bool> {
|
|
for (head, all) in [("all(", true), ("any(", false)] {
|
|
if let Some(args) = p.strip_prefix(head).and_then(|a| a.strip_suffix(')')) {
|
|
let mut parts = vec![];
|
|
let mut start = 0;
|
|
for at in attr_commas(args).into_iter().chain([args.len()]) {
|
|
if at > start {
|
|
parts.push(cfg_value(&args[start..at], t));
|
|
}
|
|
start = at + 1;
|
|
}
|
|
return if parts.contains(&Some(!all)) {
|
|
Some(!all)
|
|
} else if parts.iter().all(Option::is_some) {
|
|
Some(all)
|
|
} else {
|
|
None
|
|
};
|
|
}
|
|
}
|
|
if let Some(arg) = p.strip_prefix("not(").and_then(|a| a.strip_suffix(')')) {
|
|
let arg = arg.trim();
|
|
let arg = arg.strip_suffix(',').unwrap_or(arg).trim_end();
|
|
return cfg_value(arg, t).map(|v| !v);
|
|
}
|
|
// An ordinary or raw string value: `"linux"`, `r"linux"`, `r#"linux"#`.
|
|
// An ordinary string is compared by its decoded value (`"\x6cinux"` is `linux`); a raw string's
|
|
// contents are kept as written.
|
|
let (key, value) = p.split_once('=').map_or((p, String::new()), |(k, v)| match v.strip_prefix('r') {
|
|
Some(raw) => (k, raw_literal_body(raw).unwrap_or(raw).to_owned()),
|
|
None => (k, unescape(v.strip_prefix('"').and_then(|v| v.strip_suffix('"')).unwrap_or(v))),
|
|
});
|
|
let value = value.as_str();
|
|
match key {
|
|
"test" => Some(true),
|
|
"unix" => Some(t.family == "unix"),
|
|
"windows" => Some(t.family == "windows"),
|
|
"target_os" => Some(t.os == value),
|
|
"target_family" => Some(t.family == value),
|
|
"target_arch" => Some(t.arch == value),
|
|
"target_pointer_width" => Some(value == "64"),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// A `cfg` attribute found by [`cfg_attrs`].
|
|
struct CfgAttr {
|
|
pred: String,
|
|
/// The offset of the attribute's `cfg` or `cfg_attr`.
|
|
at: usize,
|
|
/// The offset of its closing `]`.
|
|
end: usize,
|
|
inner: bool,
|
|
}
|
|
|
|
/// The `#[cfg(…)]`, `#![cfg(…)]` and `#[cfg_attr(<condition>, cfg(…))]` attributes in `m[from..to]`,
|
|
/// sorted by offset. A nested `cfg` becomes `any(not(<condition>),<predicate>)`: it removes the item
|
|
/// only when the condition holds. `m` is the masked text of `src`.
|
|
fn cfg_attrs(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<CfgAttr> {
|
|
let mut out = vec![];
|
|
for (word, nested) in [(&b"cfg"[..], false), (&b"cfg_attr"[..], true)] {
|
|
for at in words(m, word, from, to) {
|
|
let before = m[..at].trim_ascii_end();
|
|
let Some(hash) = before.strip_suffix(b"[").map(<[u8]>::trim_ascii_end) else { continue };
|
|
let inner = hash.ends_with(b"#!");
|
|
if !inner && !hash.ends_with(b"#") {
|
|
continue;
|
|
}
|
|
let open = skip_ws(m, at + word.len());
|
|
let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue };
|
|
let end = skip_ws(m, close + 1);
|
|
if m.get(end) != Some(&b']') {
|
|
continue;
|
|
}
|
|
let text = pred_text(&src[open + 1..close]);
|
|
if !nested {
|
|
out.push(CfgAttr { pred: text, at, end, inner });
|
|
continue;
|
|
}
|
|
for pred in cfg_attr_preds(&text, None) {
|
|
out.push(CfgAttr { pred, at, end, inner });
|
|
}
|
|
}
|
|
}
|
|
out.sort_by_key(|a| a.at);
|
|
out
|
|
}
|
|
|
|
/// The `cfg` predicates inside the arguments of a `cfg_attr(<condition>, …)`, each made
|
|
/// `any(not(<conditions>),<predicate>)`. A nested `cfg_attr` adds its condition to the enclosing
|
|
/// ones: `cfg_attr(unix, cfg_attr(test, cfg(p)))` gives `any(not(all(unix,test)),p)`.
|
|
fn cfg_attr_preds(text: &str, outer: Option<&str>) -> Vec<String> {
|
|
let cuts = attr_commas(text);
|
|
let Some(&first) = cuts.first() else { return vec![] };
|
|
let cond = match outer {
|
|
Some(o) => format!("all({o},{})", &text[..first]),
|
|
None => text[..first].to_owned(),
|
|
};
|
|
let mut out = vec![];
|
|
let mut start = first + 1;
|
|
for cut in cuts[1..].iter().copied().chain([text.len()]) {
|
|
let arg = text.get(start..cut).unwrap_or("");
|
|
if let Some(p) = arg.strip_prefix("cfg(").and_then(|p| p.strip_suffix(')')) {
|
|
out.push(format!("any(not({cond}),{p})"));
|
|
} else if let Some(n) = arg.strip_prefix("cfg_attr(").and_then(|p| p.strip_suffix(')')) {
|
|
out.extend(cfg_attr_preds(n, Some(&cond)));
|
|
}
|
|
start = cut + 1;
|
|
}
|
|
out
|
|
}
|
|
|
|
/// A `cfg` predicate's source text without whitespace or comments. Masking would also blank the
|
|
/// string literals `target_os = "macos"` needs, so only comments are blanked.
|
|
fn pred_text(src: &[u8]) -> String {
|
|
norm(&mask_parts(&String::from_utf8_lossy(src), true, false))
|
|
}
|
|
|
|
/// The predicates of the `cfg` attributes of [`cfg_spans`] whose item holds `pos`, each with the
|
|
/// offsets where its attribute starts and ends.
|
|
fn cfgs_at(spans: &[CfgSpan], pos: usize) -> Vec<(String, usize, usize)> {
|
|
spans.iter().filter(|s| s.span.0 <= pos && pos <= s.span.1).map(|s| (s.pred.clone(), s.at, s.end)).collect()
|
|
}
|
|
|
|
/// A `cfg` attribute and the item it covers, from its start to its closing brace.
|
|
struct CfgSpan {
|
|
pred: String,
|
|
at: usize,
|
|
end: usize,
|
|
span: (usize, usize),
|
|
}
|
|
|
|
/// Every `cfg` attribute in `src` ([`cfg_attrs`]) with the item it covers, read once per file and
|
|
/// queried for each test or declaration with [`cfgs_at`].
|
|
fn cfg_spans(m: &[u8], src: &[u8]) -> Vec<CfgSpan> {
|
|
let mut out = vec![];
|
|
for CfgAttr { pred, at, end, inner } in cfg_attrs(m, src, 0, m.len()) {
|
|
let span = if inner {
|
|
// An inner attribute covers the file (or the module) it opens.
|
|
let enclosing = m[..at].iter().rposition(|&c| c == b'{');
|
|
enclosing.and_then(|o| matching(m, o).map(|c| (o, c))).unwrap_or((0, m.len()))
|
|
} else {
|
|
// Later attributes can hold `;` (`#[test_case(1; "one")]`); skip them whole, as `fn_after` does.
|
|
let mut after = end + 1;
|
|
while m[skip_ws(m, after)..].starts_with(b"#[") {
|
|
let Some(close) = matching(m, skip_ws(m, after) + 1) else { break };
|
|
after = close + 1;
|
|
}
|
|
let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue };
|
|
match (m[open], matching(m, open)) {
|
|
(b'{', Some(close)) => (at, close),
|
|
_ => continue,
|
|
}
|
|
};
|
|
out.push(CfgSpan { pred, at, end, span });
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Whether the files directly in `dir` are crate target roots: `tests`, `benches` or `examples`
|
|
/// beside a crate's `src`, or `src/bin`.
|
|
fn is_root_dir(dir: &str) -> bool {
|
|
let outside_src = |d: &str| dir.strip_suffix(d).is_some_and(|crate_dir| !crate_dir.split('/').any(|s| s == "src"));
|
|
["/tests", "/benches", "/examples"].iter().any(|d| outside_src(d)) || dir.ends_with("/src/bin")
|
|
}
|
|
|
|
/// Whether the modules the file `path` declares by name sit in its own directory: `mod.rs`,
|
|
/// `lib.rs`, `main.rs` and every crate root (`tests/smoke.rs`, `build.rs`).
|
|
fn owns_its_dir(path: &str) -> bool {
|
|
let file = path.rsplit_once('/').map_or(path, |(_, f)| f);
|
|
["mod.rs", "lib.rs", "main.rs"].contains(&file) || module_parent(path).is_none()
|
|
}
|
|
|
|
/// Whether `path` is a `mod.rs` one directory below a target directory (`tests/common/mod.rs`).
|
|
fn beside_roots(path: &str) -> bool {
|
|
path.rsplit_once('/').is_some_and(|(dir, file)| file == "mod.rs" && dir.rsplit_once('/').is_some_and(|(up, _)| is_root_dir(up)))
|
|
}
|
|
|
|
/// The routes to each [`beside_roots`] file of `files`: every target root in the directory above it
|
|
/// (`tests/smoke.rs` for `tests/common/mod.rs`) may load it with `mod common;`.
|
|
fn root_routes(files: &[String]) -> Overrides {
|
|
let mut out: Overrides = HashMap::new();
|
|
for child in files.iter().filter(|p| beside_roots(p)) {
|
|
let Some((up, _)) = child.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')) else { continue };
|
|
let roots = files.iter().filter(|p| p.rsplit_once('/').is_some_and(|(d, f)| d == up && f.ends_with(".rs")));
|
|
out.entry(child.clone()).or_default().extend(roots.map(|r| (r.clone(), vec![])));
|
|
}
|
|
out
|
|
}
|
|
|
|
/// `overrides` with the routes of [`root_routes`] added.
|
|
fn with_root_routes(mut overrides: Overrides, files: &[String]) -> Overrides {
|
|
for (child, routes) in root_routes(files) {
|
|
let known = overrides.entry(child).or_default();
|
|
for route in routes {
|
|
if !known.contains(&route) {
|
|
known.push(route);
|
|
}
|
|
}
|
|
}
|
|
overrides
|
|
}
|
|
|
|
/// The module name a file declares and the files that may declare it with `mod <name>;`, or `None`
|
|
/// for a crate root (`lib.rs`, `main.rs`, `build.rs`, a file directly in `tests`, `benches` or
|
|
/// `examples` beside a crate's `src`, or a file directly in `src/bin`). A `tests` directory under
|
|
/// `src` holds modules, not test targets. A `mod.rs` one directory below a target directory
|
|
/// (`tests/common/mod.rs`) has no candidates here: the target roots beside that directory load it
|
|
/// (`tests/smoke.rs` with `mod common;`), and [`root_routes`] lists them.
|
|
fn module_parent(path: &str) -> Option<(&str, Vec<String>)> {
|
|
let (dir, file) = path.rsplit_once('/')?;
|
|
if beside_roots(path) {
|
|
return Some((dir.rsplit_once('/')?.1, vec![]));
|
|
}
|
|
if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (is_root_dir(dir) && file != "mod.rs") {
|
|
return None;
|
|
}
|
|
let (name, parent) = if file == "mod.rs" { dir.rsplit_once('/').map(|(p, n)| (n, p))? } else { (file.strip_suffix(".rs")?, dir) };
|
|
let mut candidates: Vec<String> = ["mod.rs", "lib.rs", "main.rs"].iter().map(|f| format!("{parent}/{f}")).collect();
|
|
candidates.push(format!("{parent}.rs"));
|
|
Some((name, candidates))
|
|
}
|
|
|
|
/// Where a module file is loaded from: the file `path`, the name `name` it declares by default and
|
|
/// the inline modules `chain` (outermost first) its declaration must sit in.
|
|
struct Loaded<'a> {
|
|
path: &'a str,
|
|
name: &'a str,
|
|
chain: &'a [String],
|
|
}
|
|
|
|
/// The `cfg` predicates under which `src`, the file `parent`, loads `want`: those on the
|
|
/// `mod <name>;` declarations that load it (by name, or through a `#[path]` override) and on the
|
|
/// items, inline modules and file around them, with the 1-based lines of those declarations and
|
|
/// attributes. Several declarations that load the file join into one `any(all(…), …)`. `None`
|
|
/// when `src` loads no such file. `owns_dir` reads `parent` as loaded through `#[path]`, which
|
|
/// declares its modules in its own directory, as a `mod.rs` or a crate root does. `via` keeps only
|
|
/// the declarations that load `want` by name (`Named`) or through `#[path]` (`Path`).
|
|
fn declared_cfgs(src: &str, parent: &str, want: &Loaded, owns_dir: bool, via: Via) -> Option<(Vec<String>, Vec<usize>)> {
|
|
let m = mask(src);
|
|
let lines = Lines::new(src);
|
|
let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent));
|
|
let mod_rs = owns_dir || owns_its_dir(parent);
|
|
let mut default_dir = if mod_rs { dir.to_owned() } else { join_path(dir, file.strip_suffix(".rs").unwrap_or(file)) };
|
|
for seg in want.chain {
|
|
default_dir = join_path(&default_dir, seg);
|
|
}
|
|
let (mut each, mut at_lines) = (vec![], vec![]);
|
|
// The file's `cfg` attributes, read on the first declaration that loads `want`.
|
|
let mut spans: Option<Vec<CfgSpan>> = None;
|
|
for at in words(&m, b"mod", 0, m.len()) {
|
|
let start = skip_ws(&m, at + 3);
|
|
let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count();
|
|
if end == start || m.get(skip_ws(&m, end)) != Some(&b';') {
|
|
continue;
|
|
}
|
|
// The conditions under which the inline modules around the declaration resolve to `want.chain`.
|
|
let mut via_chain: Vec<Vec<String>> =
|
|
inline_routes(&m, src.as_bytes(), at).into_iter().filter(|(c, _)| c == want.chain).map(|(_, k)| k).collect();
|
|
let inline_cond = match via_chain.len() {
|
|
0 => continue,
|
|
1 => via_chain.pop().filter(|k| !k.is_empty()).map(|k| format!("all({})", k.join(","))),
|
|
_ => Some(format!("any({})", via_chain.iter().map(|k| format!("all({})", k.join(","))).collect::<Vec<_>>().join(","))),
|
|
};
|
|
let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1);
|
|
// A `cfg_attr` override loads its path where its condition holds, and the default (or a
|
|
// plain `#[path]`) elsewhere.
|
|
let conditional = cfg_attr_paths(&m, src.as_bytes(), item, at);
|
|
let overrides_here = |rel: &str| override_path(dir, file, mod_rs, want.chain, rel) == want.path;
|
|
let fallback = match path_attr(&m, src.as_bytes(), item, at) {
|
|
Some(rel) => via != Via::Named && overrides_here(&rel),
|
|
None => {
|
|
via != Via::Path
|
|
&& &m[start..end] == want.name.as_bytes()
|
|
&& [format!("{}.rs", want.name), format!("{}/mod.rs", want.name)].iter().any(|rel| join_path(&default_dir, rel) == want.path)
|
|
}
|
|
};
|
|
let selected: Vec<&str> = conditional.iter().filter(|(_, rel)| via != Via::Named && overrides_here(rel)).map(|(c, _)| c.as_str()).collect();
|
|
let route = match (fallback, selected.is_empty(), conditional.is_empty()) {
|
|
(true, _, true) => None,
|
|
(true, true, false) => Some(format!("not(any({}))", conditional.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>().join(","))),
|
|
(true, false, false) => {
|
|
let others: Vec<&str> = conditional.iter().filter(|(_, rel)| !overrides_here(rel)).map(|(c, _)| c.as_str()).collect();
|
|
(!others.is_empty()).then(|| format!("not(any({}))", others.join(",")))
|
|
}
|
|
(false, true, _) => continue,
|
|
(false, false, _) => Some(format!("any({})", selected.join(","))),
|
|
};
|
|
// Inner attributes cover the file, and [`cfgs_at`] reads them.
|
|
let attrs: Vec<CfgAttr> = cfg_attrs(&m, src.as_bytes(), item, at).into_iter().filter(|a| !a.inner).collect();
|
|
at_lines.push(lines.of(at));
|
|
// Every line of a multiline attribute counts: an edit inside its predicate changes it.
|
|
at_lines.extend(attrs.iter().flat_map(|a| lines.of(a.at)..=lines.of(a.end)));
|
|
let mut preds: Vec<String> = attrs.into_iter().map(|a| a.pred).collect();
|
|
if let Some(route) = route {
|
|
preds.push(route);
|
|
at_lines.extend(lines.of(skip_ws(&m, item))..=lines.of(at));
|
|
}
|
|
preds.extend(inline_cond);
|
|
for (p, a, e) in cfgs_at(spans.get_or_insert_with(|| cfg_spans(&m, src.as_bytes())), at) {
|
|
preds.push(p);
|
|
at_lines.extend(lines.of(a)..=lines.of(e));
|
|
}
|
|
each.push(preds);
|
|
}
|
|
let preds = match each.len() {
|
|
0 => return None,
|
|
1 => each.pop().unwrap_or_default(),
|
|
_ => vec![format!("any({})", each.iter().map(|p| format!("all({})", p.join(","))).collect::<Vec<_>>().join(","))],
|
|
};
|
|
Some((preds, at_lines))
|
|
}
|
|
|
|
/// The file a `#[path = "<rel>"]` declaration in the file `dir/file` loads. Outside inline modules
|
|
/// `rel` is relative to the file's directory; inside them (`chain`, outermost first), to the inline
|
|
/// modules' directory under the file's module.
|
|
fn override_path(dir: &str, file: &str, mod_rs: bool, chain: &[String], rel: &str) -> String {
|
|
let mut base = dir.to_owned();
|
|
if !chain.is_empty() && !mod_rs {
|
|
base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file));
|
|
}
|
|
for seg in chain {
|
|
base = join_path(&base, seg);
|
|
}
|
|
join_path(&base, rel)
|
|
}
|
|
|
|
/// The files that `#[path]` declarations in `src`, the file `parent`, load, each with the inline
|
|
/// modules its declaration sits in.
|
|
fn path_children(src: &str, parent: &str) -> Vec<(String, Vec<String>)> {
|
|
let m = mask(src);
|
|
let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent));
|
|
let mod_rs = owns_its_dir(parent);
|
|
let mut out = vec![];
|
|
for at in words(&m, b"mod", 0, m.len()) {
|
|
let start = skip_ws(&m, at + 3);
|
|
let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count();
|
|
if end == start || m.get(skip_ws(&m, end)) != Some(&b';') {
|
|
continue;
|
|
}
|
|
let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1);
|
|
let rels =
|
|
path_attr(&m, src.as_bytes(), item, at).into_iter().chain(cfg_attr_paths(&m, src.as_bytes(), item, at).into_iter().map(|(_, r)| r));
|
|
let chains: Vec<Vec<String>> = inline_routes(&m, src.as_bytes(), at).into_iter().map(|(chain, _)| chain).collect();
|
|
for rel in rels {
|
|
for chain in &chains {
|
|
out.push((override_path(dir, file, mod_rs, chain, &rel), chain.clone()));
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The files that load a module file through `#[path]`, keyed by the file they load: a sibling such
|
|
/// as `graphics.rs` loading `tests_graphics.rs` is not among the files [`module_parent`] names.
|
|
type Overrides = HashMap<String, Vec<(String, Vec<String>)>>;
|
|
|
|
/// Find the files carrying `#[path]` in the work tree or at `base`, then read that tree's sources.
|
|
fn discover_path_overrides(root: &Path, base: Option<&str>, read: &dyn Fn(&str) -> Option<String>) -> Overrides {
|
|
let with_path = match base {
|
|
// `-z` lists each path verbatim, NUL-terminated: without it Git quotes a non-ASCII path.
|
|
Some(base) => git(root, &["grep", "-z", "-l", "-w", "path", base, "--", "*.rs"]),
|
|
None => git(root, &["grep", "-z", "--untracked", "-l", "-w", "path", "--", "*.rs"]),
|
|
}
|
|
.unwrap_or_default();
|
|
listed_path_overrides(&with_path, base, read)
|
|
}
|
|
|
|
/// Read paths from `git grep -z -l` (NUL-separated), removing the revision prefix for a base-tree listing.
|
|
fn listed_path_overrides(list: &str, base: Option<&str>, read: &dyn Fn(&str) -> Option<String>) -> Overrides {
|
|
let prefix = base.map(|b| format!("{b}:"));
|
|
let sources: Vec<(String, String)> = list
|
|
.split('\0')
|
|
.filter(|p| !p.is_empty())
|
|
.filter_map(|p| match &prefix {
|
|
Some(prefix) => p.strip_prefix(prefix),
|
|
None => Some(p),
|
|
})
|
|
.filter(|p| is_scanned(p))
|
|
.filter_map(|p| read(p).map(|s| (p.to_owned(), s)))
|
|
.collect();
|
|
path_overrides(sources.iter().map(|(p, s)| (p.as_str(), s.as_str())))
|
|
}
|
|
|
|
/// [`Overrides`] for the files `sources`, as `(path, source)` pairs.
|
|
fn path_overrides<'a>(sources: impl IntoIterator<Item = (&'a str, &'a str)>) -> Overrides {
|
|
let mut out: Overrides = HashMap::new();
|
|
for (parent, src) in sources {
|
|
if !src.contains("path") {
|
|
continue;
|
|
}
|
|
for (child, chain) in path_children(src, parent) {
|
|
// One entry per parent and inline modules: [`declared_cfgs`] joins the declarations of
|
|
// one file in one module.
|
|
let routes = out.entry(child).or_default();
|
|
if !routes.iter().any(|(p, c)| p == parent && *c == chain) {
|
|
routes.push((parent.to_owned(), chain));
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The string value of a `#[path = "…"]` attribute in `m[from..to]`, written as an ordinary or a
|
|
/// raw string literal (`#[path = r"shared.rs"]`, `#[path = r#"shared.rs"#]`). The escapes of an
|
|
/// ordinary literal are decoded (`"\x63hild.rs"` names `child.rs`); a raw literal is read as written.
|
|
fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option<String> {
|
|
words(m, b"path", from, to).into_iter().find_map(|at| {
|
|
let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#"));
|
|
let eq = skip_ws(m, at + 4);
|
|
let mut q = skip_ws(m, eq + 1);
|
|
if !attr || m.get(eq) != Some(&b'=') {
|
|
return None;
|
|
}
|
|
let raw = m.get(q) == Some(&b'r');
|
|
let hashes = if raw {
|
|
let h = m[q + 1..].iter().take_while(|&&c| c == b'#').count();
|
|
q += 1 + h;
|
|
h
|
|
} else {
|
|
0
|
|
};
|
|
if m.get(q) != Some(&b'"') {
|
|
return None;
|
|
}
|
|
let close: Vec<u8> = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect();
|
|
let end = find(m, &close, q + 1)?;
|
|
let body = String::from_utf8_lossy(&src[q + 1..end]);
|
|
Some(if raw { body.into_owned() } else { unescape(&body) })
|
|
})
|
|
}
|
|
|
|
/// The value of a whitespace-free `path=<literal>` argument, for an ordinary or a raw string literal.
|
|
/// The escapes of an ordinary literal are decoded, as in [`path_attr`].
|
|
fn path_arg(arg: &str) -> Option<String> {
|
|
let lit = arg.strip_prefix("path=")?;
|
|
let body = whole_literal(lit).map(|l| &l[1..l.len() - 1])?;
|
|
Some(if lit.starts_with('"') { unescape(body) } else { body.to_owned() })
|
|
}
|
|
|
|
/// The `#[cfg_attr(<condition>, path = "…")]` overrides in `m[from..to]`, each as its condition and
|
|
/// path.
|
|
fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, String)> {
|
|
let mut out = vec![];
|
|
for at in words(m, b"cfg_attr", from, to) {
|
|
if !m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")) {
|
|
continue;
|
|
}
|
|
let open = skip_ws(m, at + "cfg_attr".len());
|
|
let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue };
|
|
let text = norm_outside_literals(&mask_parts(&String::from_utf8_lossy(&src[open + 1..close]), true, false));
|
|
let cuts = attr_commas(&text);
|
|
let Some(&first) = cuts.first() else { continue };
|
|
let mut start = first + 1;
|
|
for cut in cuts[1..].iter().copied().chain([text.len()]) {
|
|
let arg = text.get(start..cut).unwrap_or("");
|
|
if let Some(rel) = path_arg(arg) {
|
|
out.push((text[..first].to_owned(), rel));
|
|
}
|
|
start = cut + 1;
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// `rel` joined to the directory `base`, with `.` and `..` resolved.
|
|
fn join_path(base: &str, rel: &str) -> String {
|
|
let mut parts: Vec<&str> = base.split('/').filter(|s| !s.is_empty()).collect();
|
|
for seg in rel.split('/') {
|
|
match seg {
|
|
"" | "." => {}
|
|
".." => {
|
|
parts.pop();
|
|
}
|
|
s => parts.push(s),
|
|
}
|
|
}
|
|
parts.join("/")
|
|
}
|
|
|
|
/// The directory segments of the inline `mod <name> { … }` blocks around `at` in the masked text
|
|
/// `m` (`src` unmasked), outermost first. A `mod x;` inside them loads a file under their directory
|
|
/// instead of a sibling file. A block's directory is its name, or the value of a `#[path]` on it
|
|
/// (`#[path = "platform_impl"] mod platform { mod child; }` loads `platform_impl/child.rs`). A
|
|
/// `#[cfg_attr(<condition>, path = "…")]` on a block gives one route per directory: its path where
|
|
/// the condition holds, and the default elsewhere. Each route comes with the conditions it needs;
|
|
/// at most [`MAX_INLINE_ROUTES`] are kept.
|
|
fn inline_routes(m: &[u8], src: &[u8], at: usize) -> Vec<(Vec<String>, Vec<String>)> {
|
|
let mut routes: Vec<(String, Vec<String>)> = vec![(String::new(), vec![])];
|
|
for open in (0..at).filter(|&open| m[open] == b'{' && matching(m, open).is_some_and(|close| close > at)) {
|
|
let head = m[..open].trim_ascii_end();
|
|
let name = head.iter().rev().take_while(|&&c| is_ident(c)).count();
|
|
let before = head[..head.len() - name].trim_ascii_end();
|
|
if name == 0 || !before.ends_with(b"mod") || before[..before.len() - 3].last().copied().is_some_and(is_ident) {
|
|
continue;
|
|
}
|
|
let kw = before.len() - 3;
|
|
let item = m[..kw].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1);
|
|
let seg = path_attr(m, src, item, kw).unwrap_or_else(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned());
|
|
let conditional = cfg_attr_paths(m, src, item, kw);
|
|
let mut options: Vec<(String, Vec<String>)> = conditional.iter().map(|(c, rel)| (rel.clone(), vec![c.clone()])).collect();
|
|
let fallback =
|
|
(!conditional.is_empty()).then(|| format!("not(any({}))", conditional.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>().join(",")));
|
|
options.push((seg, fallback.into_iter().collect()));
|
|
routes = routes
|
|
.iter()
|
|
.flat_map(|(dir, conds)| options.iter().map(move |(seg, c)| (join_path(dir, seg), conds.iter().chain(c).cloned().collect())))
|
|
.take(MAX_INLINE_ROUTES)
|
|
.collect();
|
|
}
|
|
routes.into_iter().map(|(dir, conds)| (dir.split('/').filter(|s| !s.is_empty()).map(str::to_owned).collect(), conds)).collect()
|
|
}
|
|
|
|
/// The most routes [`inline_routes`] follows through nested conditional directories.
|
|
const MAX_INLINE_ROUTES: usize = 16;
|
|
|
|
/// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the
|
|
/// modules above it, read through `read`.
|
|
fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option<String>, overrides: &Overrides) -> HashMap<String, Vec<String>> {
|
|
module_gates(paths, read, overrides).into_iter().map(|(p, g)| (p, g.preds)).collect()
|
|
}
|
|
|
|
/// The `cfg` predicates a module file inherits ([`module_cfgs`]) and, for each file that declares
|
|
/// them, the lines of those declarations and attributes.
|
|
#[derive(Default)]
|
|
struct Gates {
|
|
preds: Vec<String>,
|
|
sources: Vec<(String, Vec<usize>)>,
|
|
/// Whether a crate target loads the file through at least one route.
|
|
reached: bool,
|
|
}
|
|
|
|
/// [`Gates`] for each of `paths` that inherits a predicate. A file is looked up in the files that
|
|
/// may declare its module and in the files above them through inline modules
|
|
/// (`mod platform { mod child; }` loads `platform/child.rs`), and in the files of `overrides` that
|
|
/// load it through `#[path]`.
|
|
fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option<String>, overrides: &Overrides) -> HashMap<String, Gates> {
|
|
let read = cached_read(read);
|
|
paths
|
|
.iter()
|
|
.filter_map(|path| {
|
|
let gates = module_gate(path, &read, overrides, 0, Via::Any);
|
|
(!gates.preds.is_empty()).then(|| (path.clone(), gates))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// The files of `paths` that a crate target loaded through a parent at the base (read through
|
|
/// `read_base`) and that no crate target loads now, each with the base files of its routes: a change
|
|
/// that removes the last `mod` or `#[path]` declaration on the way to a file compiles its tests out.
|
|
fn lost_routes(
|
|
paths: &[String],
|
|
read: &dyn Fn(&str) -> Option<String>,
|
|
overrides: &Overrides,
|
|
read_base: &dyn Fn(&str) -> Option<String>,
|
|
base_overrides: &Overrides,
|
|
) -> HashMap<String, Vec<String>> {
|
|
paths
|
|
.iter()
|
|
.filter_map(|path| {
|
|
let base = module_gate(path, read_base, base_overrides, 0, Via::Any);
|
|
// A head with no route at all is lost too: when no file that could load it is left, the
|
|
// parent is unknown and [`module_gate`] counts it as reached, but the base had one.
|
|
if !base.reached || base.sources.is_empty() || !module_gate(path, read, overrides, 0, Via::Any).sources.is_empty() {
|
|
return None;
|
|
}
|
|
Some((path.clone(), base.sources.into_iter().map(|(p, _)| p).collect()))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Which routes to a file [`module_gate`] follows: a file that is not a `mod.rs` or a crate root
|
|
/// declares its modules in a directory named after it when a `mod <name>;` loads it (`Named`), and
|
|
/// in its own directory when a `#[path]` loads it (`Path`).
|
|
#[derive(Clone, Copy, PartialEq)]
|
|
enum Via {
|
|
Any,
|
|
Named,
|
|
Path,
|
|
}
|
|
|
|
/// Resolve each route's ancestors before joining routes, with a bound for cyclic module paths.
|
|
fn module_gate(at: &str, read: &dyn Fn(&str) -> Option<String>, overrides: &Overrides, depth: usize, via: Via) -> Gates {
|
|
let mut gates = Gates::default();
|
|
if depth >= 16 {
|
|
return gates;
|
|
}
|
|
let by_path = if via == Via::Named { &[][..] } else { overrides.get(at).map_or(&[][..], Vec::as_slice) };
|
|
// A crate root runs independently of any module declarations that also load it.
|
|
let Some((name, mut candidates)) = module_parent(at) else {
|
|
gates.reached = true;
|
|
return gates;
|
|
};
|
|
let name = name.to_owned();
|
|
let file = at.rsplit_once('/').map_or(at, |(_, f)| f);
|
|
let Some(mut module_dir) = (if file == "mod.rs" {
|
|
at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned())
|
|
} else {
|
|
at.rsplit_once('/').map(|(d, _)| d.to_owned())
|
|
}) else {
|
|
gates.reached = true;
|
|
return gates;
|
|
};
|
|
let mut chain: Vec<String> = vec![];
|
|
// Each file that loads the module, what it declares, and the routes to it that load the module
|
|
// from there.
|
|
let mut found = vec![];
|
|
// Whether a file that could declare the module exists: when none does, the module's parent is
|
|
// unknown and the file counts as reached.
|
|
let mut parent_read = false;
|
|
// A parent that is neither a `mod.rs` nor a crate root loads the module only through its
|
|
// `mod <name>;` routes.
|
|
let named = |c: &str| if owns_its_dir(c) { Via::Any } else { Via::Named };
|
|
for _ in 0..4 {
|
|
let want = Loaded { path: at, name: &name, chain: &chain };
|
|
// Every file that loads the module is another way in (a library and a binary root
|
|
// can both load it): its tests are off only when every one of them leaves them out.
|
|
if via != Via::Path {
|
|
found.extend(candidates.iter().filter_map(|c| {
|
|
read(c).inspect(|_| parent_read = true).and_then(|s| declared_cfgs(&s, c, &want, false, via)).map(|f| (c.clone(), f, named(c)))
|
|
}));
|
|
}
|
|
if chain.is_empty() {
|
|
for (c, inline) in by_path {
|
|
// A candidate was read with no inline modules; another route through the
|
|
// same file still counts.
|
|
if via != Via::Path && inline.is_empty() && candidates.contains(c) {
|
|
continue;
|
|
}
|
|
let want = Loaded { path: at, name: &name, chain: inline };
|
|
found.extend(read(c).and_then(|s| declared_cfgs(&s, c, &want, false, via)).map(|f| (c.clone(), f, Via::Any)));
|
|
}
|
|
// A file loaded through `#[path]` owns its directory like a `mod.rs`: its `mod child;`
|
|
// loads the `child.rs` beside it (`impl/platform.rs` loads `impl/child.rs`).
|
|
let path_loaded = overrides
|
|
.keys()
|
|
.filter(|k| via != Via::Path && k.as_str() != at && !owns_its_dir(k) && k.rsplit_once('/').is_some_and(|(d, _)| d == module_dir));
|
|
for owner in path_loaded {
|
|
found.extend(read(owner).and_then(|s| declared_cfgs(&s, owner, &want, true, via)).map(|f| (owner.clone(), f, Via::Path)));
|
|
}
|
|
}
|
|
if via == Via::Path || beside_roots(at) {
|
|
break;
|
|
}
|
|
let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break };
|
|
let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break };
|
|
chain.insert(0, seg);
|
|
candidates = next;
|
|
module_dir = up;
|
|
}
|
|
let mut each = vec![];
|
|
// Through `#[path]` alone, a file no `#[path]` declaration loads is not reached.
|
|
gates.reached = found.is_empty() && !parent_read && via != Via::Path;
|
|
for (parent, (mut preds, lines), parent_via) in found {
|
|
let ancestors = module_gate(&parent, read, overrides, depth + 1, parent_via);
|
|
// A parent that no crate target loads (a file left on disk after its `mod` line was
|
|
// removed) is not a route, so it cannot stand in for an ungated one.
|
|
if !ancestors.reached {
|
|
continue;
|
|
}
|
|
gates.reached = true;
|
|
preds.extend(ancestors.preds);
|
|
gates.sources.push((parent, lines));
|
|
gates.sources.extend(ancestors.sources);
|
|
each.push(preds);
|
|
}
|
|
gates.preds = match each.len() {
|
|
0 => vec![],
|
|
1 => each.pop().unwrap_or_default(),
|
|
_ => vec![format!("any({})", each.iter().map(|p| format!("all({})", p.join(","))).collect::<Vec<_>>().join(","))],
|
|
};
|
|
gates
|
|
}
|
|
|
|
/// A test that a `cfg` compiles out on every target CI runs tests on.
|
|
fn never_run(v: &View, ctx: &Ctx) -> Option<Hit> {
|
|
let local = cfgs_at(&v.file.cfgs, v.t.fn_at);
|
|
// A change to an attribute that turns the test off counts as a change to the test, on any line
|
|
// of a multiline attribute.
|
|
// An attribute whose predicate holds on every target CI tests on (`unix` without Windows) does
|
|
// not turn the test off, so its lines do not count.
|
|
let windows = windows_runs(v.file.path).then_some(&WINDOWS_TARGET);
|
|
let excludes = |p: &str| !CI_TARGETS.iter().chain(windows).all(|t| cfg_value(p, t) == Some(true));
|
|
let attr_lines: Vec<usize> =
|
|
local.iter().filter(|(p, _, _)| excludes(p)).flat_map(|&(_, at, end)| v.file.lines.of(at)..=v.file.lines.of(end)).collect();
|
|
let mut preds: Vec<String> = local.into_iter().map(|(p, _, _)| p).collect();
|
|
preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned());
|
|
if preds.is_empty() {
|
|
return None;
|
|
}
|
|
let off = |t: &Target| preds.iter().any(|p| cfg_value(p, t) == Some(false));
|
|
if CI_TARGETS.iter().chain(windows).all(off) {
|
|
let shown: Vec<String> = preds.iter().filter(|p| p.as_str() != "test").map(|p| format!("cfg({p})")).collect();
|
|
let mut note = format!("{} leaves it out of every target CI tests on", shown.join(", "));
|
|
let mut builds: Vec<&str> = PLATFORM_TARGETS.iter().filter(|(_, t)| !off(t)).map(|(name, _)| *name).collect();
|
|
builds.dedup();
|
|
if !builds.is_empty() {
|
|
note += &format!("; it builds on {}, so run it there", builds.join(" and "));
|
|
}
|
|
let mut hit = v.whole(Rule::NeverRun, note);
|
|
hit.report_only = !builds.is_empty();
|
|
// Enclosing attributes count as separate lines, so an edit to code between them and the
|
|
// test does not count.
|
|
hit.gates = attr_lines.into_iter().filter(|&l| l < hit.first).collect();
|
|
return Some(hit);
|
|
}
|
|
None
|
|
}
|
|
|
|
/// What may follow a screen rect in an exact-pixel comparison: a corner, an edge or a size.
|
|
const RECT_PARTS: &[&str] = &[
|
|
".min",
|
|
".max",
|
|
".left_top()",
|
|
".right_bottom()",
|
|
".center()",
|
|
".size()",
|
|
".width()",
|
|
".height()",
|
|
".left()",
|
|
".right()",
|
|
".top()",
|
|
".bottom()",
|
|
];
|
|
|
|
/// Whether a whitespace-free operand reads a screen rect: an identifier `rect`, or one that starts
|
|
/// with `rect_` or ends with `_rect` (a call to one included), taken whole or through
|
|
/// [`RECT_PARTS`]. Document geometry (artboards, `x0`/`y0` corners, a document's nodes) and a rect
|
|
/// passed on as an argument do not count.
|
|
fn names_rect(op: &str) -> bool {
|
|
if ["artboard", ".x0", ".y0", ".x1", ".y1", "obox"].iter().any(|w| op.contains(w)) {
|
|
return false;
|
|
}
|
|
let document = |w: &str| w == "doc" || w == "document" || w.starts_with("doc_") || w.ends_with("_doc");
|
|
if op.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).any(document) {
|
|
return false;
|
|
}
|
|
let b = op.as_bytes();
|
|
let mut i = 0;
|
|
while i < b.len() {
|
|
if !is_ident(b[i]) || (i > 0 && is_ident(b[i - 1])) {
|
|
i += 1;
|
|
continue;
|
|
}
|
|
let end = i + b[i..].iter().take_while(|&&c| is_ident(c)).count();
|
|
let w = &op[i..end];
|
|
if w == "rect" || w.starts_with("rect_") || w.ends_with("_rect") {
|
|
let mut after = end;
|
|
if b.get(after) == Some(&b'(') {
|
|
after = matching(b, after).map_or(b.len(), |c| c + 1);
|
|
}
|
|
// The rect and its parts make up the whole operand: `a.width() - b.width()` compares two
|
|
// rects, not one with a number.
|
|
let mut rest = &op[after..];
|
|
while let Some(r) = RECT_PARTS.iter().chain(&[".x", ".y"]).find_map(|p| rest.strip_prefix(p)) {
|
|
rest = r;
|
|
}
|
|
// Only grouping parentheses may surround it: in `count_items(button_rect)` the rect is a
|
|
// call's argument, and the operand is what the call returns.
|
|
let lead = op[..i].trim_start_matches(['&', '*']);
|
|
let lb = lead.as_bytes();
|
|
let call = (1..lb.len()).any(|k| lb[k] == b'(' && (is_ident(lb[k - 1]) || matches!(lb[k - 1], b'!' | b'>')));
|
|
let groups = lead.matches('(').count();
|
|
let path = lead.trim_start_matches(['&', '*', '(']);
|
|
if !call && rest.len() == groups && rest.bytes().all(|c| c == b')') && !path.contains(['+', '-', '*', '/', '%', ',', '(']) {
|
|
return true;
|
|
}
|
|
}
|
|
i = end;
|
|
}
|
|
false
|
|
}
|
|
|
|
/// Whether a whitespace-free operand is only numbers, alone or in `pos2`, `vec2` or `Rect` builders.
|
|
fn only_numbers(op: &str) -> bool {
|
|
let mut rest = op.trim_start_matches('&').replace("egui::", "").replace("emath::", "");
|
|
for builder in ["Rect::from_min_max", "Rect::from_min_size", "Rect::from_center_size", "Pos2::new", "Vec2::new", "pos2", "vec2", "Some"] {
|
|
rest = rest.replace(builder, "");
|
|
}
|
|
let rest = rest.replace("f32", "");
|
|
rest.bytes().any(|c| c.is_ascii_digit()) && rest.bytes().all(|c| c.is_ascii_digit() || b".,()-+_".contains(&c))
|
|
}
|
|
|
|
/// An assertion in a UI test that a rect, or a coordinate or size of one, equals numbers written out.
|
|
fn exact_pixels(v: &View) -> Vec<Hit> {
|
|
if !contains(&v.file.m, b"egui") {
|
|
return vec![];
|
|
}
|
|
v.asserts
|
|
.iter()
|
|
.filter_map(|a| {
|
|
let arg = |i: usize| a.args.get(i).map(|&(f, t)| norm(&v.file.m[f..t]));
|
|
let (l, r) = if a.name.ends_with("_eq") {
|
|
(arg(0)?, arg(1)?)
|
|
} else if PLAIN_ASSERTS.contains(&a.name.as_str()) {
|
|
let cond = arg(0)?;
|
|
let at = *top_level_at(&cond, "==").first()?;
|
|
(cond[..at].to_owned(), cond[at + 2..].to_owned())
|
|
} else {
|
|
return None;
|
|
};
|
|
let pixel = (names_rect(&l) && only_numbers(&r)) || (names_rect(&r) && only_numbers(&l));
|
|
pixel.then(|| v.hit(a.at, Rule::ExactPixel, format!("{}! compares a rect with numbers written out", a.name)))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn ctx() -> Ctx {
|
|
Ctx { ci_env: ["SET_IN_CI".to_owned()].into_iter().collect(), ..Ctx::default() }
|
|
}
|
|
|
|
/// 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 census_round_trips_look_up_the_entry() {
|
|
let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
|
let fixed = "#[test]\nfn t() {\n for expected in CASES {\n assert_eq!(lookup(\"baseline\"), expected);\n }\n}\n";
|
|
assert_eq!(census(fixed), [], "a lookup of a fixed key is not a round trip of the entry");
|
|
let cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(k as usize), k);\n }\n}\n";
|
|
assert_eq!(census(cast), [(2, "census")], "a cast of the entry is still the entry");
|
|
let fixed_cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(FIXED as usize), k);\n }\n}\n";
|
|
assert_eq!(census(fixed_cast), [], "a cast of a fixed key");
|
|
let one_word = "#[test]\nfn t() {\n let kasusize = 3;\n for k in KEYS {\n assert_eq!(lookup(kasusize), k);\n }\n}\n";
|
|
assert_eq!(census(one_word), [], "a fixed local spelled like a cast of the entry");
|
|
let field =
|
|
"#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(config.k), k);\n assert_eq!(lookup(keys::k), k);\n }\n}\n";
|
|
assert_eq!(census(field), [], "a field or path named like the binding is a fixed key");
|
|
let derived = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id()), Some(k));\n }\n}\n";
|
|
assert_eq!(census(derived), [(2, "census")]);
|
|
let successor = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(1 + lookup(k), k);\n }\n}\n";
|
|
assert_eq!(census(successor), [], "arithmetic before the lookup checks a successor, not a round trip");
|
|
}
|
|
|
|
#[test]
|
|
fn census_loops_over_whole_tables_are_reported() {
|
|
let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
|
let consts = "#[test]\nfn t() {\n for c in COLORS.iter() {\n assert!(!c.name.is_empty());\n }\n}\n";
|
|
assert_eq!(census(consts), [(2, "census")]);
|
|
let round = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id()), Some(k));\n }\n}\n";
|
|
assert_eq!(census(round), [(2, "census")]);
|
|
let call = "#[test]\nfn t() {\n for p in builtin_presets() {\n assert!(lookup(&p.name).is_some());\n }\n}\n";
|
|
assert_eq!(census(call), [(2, "census")]);
|
|
let all = "#[test]\nfn t() {\n assert!(Swatch::iter().all(|s| s.rgb().is_some()));\n}\n";
|
|
assert_eq!(census(all), [(2, "census")]);
|
|
let behavior = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(apply(k, 2), 4);\n }\n}\n";
|
|
assert_eq!(census(behavior), [], "a computed result for each entry is a real check");
|
|
let mixed = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some());\n assert_eq!(blend(c), WHITE);\n }\n}\n";
|
|
assert_eq!(census(mixed), [], "one real assertion in the loop keeps it");
|
|
let joined = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some() && blend(c) == WHITE);\n }\n assert!(Swatch::iter().all(|s| s.rgb().is_some() && s.rgb() != BLACK));\n}\n";
|
|
assert_eq!(census(joined), [], "a presence guard joined to a real check");
|
|
let both = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some() && !c.name.is_empty());\n }\n}\n";
|
|
assert_eq!(census(both), [(2, "census")]);
|
|
let few = "#[test]\nfn t() {\n for c in COLORS.iter().take(2) {\n assert!(c.is_some());\n }\n for c in &COLORS[..2] {\n assert!(c.is_some());\n }\n}\n";
|
|
assert_eq!(census(few), [], "a few representative entries");
|
|
let expected = "#[test]\nfn t() {\n for case in CASES {\n assert_eq!(parse(case.input), case.expected);\n assert_eq!(sparse(case), case);\n }\n}\n";
|
|
assert_eq!(census(expected), [], "an expected value written in the table, and a name that only ends in parse");
|
|
let helper = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some());\n check_render(c);\n }\n}\n";
|
|
assert_eq!(census(helper), [], "an asserting helper in the loop");
|
|
let local = "#[test]\nfn t() {\n for x in xs.iter() {\n assert!(x.is_some());\n }\n}\n";
|
|
assert_eq!(census(local), [], "a local collection is not a table");
|
|
let allowed = "// test-lint: allow census every command needs a menu path\n#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c).is_some());\n }\n}\n";
|
|
assert_eq!(census(allowed), []);
|
|
for ne in ["assert_ne!(Kind::from_id(k.id()), Some(k))", "debug_assert_ne!(lookup(k), k)", "prop_assert_ne!(Kind::parse(k.name()), Ok(k))"] {
|
|
let rejects = format!("#[test]\nfn t() {{\n for k in Kind::ALL {{\n {ne};\n }}\n}}\n");
|
|
assert_eq!(census(&rejects), [], "an inequality is not a round trip: {ne}");
|
|
}
|
|
let borrowed = "#[test]\nfn t() {\n for k in &Kind::ALL {\n assert_eq!(Kind::from_id(k.id()).as_ref(), Some(k));\n }\n}\n";
|
|
assert_eq!(census(borrowed), [(2, "census")]);
|
|
let both_all = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) && LABELS.iter().all(|s| !s.is_empty()));\n}\n";
|
|
assert_eq!(census(both_all), [(2, "census")]);
|
|
let either = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) || actual == expected);\n}\n";
|
|
assert_eq!(census(either), [(2, "census")], "an || lets the presence branch pass alone");
|
|
let long = format!(
|
|
"#[test]\nfn t() {{\n assert!(COLORS.iter().all(|c| c.is_some()){});\n}}\n",
|
|
"&&COLORS.iter().all(|c|c.is_some())".repeat(200)
|
|
);
|
|
assert_eq!(census(&long), [], "a chain deeper than the limit is not judged");
|
|
let inner = "#[test]\nfn t() {\n for a in COLORS.iter().map(|c| c.aliases.iter().filter_map(|a| a.id()).next()) {\n assert!(a.is_some());\n }\n}\n";
|
|
assert_eq!(census(inner), [(2, "census")]);
|
|
let accented = "#[test]\nfn t() {\n for c in COLORS.iter().clonés() {\n assert!(c.is_some());\n }\n}\n";
|
|
assert_eq!(census(accented), [(2, "census")], "a non-ASCII method name is read without panicking");
|
|
let nested = "#[test]\nfn t() {\n assert!(COLORS.iter().map(|c| c.parts.iter().all(|p| p.ok)).all(|c| c.is_some()));\n}\n";
|
|
assert_eq!(census(nested), [(2, "census")]);
|
|
let wrapped = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Some(Kind::parse(k.name()).unwrap()), Some(k));\n }\n}\n";
|
|
assert_eq!(census(wrapped), [(2, "census")]);
|
|
let derived = "#[test]\nfn t() {\n for n in COUNTS {\n assert_eq!(parse(&src(n)).unwrap().children.len(), n);\n }\n}\n";
|
|
assert_eq!(census(derived), [], "a value derived from the parsed entry is a real check");
|
|
let unwrapped = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::parse(k.name()).unwrap(), k);\n }\n}\n";
|
|
assert_eq!(census(unwrapped), [(2, "census")]);
|
|
let all_joined = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) && actual == expected);\n}\n";
|
|
assert_eq!(census(all_joined), [], "an .all(…) presence check joined to a real check");
|
|
let subsets = "#[test]\nfn t() {\n for c in COLORS.iter().filter_map(|c| c.alt) {\n assert!(c.is_some());\n }\n for c in COLORS.iter().take_while(|c| c.light) {\n assert!(c.is_some());\n }\n for c in COLORS.iter().skip_while(|c| c.light) {\n assert!(c.is_some());\n }\n for c in COLORS.iter().map_while(|c| c.alt) {\n assert!(c.is_some());\n }\n}\n";
|
|
assert_eq!(census(subsets), [], "subset adapters pick a few entries");
|
|
}
|
|
|
|
#[test]
|
|
fn census_skips_derived_lookups_and_deep_nesting() {
|
|
let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
|
let offset = "#[test]\nfn t() {\n for n in COUNTS {\n assert_eq!(offset + lookup(n).unwrap(), n);\n }\n}\n";
|
|
assert_eq!(census(offset), [], "an operator before the lookup derives a value");
|
|
let referenced = "#[test]\nfn t() {\n for n in COUNTS {\n assert_eq!(mask & lookup(n).unwrap(), n);\n }\n}\n";
|
|
assert_eq!(census(referenced), [], "a bitwise and before the lookup derives a value");
|
|
let qualified = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::parse(k.name()).unwrap(), k);\n }\n}\n";
|
|
assert_eq!(census(qualified), [(2, "census")]);
|
|
let deep =
|
|
format!("#[test]\nfn t() {{\n for c in COLORS {{\n assert!({}c.is_some(){});\n }}\n}}\n", "(".repeat(66), ")".repeat(66));
|
|
assert_eq!(census(&deep), [], "nesting deeper than the limit is not judged");
|
|
}
|
|
|
|
#[test]
|
|
fn census_skips_loops_bounded_by_zip_or_flat_map() {
|
|
let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
|
let zipped = "#[test]\nfn t() {\n for (c, l) in COLORS.iter().zip(labels.iter().take(2)) {\n assert!(c.is_some());\n }\n}\n";
|
|
assert_eq!(census(zipped), [], "a bounded iterator zipped in bounds the loop");
|
|
let ranged = "#[test]\nfn t() {\n for (c, i) in COLORS.iter().zip(0..2) {\n assert!(c.is_some());\n }\n}\n";
|
|
assert_eq!(census(ranged), [], "a range zipped in bounds the loop");
|
|
for range in ["0..", "0..,", "(0..)", "((0..)),", "std::iter::repeat(0..2)"] {
|
|
let open = format!("#[test]\nfn t() {{\n for (c, i) in COLORS.iter().zip({range}) {{\n assert!(c.is_some());\n }}\n}}\n");
|
|
assert_eq!(census(&open), [(2, "census")], "an open-ended range zipped in visits every entry: {range}");
|
|
}
|
|
let flat = "#[test]\nfn t() {\n for e in GROUPS.iter().flat_map(|g| g.es.iter().take(1)) {\n assert!(e.is_some());\n }\n}\n";
|
|
assert_eq!(census(flat), [], "a bounded iterator returned by flat_map bounds the loop");
|
|
}
|
|
|
|
#[test]
|
|
fn census_counts_rejections_and_helpers_as_checks() {
|
|
let census_in = |src: &str, ctx: &Ctx| hits_in("crates/x/src/tests.rs", src, ctx).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
|
let rejected = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).unwrap_err();\n }\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).expect_err(\"rejects\");\n }\n}\n";
|
|
assert_eq!(census_in(rejected, &ctx()), [], "an unwrap_err or expect_err in the loop checks a rejection");
|
|
let spaced = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).unwrap_err ();\n }\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).expect_err (\"rejects\");\n }\n}\n";
|
|
assert_eq!(census_in(spaced, &ctx()), [], "whitespace inside the rejection call");
|
|
let all_rejects = "#[test]\nfn t() {\n assert!(CASES.iter().all(|c| parse(c.bad).unwrap_err().contains(\"bad\")));\n assert!(CASES.iter().all(|c| parse(c.bad).expect_err(\"rejects\").contains(\"bad\")));\n}\n";
|
|
assert_eq!(census_in(all_rejects, &ctx()), [], "an unwrap_err or expect_err in the .all(…) predicate checks a rejection");
|
|
let skips = "#[test]\nfn t() {\n assert!(CASES.iter().all(|c| c.is_some() || parse(c.bad).unwrap_err().contains(\"bad\")));\n}\n";
|
|
assert_eq!(census_in(skips, &ctx()), [(2, "census")], "a rejection after a presence check on an || can be skipped");
|
|
let first = "#[test]\nfn t() {\n assert!(parse(invalid).unwrap_err().contains(\"bad\") || CASES.iter().all(|c| c.is_some()));\n}\n";
|
|
assert_eq!(census_in(first, &ctx()), [], "a rejection on the left of an || always runs");
|
|
let and_rejects = "#[test]\nfn t() {\n assert!(CASES.iter().all(|c| c.is_some()) && parse(invalid).unwrap_err().is_empty());\n}\n";
|
|
assert_eq!(census_in(and_rejects, &ctx()), [], "a rejection on the other side of an && always runs");
|
|
let broken = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some());\n break;\n }\n}\n";
|
|
assert_eq!(census_in(broken, &ctx()), [], "a break can end the loop before the last entry");
|
|
assert_eq!(census_in(&broken.replace(" break;\n", ""), &ctx()), [(2, "census")]);
|
|
let only_ok = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n }\n}\n";
|
|
assert_eq!(census_in(only_ok, &ctx()), [(2, "census")]);
|
|
let all_helper = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| exercise(c).is_some()));\n}\nfn exercise(c: &Color) -> Option<()> {\n assert_eq!(blend(c), WHITE);\n Some(())\n}\n";
|
|
let files = [("crates/x/src/tests.rs".to_owned(), all_helper.to_owned())];
|
|
let with_helpers = Ctx { helpers: asserting_helpers(&files), ..ctx() };
|
|
assert_eq!(census_in(all_helper, &with_helpers), [], "an asserting helper in the .all(…) predicate");
|
|
assert_eq!(census_in(all_helper, &ctx()), [(2, "census")], "a predicate whose call does not assert");
|
|
let message =
|
|
"#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok(),\"{:?}\", probe().unwrap_err());\n }\n}\n";
|
|
assert_eq!(census_in(message, &ctx()), [(2, "census")], "an unwrap_err in a failure message runs only after a failure");
|
|
let skipped = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) || verify_fallback());\n}\n";
|
|
assert_eq!(census_in(skipped, &ctx()), [(2, "census")], "a helper on the other side of an || can be skipped");
|
|
let inner = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some() || verify_fallback(c).is_some()));\n}\n";
|
|
assert_eq!(census_in(inner, &ctx()), [(2, "census")], "a helper inside the predicate behind an || can be skipped");
|
|
let outer = "#[test]\nfn t() {\n assert!(verify_entry() || COLORS.iter().all(|c| c.is_some()));\n}\n";
|
|
assert_eq!(census_in(outer, &ctx()), [], "a helper on the left of an outer || always runs");
|
|
let in_message = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some(), \"{:?}\", verify_entry(c));\n }\n}\n";
|
|
assert_eq!(census_in(in_message, &ctx()), [(2, "census")], "a helper in a failure message runs only after a failure");
|
|
let first = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| verify_entry(c) || c.is_some()));\n}\n";
|
|
assert_eq!(census_in(first, &ctx()), [], "a helper on the left of an || always runs");
|
|
let generic = all_helper.replace("exercise(c)", "exercise::<Color>(c)");
|
|
assert_eq!(census_in(&generic, &with_helpers), [], "a helper called with a turbofish");
|
|
let enforced = "#[test]\nfn t() {\n for case in CASES {\n assert!(!case.is_empty());\n let Ok(_) = parse(case) else { panic!(\"parse failed\") };\n }\n}\n";
|
|
assert_eq!(census_in(enforced, &ctx()), [(2, "census")], "a panic that only enforces success");
|
|
let mapped = "#[test]\nfn t() {\n assert!(COLORS.iter().map(|c| { verify_entry(c); c }).all(|c| c.is_some()));\n}\n";
|
|
assert_eq!(census_in(mapped, &ctx()), [], "a helper in the .all(…) receiver runs for every entry");
|
|
assert_eq!(census_in(&mapped.replace("verify_entry(c); ", ""), &ctx()), [(2, "census")]);
|
|
let sourced = "#[test]\nfn t() {\n for c in COLORS.iter().map(|c| { verify_entry(c); c }) {\n assert!(c.is_some());\n }\n}\n";
|
|
assert_eq!(census_in(sourced, &ctx()), [], "a helper in the loop source runs for every entry");
|
|
assert_eq!(census_in(&sourced.replace("verify_entry(c); ", ""), &ctx()), [(2, "census")]);
|
|
let refused = "#[test]\nfn t() {\n for case in CASES {\n assert!(!parse(case.invalid).is_ok());\n }\n for case in CASES {\n assert!(!lookup(case.missing).is_some());\n }\n}\n";
|
|
assert_eq!(census_in(refused, &ctx()), [], "a negated is_ok or is_some checks a rejection");
|
|
let filled = "#[test]\nfn t() {\n for c in COLORS {\n assert!(!c.name.is_empty());\n }\n}\n";
|
|
assert_eq!(census_in(filled, &ctx()), [(2, "census")]);
|
|
}
|
|
|
|
#[test]
|
|
fn census_counts_a_helper_on_the_left_of_an_or_only_when_it_always_runs() {
|
|
let census_in = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
|
let guarded = "#[test]\nfn t() {\n assert!((ready && verify_entry()) || COLORS.iter().all(|c| c.is_some()));\n}\n";
|
|
assert_eq!(census_in(guarded), [(2, "census")], "a helper behind an && on the left is skipped when ready is false");
|
|
let arm = "#[test]\nfn t() {\n assert!((if ready { verify_entry() } else { false }) || COLORS.iter().all(|c| c.is_some()));\n}\n";
|
|
assert_eq!(census_in(arm), [(2, "census")], "a helper in one arm of an if on the left is skipped when ready is false");
|
|
let scrutinee = "#[test]\nfn t() {\n assert!((if verify_entry() { true } else { false }) || COLORS.iter().all(|c| c.is_some()));\n}\n";
|
|
assert_eq!(census_in(scrutinee), [], "the condition of an if on the left always runs");
|
|
let block = "#[test]\nfn t() {\n assert!(({ verify_entry(); false }) || COLORS.iter().all(|c| c.is_some()));\n}\n";
|
|
assert_eq!(census_in(block), [], "a plain block on the left always runs its statements");
|
|
let block_if = "#[test]\nfn t() {\n assert!(({ if ready { verify_entry(); } false }) || COLORS.iter().all(|c| c.is_some()));\n}\n";
|
|
assert_eq!(census_in(block_if), [(2, "census")], "a helper in an if inside a block on the left can be skipped");
|
|
let after_if =
|
|
"#[test]\nfn t() {\n assert!(({ if ready { setup(); } verify_entry(); false }) || COLORS.iter().all(|c| c.is_some()));\n}\n";
|
|
assert_eq!(census_in(after_if), [], "a helper after an if statement in the block always runs");
|
|
}
|
|
|
|
#[test]
|
|
fn census_is_report_only() {
|
|
assert!(!Rule::Census.fails());
|
|
assert_eq!(Rule::from_id("census"), Some(Rule::Census));
|
|
}
|
|
|
|
#[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::<Vec<_>>()",
|
|
"(0..0).collect::<Vec<_>>()",
|
|
"(3..1).collect::<Vec<_>>()",
|
|
"(0..n).collect::<Vec<_>>()",
|
|
"(0..).take(3).collect::<Vec<_>>()",
|
|
"[1, 2].iter().filter(|x| keep(x)).collect::<Vec<_>>()",
|
|
"[1, 2].into_iter().zip(ys).collect::<Vec<_>>()",
|
|
"[None::<u8>].into_iter().collect::<Option<Vec<_>>>()",
|
|
"[Err::<u8, E>(error())].into_iter().collect::<Result<Vec<_>, E>>()",
|
|
"[1, 2].into_iter().collect()",
|
|
"[1, 2].into_iter().collect::<Items>()",
|
|
"[1, 2].into_iter().collect::<unknown::Vec<_>>()",
|
|
] {
|
|
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<u8> = [1, 2].iter().copied().rev().collect();",
|
|
"let xs: Vec<Px> = (0..40u8).map(|n| px(n)).collect();",
|
|
"let xs = (1..=3).collect::<Vec<_>>();",
|
|
"let xs = (-2..1).step_by(2).collect::<Vec<_>>();",
|
|
"let xs: Vec<_> = (0..N).collect();",
|
|
"let xs: Vec<_> = [1, 2].into_iter().collect::<Vec<_>>().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::<Vec<_>>();",
|
|
"let xs = [0.0; NONE];",
|
|
"let xs: [u8; NONE] = [1];",
|
|
"let xs = (0..M).collect::<Vec<_>>();",
|
|
"let xs = [None::<u8>].into_iter().collect::<Option<Vec<_>>>();",
|
|
"let xs = [Err::<u8, E>(error())].into_iter().collect::<Result<Vec<_>, E>>();",
|
|
"let xs: Option<Vec<u8>> = [1].into_iter().collect();",
|
|
"let xs: Result<Vec<u8>, 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::<u8>].into_iter().collect::<Option<Vec<_>>>().into_iter().collect();",
|
|
"let xs: Vec<_> = [1, 2].into_iter().collect::<Items>();",
|
|
] {
|
|
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::<T>();",
|
|
] {
|
|
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::<Vec<_>>();"),
|
|
] {
|
|
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<f32> }\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<f32> }}\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<f32>", "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::<Vec<_>>().into_iter().collect()",
|
|
"xs.iter().map(|l| l.0).collect::<Vec<_>>()",
|
|
"&xs.iter().copied().rev().collect::<Vec<u8>>()",
|
|
] {
|
|
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::<Vec<_>>();", "assert_eq!([\"a\"], ids);"),
|
|
("let ids = xs.iter().copied().collect::<Vec<_>>();", "assert_eq!(ids, [1]);"),
|
|
("let ids: Vec<_> = xs.iter().copied().collect::<Vec<_>>().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::<Vec<_>>()",
|
|
"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<Vec<u8>> = xs.iter().copied().collect();",
|
|
"let ids: Result<Vec<u8>, 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::<Vec<_>>();",
|
|
"let ids: Vec<_> = xs.iter().copied().collect().clone();",
|
|
] {
|
|
let src = format!(
|
|
"#[test]\nfn t() {{\n {binding}\n assert_eq!(ids.into_iter().collect::<Vec<_>>(), [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"
|
|
);
|
|
assert_eq!(hits(&src), [(5, "all-unguarded")], "{binding}");
|
|
}
|
|
for target in ["Option<Vec<_>>", "Result<Vec<_>, E>", "Items"] {
|
|
let operand = format!("xs.iter().copied().collect::<{target}>().iter().collect::<Vec<_>>()");
|
|
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::<u32>()");
|
|
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::<A, B>(), \"{{:?}}\", out.stderr);\n}}\n"
|
|
);
|
|
assert_eq!(hits(&bad), [(2, "exit-status-only")], "{assertion}");
|
|
let good = bad.replace("f::<A, B>()", "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::<A, B>()", "f::<A, Vec<B, C>>()", "f :: <A, B>()"] {
|
|
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, ..Ctx::default() };
|
|
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::default()), [(8, "no-assertion")]);
|
|
}
|
|
|
|
#[test]
|
|
fn generic_asserting_calls_count_for_functions_and_methods() {
|
|
for call in ["check_round_trip::<u8>()", "check_round_trip::<A, Vec<B>>(x)", "value.check::<T>()", "value.check :: <Vec<Vec<T>>> ()"] {
|
|
let src = format!("#[test]\nfn t() {{\n {call};\n}}\n");
|
|
assert_eq!(hits(&src), [], "{call}");
|
|
}
|
|
for expression in ["check_round_trip::<u8>", "value.check::<T>", "round_trip::<u8>()", "value.round_trip::<T>()"] {
|
|
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<T>(a: T, b: T) { assert_eq!(a, b); }\nfn twice<T>(a: T) { same::<T>(a, a); }\nfn idle<T>() {}\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, ..Ctx::default() };
|
|
for call in ["same::<u8>(a, b)", "twice::<Vec<Vec<u8>>>(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::<u8>()", "same::<u8>", "value.same::<u8>()"] {
|
|
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<String> = 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<usize> = [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", "reads-source", "never-run"]);
|
|
let ios = "#[cfg(target_os = \"ios\")]\n#[test]\nfn ios() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert!(finish(&lint_file("crates/x/src/tests.rs", ios, &ctx()), 0, 1, "base").is_err(), "never-run fails the check");
|
|
let weak = "#[test]\nfn weak() {\n assert!(f().is_ok());\n}\n";
|
|
let unguarded = "#[test]\nfn all() {\n assert!(f().iter().all(|x| valid(x)));\n}\n";
|
|
let skipped = "#[test]\n#[ignore]\nfn skipped() {\n assert_eq!(f(), 1);\n}\n";
|
|
let 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<String> = 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<String> = 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<_>>(), Vec::<String>::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::<Vec<_>>(), ["MY_SAMPLES"], "{assignment}");
|
|
let commented = format!("# {assignment}");
|
|
assert_eq!(upper_words(&commented).collect::<Vec<_>>(), Vec::<String>::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<_>>(), Vec::<String>::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 { ci_env: upper_words(workflow).collect(), ..Ctx::default() };
|
|
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 { ci_env: upper_words(workflow).collect(), ..Ctx::default() };
|
|
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<_>>(), Vec::<String>::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::<Vec<_>>(), ["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::<Vec<_>>(), [(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, ..Ctx::default() }), [(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, ..Ctx::default() }), []);
|
|
}
|
|
|
|
#[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::<Vec<_>>(), [(Rule::EnvGateUnset, 3, 3, 4)]);
|
|
assert!(touches(&found[0], Some(&[4].into_iter().collect())), "a change to the name alone");
|
|
}
|
|
|
|
#[test]
|
|
fn sleep_in_a_condition_poll_or_a_spawned_release_is_not_reported() {
|
|
let polls = [
|
|
"fn wait(r: &R, back_off: bool) {\n while !r.load(SeqCst) {\n if back_off {\n thread::sleep(D);\n }\n }\n}\n",
|
|
"fn wait(r: &R) {\n loop {\n match r.state() {\n S::Done => break,\n _ => {\n thread::sleep(D);\n }\n }\n }\n}\n",
|
|
"fn wait(s: &S) -> P {\n loop {\n let p = s.progress();\n if p.done || Instant::now() > until {\n return p;\n }\n thread::sleep(D);\n }\n}\n",
|
|
"fn wait(g: &G) {\n while !g.0.load(SeqCst) {\n std::thread::sleep(Duration::from_millis(1));\n }\n}\n",
|
|
"fn wait(t: &mut T) {\n while t.waiting() {\n thread::sleep(D);\n t.poll();\n }\n}\n",
|
|
"fn wait(s: &S) {\n while s.execute(\"a\", &json!({})).unwrap()[\"n\"] != 1 && Instant::now() < until {\n thread::sleep(D);\n }\n}\n",
|
|
"#[test]\nfn t() {\n std::thread::spawn(move || {\n std::thread::sleep(Duration::from_secs(10));\n gate.open();\n });\n assert_eq!(f(), 1);\n}\n",
|
|
"fn wait(r: &R) {\n while { r.load(SeqCst) } {\n thread::sleep(D);\n }\n}\n",
|
|
"fn wait(r: &R) {\n m! { r }\n while !r.load(SeqCst) {\n thread::sleep(D);\n }\n}\n",
|
|
"fn wait(r: &R) {\n 'outer: while !r.load(SeqCst) {\n thread::sleep(D);\n }\n}\n",
|
|
"#[test]\nfn t() {\n std::thread::spawn(move || -> () {\n std::thread::sleep(D);\n gate.open();\n });\n assert_eq!(f(), 1);\n}\n",
|
|
"fn wait() -> P {\n let p = loop {\n let p = progress();\n if p.done {\n break p;\n }\n std::thread::sleep(D);\n };\n p\n}\n",
|
|
"#[test]\nfn t() {\n ::std::thread::spawn(move || {\n std::thread::sleep(D);\n release();\n });\n assert_eq!(f(), 1);\n}\n",
|
|
"fn wait() {\n while ScheduleDuration::new().pending {\n thread::sleep(D);\n }\n}\n",
|
|
"#[test]\nfn t() {\n std::thread::spawn(|| std::thread::sleep(D));\n assert_eq!(f(), 1);\n}\n",
|
|
"use std::thread::{self, spawn};\n#[test]\nfn t() {\n spawn(|| {\n thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n",
|
|
"fn wait() {\n while !ready({ let key = 1; key }) {\n thread::sleep(D);\n }\n}\n",
|
|
"fn wait(pending: bool) {\n while pending || { ready() } {\n thread::sleep(D);\n }\n}\n",
|
|
"#[test]\nfn t() {\n std::thread::spawn(|| {\n let () = {\n std::thread::sleep(D);\n };\n });\n assert_eq!(f(), 1);\n}\n",
|
|
"use std::thread;\n#[test]\nfn t() {\n thread::spawn(|| {\n thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n",
|
|
"use std::{thread, time::Duration};\n#[test]\nfn t() {\n thread::spawn(|| {\n thread::sleep(Duration::ZERO);\n });\n assert_eq!(f(), 1);\n}\n",
|
|
"fn wait(q: &Q) {\n while q.len() < 3 {\n thread::sleep(D);\n }\n}\n",
|
|
"fn wait(q: &Q) {\n while 0 < { q.len() } {\n thread::sleep(D);\n }\n}\n",
|
|
"fn wait(q: &Q) {\n while 3 > { q.len() } {\n thread::sleep(D);\n }\n}\n",
|
|
];
|
|
for src in polls {
|
|
assert_eq!(hits(src), [], "{src}");
|
|
}
|
|
let timed = [
|
|
"fn wait() {\n for _ in 0..3 {\n if ready() {\n thread::sleep(D);\n }\n }\n}\n",
|
|
"fn start() -> JoinHandle<()> {\n return std::thread::spawn(move || {\n std::thread::sleep(D);\n });\n}\n",
|
|
"fn start() -> JoinHandle<()> {\n return ::std::thread::spawn(move || {\n std::thread::sleep(D);\n });\n}\n",
|
|
"fn wait() {\n let t0 = Instant::now();\n while t0.elapsed() < D {\n fn unused() {}\n thread::sleep(D);\n }\n}\n",
|
|
"fn wait() {\n let t0 = Instant::now();\n while t0.elapsed() < Duration::from_millis(50) {\n thread::sleep(Duration::from_millis(5));\n }\n}\n",
|
|
"fn wait() {\n let t0 = Instant::now();\n while t0.elapsed().as_millis() < 50 {\n thread::sleep(D);\n }\n}\n",
|
|
"fn wait() {\n let t0 = Instant::now();\n while t0.elapsed() < Duration::new(1, 0) {\n thread::sleep(D);\n }\n}\n",
|
|
"fn wait() {\n let mut n = 0;\n loop {\n thread::sleep(D);\n n += 1;\n if n == 3 {\n break;\n }\n }\n}\n",
|
|
"fn wait(g: &G) {\n if g.ready() {\n thread::sleep(D);\n }\n}\n",
|
|
"fn wait() {\n let t0 = Instant::now();\n loop {\n thread::sleep(D);\n println!(\"{:?}\", t0.elapsed());\n if t0.elapsed() > D {\n break;\n }\n }\n}\n",
|
|
"#[test]\nfn t() {\n let h = run(move || {\n thread::sleep(D);\n });\n assert_eq!(h, 1);\n}\n",
|
|
"#[test]\nfn t() {\n std::thread::spawn(move || {\n std::thread::sleep(D);\n })\n .join()\n .unwrap();\n assert_eq!(f(), 1);\n}\n",
|
|
"#[test]\nfn t() {\n handles.push(std::thread::spawn(move || {\n std::thread::sleep(D);\n }));\n assert_eq!(f(), 1);\n}\n",
|
|
"#[test]\nfn t() {\n let release = std::thread::spawn(move || {\n std::thread::sleep(D);\n gate.open();\n });\n assert_eq!(f(), 1);\n release.join().unwrap();\n}\n",
|
|
"fn spawn(f: impl FnOnce()) {\n f();\n}\n#[test]\nfn t() {\n spawn(|| {\n thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n",
|
|
"fn wait(t0: Instant) {\n while t0.elapsed() < Duration::new(1, 0) {\n let new = t0.elapsed();\n thread::sleep(D);\n }\n}\n",
|
|
"fn wait() {\n let mut n = 0;\n while n < 3 {\n thread::sleep(delay());\n n += 1;\n }\n}\n",
|
|
"fn wait(t0: Instant) {\n while t0.elapsed().checked_sub(Duration::ZERO).unwrap() < D {\n thread::sleep(D);\n }\n}\n",
|
|
"fn wait(t0: Instant) {\n while t0.elapsed() < D {\n let _ = stringify!(probe());\n std::thread::sleep(D);\n }\n}\n",
|
|
"#[test]\nfn t() {\n while !ready() {\n std::thread::spawn(|| std::thread::sleep(D)).join().unwrap();\n }\n assert_eq!(f(), 1);\n}\n",
|
|
"fn wait() -> u8 {\n let mut n = 0;\n let r = loop {\n n += 1;\n if n == 3 {\n break n;\n }\n thread::sleep(D);\n };\n r\n}\n",
|
|
"fn wait() {\n let attempts = [0, 1, 2];\n let mut n = 0;\n while n < attempts.len() {\n thread::sleep(D);\n n += 1;\n }\n}\n",
|
|
"use std::thread::spawn as spawn_thread;\nfn spawn(f: impl FnOnce()) {\n f();\n}\n#[test]\nfn t() {\n spawn(|| {\n std::thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n",
|
|
"mod thread {\n pub fn spawn(f: impl FnOnce()) {\n f();\n }\n}\n#[test]\nfn t() {\n thread::spawn(|| {\n std::thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n",
|
|
"#[test]\nfn t() {\n let h = std::thread::spawn(|| {\n let () = {\n std::thread::sleep(D);\n };\n });\n h.join().unwrap();\n}\n",
|
|
"fn wait(r: &R) {\n while !r.load(SeqCst) {\n let x = {\n thread::sleep(D);\n 1\n };\n }\n}\n",
|
|
"fn wait() {\n let attempts = [0, 1, 2];\n let mut n = 0;\n while n < attempts.len() {\n thread::sleep(D);\n n = n + 1;\n }\n}\n",
|
|
"#[test]\nfn t() {\n std::thread::spawn(prepare(|| {\n std::thread::sleep(D);\n }));\n assert_eq!(f(), 1);\n}\n",
|
|
"fn wait(t0: Instant) {\n while t0.elapsed() < D {\n println!(\"{}\", 1u8.to_string());\n thread::sleep(D);\n }\n}\n",
|
|
"use crate::thread::spawn;\n#[test]\nfn t() {\n spawn(|| {\n std::thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n",
|
|
"use std::thread::{self as worker};\nmod thread {\n pub fn spawn(f: impl FnOnce()) {\n f();\n }\n}\n#[test]\nfn t() {\n thread::spawn(|| {\n std::thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n",
|
|
];
|
|
for src in timed {
|
|
assert_eq!(hits(src).iter().filter(|h| h.1 == "sleep").count(), 1, "{src}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn an_edit_to_the_loop_around_a_sleep_counts_as_a_change() {
|
|
let src = "fn wait() {\n let mut n = 0;\n while n < 3 {\n thread::sleep(D);\n n += 1;\n }\n}\n";
|
|
let found = lint_file("crates/x/src/tests.rs", src, &ctx());
|
|
assert_eq!(found.iter().map(|h| (h.rule, h.line)).collect::<Vec<_>>(), [(Rule::Sleep, 4)]);
|
|
assert!(touches(&found[0], Some(&[3].into_iter().collect())), "a change to the loop's condition");
|
|
assert!(!touches(&found[0], Some(&[2].into_iter().collect())), "a change outside the loop");
|
|
}
|
|
|
|
#[test]
|
|
fn an_edit_that_joins_a_spawned_sleep_counts_as_a_change() {
|
|
let block = "#[test]\nfn t() {\n std::thread::spawn(move || {\n std::thread::sleep(D);\n })\n .join()\n .unwrap();\n assert_eq!(f(), 1);\n}\n";
|
|
let bare =
|
|
"#[test]\nfn t() {\n std::thread::spawn(|| std::thread::sleep(D))\n .join()\n .unwrap();\n assert_eq!(f(), 1);\n}\n";
|
|
for (src, line, join) in [(block, 4, 7), (bare, 3, 5)] {
|
|
let found = lint_file("crates/x/src/tests.rs", src, &ctx());
|
|
assert_eq!(found.iter().map(|h| (h.rule, h.line)).collect::<Vec<_>>(), [(Rule::Sleep, line)], "{src}");
|
|
assert!(touches(&found[0], Some(&[join].into_iter().collect())), "a change to the join: {src}");
|
|
assert!(!touches(&found[0], Some(&[join + 1].into_iter().collect())), "a change after the statement: {src}");
|
|
}
|
|
}
|
|
|
|
#[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}");
|
|
}
|
|
for import in ["use std::thread::sleep as nap;", "use std::thread::sleep_ms;", "use std::thread::{sleep as nap};"] {
|
|
let src = format!("{import}\nfn sleep(_: u8) {{}}\n#[test]\nfn t() {{\n sleep(1);\n assert_eq!(f(), 42);\n}}\n");
|
|
assert_eq!(hits(&src), [], "{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 { ci_env: upper_words("env:\n X: 1\n").collect(), ..Ctx::default() };
|
|
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::<Vec<_>>(), [(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<u8> = 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<u8> = 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<usize> = (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::<Vec<_>>(), [(Rule::IgnoreWithoutReason, 2, 2, 3)]);
|
|
assert!(touches(&found[0], Some(&[3].into_iter().collect())), "a change to the reason alone");
|
|
}
|
|
|
|
fn only(rule: &'static str, src: &str) -> Vec<(usize, &'static str)> {
|
|
hits(src).into_iter().filter(|h| h.1 == rule).collect()
|
|
}
|
|
|
|
#[test]
|
|
fn mirrors_call_the_same_function_on_both_sides() {
|
|
let bad = "#[test]\nfn t() {\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n";
|
|
assert_eq!(only("mirror", bad), [(3, "mirror")]);
|
|
let written = "#[test]\nfn t() {\n assert_eq!(scale(p, 2.0), Point::new(2.0, 4.0));\n}\n";
|
|
assert_eq!(only("mirror", written), []);
|
|
let builders = "#[test]\nfn t() {\n assert_eq!(Some(area(a)), Some(4.0));\n assert_eq!(a.to_string(), b.to_string());\n}\n";
|
|
assert_eq!(only("mirror", builders), [], "a builder or conversion on both sides");
|
|
let same = "#[test]\nfn t() {\n assert_eq!(scale(p), scale(p));\n}\n";
|
|
assert_eq!(only("mirror", same), [], "identical sides are self-compare's");
|
|
let oracle = "#[test]\nfn t() {\n assert_eq!(actual::area(s), reference::area(s) * 2.0);\n}\n";
|
|
assert_eq!(only("mirror", oracle), [], "two functions of the same name in different paths");
|
|
let ne = "#[test]\nfn t() {\n assert_ne!(hash(a), hash(b));\n}\n";
|
|
assert_eq!(only("mirror", ne), [], "two inputs that must differ");
|
|
let allowed = "#[test]\nfn t() {\n // test-lint: allow mirror scaling is linear by definition\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n";
|
|
assert_eq!(only("mirror", allowed), [], "the allow removes the hit `bad` reports");
|
|
let derived_arg = "#[test]\nfn t() {\n assert_eq!(area(grow(s, 2.0)), area(s) * 4.0);\n}\n";
|
|
assert_eq!(only("mirror", derived_arg), [(3, "mirror")], "a computed input is a quantity, not an entry");
|
|
let swapped = "#[test]\nfn t() {\n assert_eq!(scale(p, 1.0) * 2.0, scale(p, 2.0));\n}\n";
|
|
assert_eq!(only("mirror", swapped), [(3, "mirror")], "the arithmetic on the left side");
|
|
}
|
|
|
|
#[test]
|
|
fn mirrors_leave_out_reads_at_two_entries_and_shared_arithmetic() {
|
|
let order = "#[test]\nfn t() {\n assert_eq!(at(\"Graphic styles\"), at(\"Swatches\") + 1);\n assert_eq!(at(front[0]), at(a) + 1);\n}\n";
|
|
assert_eq!(only("mirror", order), [], "positions of two entries in one list");
|
|
let commented = "#[test]\nfn t() {\n assert_eq!(at(\"B\" /* later entry */), at(\"A\") + 1);\n}\n";
|
|
assert_eq!(only("mirror", commented), [], "a comment beside a key");
|
|
let raw = "#[test]\nfn t() {\n assert_eq!(at(r#\"B\"#), at(r#\"A\"#) + 1);\n assert_eq!(at(r\"B\"), at(r\"A\") + 1);\n}\n";
|
|
assert_eq!(only("mirror", raw), [], "raw string keys");
|
|
let spaced = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at(\"AB\") + 1);\n}\n";
|
|
assert_eq!(only("mirror", spaced), [], "a space inside a key makes a different entry");
|
|
let raw_quote = "#[test]\nfn t() {\n assert_eq!(at(r#\"A\" B\"#), at(r#\"A\"B\"#) + 1);\n}\n";
|
|
assert_eq!(only("mirror", raw_quote), [], "a quote inside a raw key does not end it");
|
|
let computed = "#[test]\nfn t() {\n assert_eq!(label(\"A\".to_owned() + \"B\"), label(\"C\") + 1);\n}\n";
|
|
assert_eq!(only("mirror", computed), [(3, "mirror")], "a computed string is not an entry key");
|
|
let same_key = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at( \"A B\" ) + 1);\n}\n";
|
|
assert_eq!(only("mirror", same_key), [(3, "mirror")], "spaces between tokens do not");
|
|
let offset =
|
|
"#[test]\nfn t() {\n assert_eq!(bounds(&s, copies[0]), bounds(&s, id) + dv);\n assert_eq!(board(&s, 3), board(&s, 2) + step);\n}\n";
|
|
assert_eq!(only("mirror", offset), [], "two objects of one document, one moved from the other");
|
|
let period = "#[test]\nfn t() {\n assert_eq!(rotate_deg(-270.0) * v, rotate_deg(90.0) * v);\n}\n";
|
|
assert_eq!(only("mirror", period), [], "the same arithmetic on both sides");
|
|
let tails = "#[test]\nfn t() {\n assert_eq!(rotate_deg(-270.0) * v, rotate_deg(90.0) * w);\n}\n";
|
|
assert_eq!(only("mirror", tails), [(3, "mirror")], "different arithmetic on each side still derives one from the other");
|
|
}
|
|
|
|
#[test]
|
|
fn echoes_check_only_constants_or_the_fixture() {
|
|
let constant = "#[test]\nfn t() {\n assert_eq!(MAX_ZOOM, 64.0);\n assert!(Kind::A != Kind::B);\n}\n";
|
|
assert_eq!(only("constant-echo", constant), [(2, "constant-echo")]);
|
|
let fixture =
|
|
"#[test]\nfn t() {\n let input = vec![1, 2, 3];\n let n = 3;\n let _ = process(&input);\n assert_eq!(input.len(), n);\n}\n";
|
|
assert_eq!(only("fixture-only", fixture), [(2, "fixture-only")]);
|
|
let result = "#[test]\nfn t() {\n let input = vec![1, 2, 3];\n let out = process(&input);\n assert_eq!(out.len(), 3);\n}\n";
|
|
assert_eq!(only("fixture-only", result), [], "the result of the code under test");
|
|
let arm = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(n) => assert_eq!(n, 1),\n None => assert_eq!(n, 0),\n }\n}\n";
|
|
assert_eq!(only("fixture-only", arm), [], "a match arm binds its own n");
|
|
let outer = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(m) if m == n => assert_eq!(n, 0),\n _ => assert_eq!(n, 0),\n }\n}\n";
|
|
assert_eq!(only("fixture-only", outer), [(2, "fixture-only")], "a guard reads the outer n");
|
|
let changed = "#[test]\nfn t() {\n let mut input = vec![1, 2, 3];\n process(&mut input);\n assert_eq!(input.len(), 3);\n}\n";
|
|
assert_eq!(only("fixture-only", changed), [], "a mutable local the code changes");
|
|
let borrowed = "#[test]\nfn t() {\n let input = &mut [3, 1];\n sort(input);\n assert_eq!(*input, [1, 3]);\n}\n";
|
|
assert_eq!(only("fixture-only", borrowed), [], "an immutable binding of a mutable reference");
|
|
let pattern = "#[test]\nfn t() {\n let (a, b) = split(4);\n assert_eq!(a, 2);\n assert_eq!(b, 2);\n}\n";
|
|
assert_eq!(only("fixture-only", pattern), [], "a pattern binding of a result");
|
|
let mixed = "#[test]\nfn t() {\n assert_eq!(MAX_ZOOM, 64.0);\n assert_eq!(zoom_in(1.0), 2.0);\n}\n";
|
|
assert_eq!(only("constant-echo", mixed), [], "one real assertion keeps the test");
|
|
let shadowed = "#[test]\nfn t() {\n let x = 1;\n let x = double(x);\n assert_eq!(x, 2);\n}\n";
|
|
assert_eq!(only("fixture-only", shadowed), [], "the reaching binding is a call");
|
|
let helper = "#[test]\nfn t() {\n assert_eq!(MAX, 4);\n check_all();\n}\n";
|
|
assert_eq!(only("constant-echo", helper), [], "an asserting helper");
|
|
let printed = "#[test]\nfn t() {\n let got = sample(1.0);\n assert_eq!(format!(\"{got:?}\"), \"1\");\n}\n";
|
|
assert_eq!(hits(printed), [], "format! reads a local inside its string");
|
|
let scoped = "#[test]\nfn t() {\n let result = compute();\n {\n let result = 0;\n consume(result);\n }\n assert_eq!(result, 1);\n}\n";
|
|
assert_eq!(hits(scoped), [], "a binding in a block that has ended");
|
|
let later = "#[test]\nfn t() {\n let x = compute();\n let y = x;\n let x = 0;\n assert_eq!(y, 2);\n assert_eq!(x, 0);\n}\n";
|
|
assert_eq!(hits(later), [], "an initializer reads the binding that reaches it, not a later one");
|
|
let if_let = "#[test]\nfn t() {\n let x = 0;\n if let Some(x) = compute() {\n assert_eq!(x, 2);\n }\n}\n";
|
|
assert_eq!(only("fixture-only", if_let), [], "an `if let` binding shadows the outer one in its body");
|
|
let struct_pattern = "#[test]\nfn t() {\n let n = 0;\n if let Row { n } = compute() {\n assert_eq!(n, 2);\n }\n}\n";
|
|
assert_eq!(only("fixture-only", struct_pattern), [], "the braces of a struct pattern are not the body");
|
|
let else_branch = "#[test]\nfn t() {\n let n = 0;\n if let Row { n } = compute() {\n consume(n);\n } else {\n assert_eq!(n, 0);\n }\n}\n";
|
|
assert_eq!(only("fixture-only", else_branch), [(2, "fixture-only")], "the `else` branch sees the outer binding");
|
|
let mut_pattern =
|
|
"#[test]\nfn t() {\n let n = 0;\n if let Some(mut n) = compute() {\n n += 1;\n assert_eq!(n, 2);\n }\n}\n";
|
|
assert_eq!(only("fixture-only", mut_pattern), [], "`mut n` in an `if let` binds `n`");
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_accepts_trailing_commas_in_cfg_predicates() {
|
|
for pred in ["not(unix,)", "not( unix , )", "all(not(unix,),)", "any(not(unix,),)"] {
|
|
let src = format!("#[cfg({pred})]\n#[test]\nfn t() {{\n assert_eq!(f(), 1);\n}}\n");
|
|
assert_eq!(only("never-run", &src), [(3, "never-run")], "{pred}");
|
|
}
|
|
for pred in ["all(unix,)", "any(unix,)"] {
|
|
let src = format!("#[cfg({pred})]\n#[test]\nfn t() {{\n assert_eq!(f(), 1);\n}}\n");
|
|
assert_eq!(only("never-run", &src), [], "{pred}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_tests_are_compiled_out_on_every_ci_target() {
|
|
let mac = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", mac), [(3, "never-run")]);
|
|
let module = "#[cfg(all(test, windows))]\nmod tests {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n";
|
|
assert_eq!(hits_in("crates/x/src/lib.rs", module, &ctx()).into_iter().filter(|h| h.1 == "never-run").count(), 1);
|
|
let file = "#![cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", file), [(3, "never-run")]);
|
|
let unix = "#[cfg(unix)]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", unix), [], "Linux runs it");
|
|
let not_mac = "#[cfg(not(target_os = \"macos\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", not_mac), []);
|
|
let raw = "#[cfg(target_os = r\"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", raw), [], "a raw string value");
|
|
let feature = "#[cfg(feature = \"gpu\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", feature), [], "a feature CI may enable");
|
|
let any = "#[cfg(any(target_os = \"macos\", target_os = \"linux\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", any), []);
|
|
let win = "#[cfg(windows)]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in("apps/vectorcraft/src/printing/tests.rs", win, &ctx()), [], "the printing workflow runs it on Windows");
|
|
assert_eq!(hits_in("crates/x/src/tests.rs", win, &ctx()), [(3, "never-run")]);
|
|
let other = "#[cfg(target_os = \"macos\")]\nfn helper() {}\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", other), [], "a cfg on another item");
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_lists_tests_that_build_on_macos_or_windows_without_failing() {
|
|
let test = |gate: &str| format!("#[cfg({gate})]\n#[test]\nfn t() {{\n assert_eq!(f(), 1);\n}}\n");
|
|
let check = |path: &str, gate: &str| {
|
|
let found = lint_file(path, &test(gate), &ctx());
|
|
assert_eq!(found.iter().filter(|h| h.rule == Rule::NeverRun).count(), 1, "{gate} is listed");
|
|
finish(&found, 0, 1, "base")
|
|
};
|
|
// A touchpad gesture test that egui can only drive on macOS.
|
|
assert!(check("crates/ui-egui/src/tests/quickpenwheel.rs", "target_os = \"macos\"").is_ok(), "macOS");
|
|
// A test of performance counters that only Windows has.
|
|
assert!(check("apps/vectorcraft-cli/src/perf.rs", "windows").is_ok(), "Windows");
|
|
assert!(check("crates/x/src/tests.rs", "all(target_os = \"macos\", target_arch = \"aarch64\")").is_ok(), "Apple silicon");
|
|
assert!(check("crates/x/src/tests.rs", "target_os = \"ios\"").is_err(), "no desktop target builds it");
|
|
assert!(check("crates/x/src/tests.rs", "all(windows, unix)").is_err(), "no target builds it");
|
|
let found = lint_file("apps/vectorcraft-cli/src/perf.rs", &test("windows"), &ctx());
|
|
assert!(found[0].note.ends_with("it builds on Windows, so run it there"), "{}", found[0].note);
|
|
}
|
|
|
|
#[test]
|
|
fn module_gates_reads_each_candidate_once() {
|
|
let paths: Vec<String> = (0..32).map(|i| format!("crates/x/src/parent/child{i}.rs")).collect();
|
|
let parent = (0..32).map(|i| format!("mod child{i};\n")).collect::<String>();
|
|
let files = [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod parent;\n"), ("crates/x/src/parent.rs", parent.as_str())];
|
|
let reads = RefCell::new(HashMap::<String, usize>::new());
|
|
let read = |p: &str| {
|
|
*reads.borrow_mut().entry(p.to_owned()).or_default() += 1;
|
|
files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned())
|
|
};
|
|
let gates = module_gates(&paths, &read, &Overrides::new());
|
|
assert_eq!(gates.len(), paths.len(), "every child inherits the parent gate");
|
|
let reads = reads.borrow();
|
|
assert_eq!(reads.get("crates/x/src/lib.rs"), Some(&1), "a shared ancestor");
|
|
assert_eq!(reads.get("crates/x/src/parent.rs"), Some(&1), "a shared parent");
|
|
assert_eq!(reads.get("crates/x/src/parent/mod.rs"), Some(&1), "a missing candidate");
|
|
for (path, count) in reads.iter() {
|
|
assert_eq!(*count, 1, "candidate {path}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_follows_the_cfg_of_the_mod_declaration() {
|
|
let files: HashMap<&str, &str> = [
|
|
("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod mac;\nmod plain;\n"),
|
|
("crates/x/src/mac.rs", "mod inner;\n"),
|
|
("crates/x/src/mac/inner.rs", ""),
|
|
]
|
|
.into_iter()
|
|
.collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let paths: Vec<String> = ["crates/x/src/mac.rs", "crates/x/src/mac/inner.rs", "crates/x/src/plain.rs", "crates/x/tests/it.rs"]
|
|
.into_iter()
|
|
.map(String::from)
|
|
.collect();
|
|
let cfgs = module_cfgs(&paths, &read, &Overrides::new());
|
|
assert_eq!(cfgs.get("crates/x/src/mac.rs").map(Vec::as_slice), Some(&["target_os=\"macos\"".to_owned()][..]));
|
|
assert!(cfgs.contains_key("crates/x/src/mac/inner.rs"), "inherited through mac.rs");
|
|
assert!(!cfgs.contains_key("crates/x/src/plain.rs") && !cfgs.contains_key("crates/x/tests/it.rs"));
|
|
let ctx = Ctx { module_cfgs: cfgs, ..ctx() };
|
|
let test = "#[cfg(test)]\nmod tests {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n";
|
|
assert_eq!(hits_in("crates/x/src/mac/inner.rs", test, &ctx), [(4, "never-run")]);
|
|
assert_eq!(hits_in("crates/x/src/plain.rs", test, &ctx), []);
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_follows_the_cfg_around_the_mod_declaration() {
|
|
let child = Loaded { path: "src/child.rs", name: "child", chain: &[] };
|
|
let declared = |src: &str, want: &Loaded| declared_cfgs(src, "src/lib.rs", want, false, Via::Any).map(|(p, _)| p);
|
|
let inner = "#![cfg(target_os = \"macos\")]\nmod child;\n";
|
|
assert_eq!(declared(inner, &child), Some(vec!["target_os=\"macos\"".to_owned()]));
|
|
let block = "#[cfg(windows)]\nmod platform {\n mod child;\n}\n";
|
|
assert_eq!(declared(block, &child), None, "that `mod child;` loads platform/child.rs");
|
|
let platform = ["platform".to_owned()];
|
|
let nested = Loaded { path: "src/platform/child.rs", name: "child", chain: &platform };
|
|
assert_eq!(declared(block, &nested), Some(vec!["windows".to_owned()]), "the gate on the inline module");
|
|
let both = "#[cfg(windows)]\nmod platform {\n mod child;\n}\nmod child;\n";
|
|
assert_eq!(declared(both, &child), Some(vec![]), "the root declaration, not the one in platform");
|
|
let gated = "#[cfg(windows)]\nconst _: () = {\n mod child;\n};\n";
|
|
assert_eq!(declared(gated, &child), Some(vec!["windows".to_owned()]), "a gated block that is not a module");
|
|
assert_eq!(declared("mod child;\n", &child), Some(vec![]));
|
|
let commented = "#[cfg(target_os = /* supported */ \"linux\")]\nmod child;\n";
|
|
assert_eq!(declared(commented, &child), Some(vec!["target_os=\"linux\"".to_owned()]), "a comment in the predicate");
|
|
let paths = "#[cfg(windows)]\n#[path = \"windows.rs\"]\nmod imp;\n#[cfg(not(windows))]\nmod imp;\n";
|
|
let imp = Loaded { path: "src/imp.rs", name: "imp", chain: &[] };
|
|
assert_eq!(declared(paths, &imp), Some(vec!["not(windows)".to_owned()]), "the declaration that loads imp.rs");
|
|
let win = Loaded { path: "src/windows.rs", name: "windows", chain: &[] };
|
|
assert_eq!(declared(paths, &win), Some(vec!["windows".to_owned()]), "the `#[path]` override");
|
|
let twice = "#[cfg(target_os = \"macos\")]\nmod child;\n#[cfg(target_os = \"linux\")]\n#[path = \"child.rs\"]\nmod other;\n";
|
|
assert_eq!(declared(twice, &child), Some(vec!["any(all(target_os=\"macos\"),all(target_os=\"linux\"))".to_owned()]));
|
|
let attr = "#[cfg_attr(unix, cfg(target_os = \"macos\"))]\nmod child;\n";
|
|
assert_eq!(declared(attr, &child), Some(vec!["any(not(unix),target_os=\"macos\")".to_owned()]));
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_reads_cfg_attr_and_commented_predicates() {
|
|
let commented = "#[cfg(target_os = /* supported */ \"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", commented), [], "Linux runs it");
|
|
let mac = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", mac), [(3, "never-run")]);
|
|
let nested = "#[cfg_attr(unix, cfg(target_os = \"macos\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", nested), [(3, "never-run")], "unix holds on every CI target, so the nested cfg applies");
|
|
let unknown = "#[cfg_attr(feature = \"gpu\", cfg(target_os = \"macos\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", unknown), [], "a condition that may not hold");
|
|
}
|
|
|
|
#[test]
|
|
fn a_changed_parent_declaration_counts_for_the_child_tests() {
|
|
let files: HashMap<&str, &str> =
|
|
[("crates/x/src/lib.rs", "mod plain;\n#[cfg(target_os = \"macos\")]\nmod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new());
|
|
let lib = |lines: &[usize]| -> BTreeMap<String, Option<BTreeSet<usize>>> {
|
|
[("crates/x/src/lib.rs".to_owned(), Some(lines.iter().copied().collect()))].into_iter().collect()
|
|
};
|
|
assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[2])), "the cfg line");
|
|
assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "the declaration line");
|
|
assert!(!gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[1])), "another declaration");
|
|
let multiline: HashMap<&str, &str> = [
|
|
("crates/x/src/lib.rs", "#[cfg(all(\n unix,\n target_os = \"macos\",\n))]\nmod child;\nmod plain;\n"),
|
|
("crates/x/src/child.rs", ""),
|
|
]
|
|
.into_iter()
|
|
.collect();
|
|
let read = |p: &str| multiline.get(p).map(|s| (*s).to_owned());
|
|
let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new());
|
|
assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "a line inside a multiline predicate");
|
|
assert!(!gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[6])), "another declaration");
|
|
let enclosing: HashMap<&str, &str> = [
|
|
("crates/x/src/lib.rs", "#[cfg(all(\n unix,\n target_os = \"macos\",\n))]\nmod platform {\n mod child;\n}\nmod plain;\n"),
|
|
("crates/x/src/platform/child.rs", ""),
|
|
]
|
|
.into_iter()
|
|
.collect();
|
|
let read = |p: &str| enclosing.get(p).map(|s| (*s).to_owned());
|
|
let gates = module_gates(&["crates/x/src/platform/child.rs".to_owned()], &read, &Overrides::new());
|
|
assert!(gate_changed(gates.get("crates/x/src/platform/child.rs"), &lib(&[3])), "a line inside the inline module's predicate");
|
|
assert!(!gate_changed(gates.get("crates/x/src/platform/child.rs"), &lib(&[8])), "a declaration outside the inline module");
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_follows_a_path_override_in_a_sibling_file() {
|
|
let files: HashMap<&str, &str> = [
|
|
("crates/x/src/lib.rs", "mod solids;\n"),
|
|
("crates/x/src/solids/mod.rs", "mod graphics;\n"),
|
|
("crates/x/src/solids/graphics.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"tests_graphics.rs\"]\nmod tests;\n"),
|
|
("crates/x/src/solids/tests_graphics.rs", ""),
|
|
]
|
|
.into_iter()
|
|
.collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s)));
|
|
let child = "crates/x/src/solids/tests_graphics.rs".to_owned();
|
|
let gates = module_gates(std::slice::from_ref(&child), &read, &overrides);
|
|
assert_eq!(gates.get(&child).map(|g| g.preds.clone()), Some(vec!["target_os=\"macos\"".to_owned()]));
|
|
let changed: BTreeMap<String, Option<BTreeSet<usize>>> =
|
|
[("crates/x/src/solids/graphics.rs".to_owned(), Some([1].into_iter().collect()))].into_iter().collect();
|
|
assert!(gate_changed(gates.get(&child), &changed), "a cfg added to the sibling's declaration");
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_keeps_crate_roots_independent_of_path_overrides() {
|
|
for child in [
|
|
"crates/x/tests/shared.rs",
|
|
"crates/x/src/lib.rs",
|
|
"crates/x/src/main.rs",
|
|
"crates/x/src/bin/tool.rs",
|
|
"crates/x/examples/demo.rs",
|
|
"crates/x/benches/speed.rs",
|
|
"crates/x/build.rs",
|
|
] {
|
|
let declaration = format!("#[cfg(target_os = \"macos\")]\n#[path = \"{}\"]\nmod shared;\n", child.strip_prefix("crates/x/").unwrap());
|
|
let files = [("crates/x/other.rs", declaration.as_str())];
|
|
let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned());
|
|
let overrides = path_overrides(files);
|
|
let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in(child, test, &ctx), [], "the crate root runs independently: {child}");
|
|
let gated = format!("#[cfg(target_os = \"macos\")]\n{test}");
|
|
assert_eq!(hits_in(child, &gated, &ctx), [(3, "never-run")], "the root's own cfg still applies: {child}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_namesake_already_off_does_not_hide_a_newly_off_test() {
|
|
let src = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n";
|
|
let path = "crates/x/src/child.rs";
|
|
let base = lint_file(path, src, &ctx());
|
|
let now =
|
|
lint_file(path, src, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() });
|
|
let off: Vec<usize> = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, src, src, h)).map(|h| h.line).collect();
|
|
assert_eq!(off.len(), 1, "only the test in `b` is newly off: {off:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_test_off_at_the_base_is_matched_in_the_base_source() {
|
|
// At the base an inline module gate turned the test off; the change removes that gate and
|
|
// gates the parent instead, which also moves the test up a line.
|
|
let path = "crates/x/src/child.rs";
|
|
let before = "mod a {\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\n#[cfg(target_os = \"macos\")]\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n";
|
|
let after = "mod a {\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n";
|
|
let base = lint_file(path, before, &ctx());
|
|
let now =
|
|
lint_file(path, after, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() });
|
|
let off: Vec<&str> =
|
|
now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, before, after, h)).map(|h| h.test.as_str()).collect();
|
|
assert_eq!(off, ["u"], "`t` was already off at the base; only `u` is newly off");
|
|
}
|
|
|
|
#[test]
|
|
fn a_removed_namesake_module_does_not_hide_a_newly_off_test() {
|
|
// `a::t` was off at the base and `b::t` ran; the change deletes `mod a` and gates the parent,
|
|
// so `b::t` is now the only `t` in the file.
|
|
let path = "crates/x/src/child.rs";
|
|
let before = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n";
|
|
let after = "mod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n";
|
|
let base = lint_file(path, before, &ctx());
|
|
let now =
|
|
lint_file(path, after, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() });
|
|
let off: Vec<usize> = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, before, after, h)).map(|h| h.line).collect();
|
|
assert_eq!(off, [3], "`b::t` is newly off");
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_follows_a_tests_module_directory_under_src() {
|
|
let files: HashMap<&str, &str> =
|
|
[("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod tests;\n"), ("crates/x/src/tests.rs", "mod fonts;\n")].into_iter().collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let child = "crates/x/src/tests/fonts.rs".to_owned();
|
|
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &Overrides::new()), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")], "src/tests holds modules, not test targets");
|
|
assert_eq!(module_parent("crates/x/tests/fonts.rs"), None, "a test target beside src");
|
|
let files: HashMap<&str, &str> = [
|
|
("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"../tests/common/mod.rs\"]\nmod common;\n"),
|
|
("crates/x/tests/smoke.rs", "mod common;\n"),
|
|
("crates/x/tests/common/mod.rs", ""),
|
|
]
|
|
.into_iter()
|
|
.collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let paths: Vec<String> = files.keys().map(|p| (*p).to_owned()).collect();
|
|
let overrides = with_root_routes(path_overrides(files.iter().map(|(p, s)| (*p, *s))), &paths);
|
|
let shared = "crates/x/tests/common/mod.rs".to_owned();
|
|
let shared_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..self::ctx() };
|
|
assert_eq!(hits_in(&shared, test, &shared_ctx), [], "a test target beside it loads the shared module on every target");
|
|
// Only a macOS-gated declaration in the target beside it loads the helper.
|
|
let gated: HashMap<&str, &str> = [
|
|
("crates/x/tests/smoke.rs", "#[cfg(target_os = \"macos\")]\nmod common;\n"),
|
|
("crates/x/tests/other.rs", "fn main() {}\n"),
|
|
("crates/x/tests/common/mod.rs", ""),
|
|
]
|
|
.into_iter()
|
|
.collect();
|
|
let read = |p: &str| gated.get(p).map(|s| (*s).to_owned());
|
|
let paths: Vec<String> = gated.keys().map(|p| (*p).to_owned()).collect();
|
|
let overrides = with_root_routes(Overrides::new(), &paths);
|
|
let gated_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..self::ctx() };
|
|
assert_eq!(hits_in(&shared, test, &gated_ctx), [(2, "never-run")], "the only target that loads it is macOS-only");
|
|
let child = "crates/x/tests/common/helpers.rs".to_owned();
|
|
let with_child: HashMap<&str, &str> =
|
|
gated.iter().map(|(p, s)| (*p, *s)).chain([("crates/x/tests/common/mod.rs", "mod helpers;\n")]).collect();
|
|
let read = |p: &str| with_child.get(p).map(|s| (*s).to_owned());
|
|
let child_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &overrides), ..self::ctx() };
|
|
assert_eq!(hits_in(&child, test, &child_ctx), [(2, "never-run")], "a module below the helper inherits the gate");
|
|
let ungated: HashMap<&str, &str> = gated.iter().map(|(p, s)| (*p, *s)).chain([("crates/x/tests/other.rs", "mod common;\n")]).collect();
|
|
let read = |p: &str| ungated.get(p).map(|s| (*s).to_owned());
|
|
let ungated_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..self::ctx() };
|
|
assert_eq!(hits_in(&shared, test, &ungated_ctx), [], "another target loads it on every target");
|
|
}
|
|
|
|
#[test]
|
|
fn a_cfg_attr_path_on_an_inline_module_is_a_conditional_route() {
|
|
let lib = "#[cfg(target_os = \"macos\")]\n#[cfg_attr(target_os = \"macos\", path = \"generated\")]\nmod platform {\n mod child;\n}\n";
|
|
let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", lib)].into_iter().collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
let generated = "crates/x/src/generated/child.rs".to_owned();
|
|
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&generated), &read, &Overrides::new()), ..self::ctx() };
|
|
assert_eq!(hits_in(&generated, test, &ctx), [(2, "never-run")], "loaded only where the macOS override applies");
|
|
let unix = lib.replace("#[cfg(target_os = \"macos\")]\n#[cfg_attr(target_os = \"macos\"", "#[cfg_attr(unix");
|
|
let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", unix.as_str())].into_iter().collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&generated), &read, &Overrides::new()), ..self::ctx() };
|
|
assert_eq!(hits_in(&generated, test, &ctx), [], "the override applies on Linux and FreeBSD");
|
|
let default = "crates/x/src/platform/child.rs".to_owned();
|
|
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&default), &read, &Overrides::new()), ..self::ctx() };
|
|
assert_eq!(hits_in(&default, test, &ctx), [(2, "never-run")], "the default directory is used only on Windows");
|
|
}
|
|
|
|
#[test]
|
|
fn a_path_loaded_file_declares_its_modules_beside_it() {
|
|
let files: HashMap<&str, &str> = [
|
|
("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"impl/platform.rs\"]\nmod platform;\n"),
|
|
("crates/x/src/impl/platform.rs", "mod child;\n"),
|
|
("crates/x/src/impl/child.rs", ""),
|
|
]
|
|
.into_iter()
|
|
.collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s)));
|
|
let child = "crates/x/src/impl/child.rs".to_owned();
|
|
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &overrides), ..self::ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")], "impl/platform.rs loads impl/child.rs");
|
|
let below = "crates/x/src/impl/platform/child.rs".to_owned();
|
|
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&below), &read, &overrides), ..self::ctx() };
|
|
assert_eq!(hits_in(&below, test, &ctx), [], "the path-loaded file does not load impl/platform/child.rs");
|
|
let seeds = ["crates/x/src/impl/platform.rs".to_owned()];
|
|
let all: Vec<String> = files.keys().map(|p| (*p).to_owned()).collect();
|
|
assert!(
|
|
descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &|_| None).contains(&child),
|
|
"a change to platform.rs reaches child.rs"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_named_route_takes_only_the_gates_of_named_declarations() {
|
|
// `parent.rs` is loaded by name on macOS and through `#[path]` on Linux. Only the named route
|
|
// loads `parent/child.rs`; the `#[path]` route loads `child.rs` beside `parent.rs`.
|
|
let files: HashMap<&str, &str> = [
|
|
("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod parent;\n#[cfg(target_os = \"linux\")]\n#[path = \"parent.rs\"]\nmod p2;\n"),
|
|
("crates/x/src/parent.rs", "mod child;\n"),
|
|
("crates/x/src/parent/child.rs", ""),
|
|
("crates/x/src/child.rs", ""),
|
|
]
|
|
.into_iter()
|
|
.collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s)));
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
for (child, expected) in [("crates/x/src/parent/child.rs", vec![(2, "never-run")]), ("crates/x/src/child.rs", vec![])] {
|
|
let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..self::ctx() };
|
|
assert_eq!(hits_in(child, test, &ctx), expected, "{child}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_removed_child_declaration_still_reaches_the_child() {
|
|
let work: HashMap<&str, &str> = [
|
|
(
|
|
"crates/x/src/lib.rs",
|
|
"#[path = \"impl/platform.rs\"]\nmod platform;\n#[cfg(target_os = \"macos\")]\n#[path = \"impl/child.rs\"]\nmod child;\n",
|
|
),
|
|
("crates/x/src/impl/platform.rs", ""),
|
|
("crates/x/src/impl/child.rs", ""),
|
|
]
|
|
.into_iter()
|
|
.collect();
|
|
let read = |p: &str| work.get(p).map(|s| (*s).to_owned());
|
|
let read_base = |p: &str| if p == "crates/x/src/impl/platform.rs" { Some("mod child;\n".to_owned()) } else { read(p) };
|
|
let overrides = path_overrides(work.iter().map(|(p, s)| (*p, *s)));
|
|
let seeds = ["crates/x/src/impl/platform.rs".to_owned()];
|
|
let all: Vec<String> = work.keys().map(|p| (*p).to_owned()).collect();
|
|
let child = "crates/x/src/impl/child.rs".to_owned();
|
|
assert!(!descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &|_| None).contains(&child));
|
|
assert!(
|
|
descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &read_base).contains(&child),
|
|
"the base `mod child;` that the change removed still leads to child.rs"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn path_override_discovery_accepts_attribute_whitespace_in_both_trees() {
|
|
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
|
let root = std::env::temp_dir().join(format!("test-lint-path-{}-{unique}", std::process::id()));
|
|
std::fs::create_dir_all(root.join("crates/x/src")).unwrap();
|
|
git(&root, &["init", "--quiet"]).unwrap();
|
|
let files = [
|
|
("crates/x/src/a.rs", "#[cfg(target_os = \"macos\")]\n#[ path = \"shared.rs\"]\nmod s;\n"),
|
|
("crates/x/src/b.rs", "#[cfg(target_os = \"macos\")]\n#[\npath = \"shared.rs\"]\nmod s;\n"),
|
|
("crates/x/src/decoy.rs", "// path is not a module attribute\nmod other;\n"),
|
|
];
|
|
for (path, src) in files {
|
|
std::fs::write(root.join(path), src).unwrap();
|
|
}
|
|
git(&root, &["add", "."]).unwrap();
|
|
let base = git(&root, &["write-tree"]).unwrap();
|
|
for revision in [None, Some(base.as_str())] {
|
|
let read = |p: &str| match revision {
|
|
Some(base) => git(&root, &["show", &format!("{base}:{p}")]).ok(),
|
|
None => read_small(&root, p),
|
|
};
|
|
let overrides = discover_path_overrides(&root, revision, &read);
|
|
let child = "crates/x/src/shared.rs";
|
|
let parents: BTreeSet<&str> = overrides.get(child).into_iter().flatten().map(|(p, _)| p.as_str()).collect();
|
|
assert_eq!(parents, [files[0].0, files[1].0].into_iter().collect(), "both whitespace forms: {revision:?}");
|
|
let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in(child, test, &ctx), [(2, "never-run")], "the discovered gates apply: {revision:?}");
|
|
}
|
|
std::fs::remove_dir_all(root).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn base_root_routes_come_from_the_base_tree() {
|
|
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
|
let root = std::env::temp_dir().join(format!("test-lint-roots-{}-{unique}", std::process::id()));
|
|
std::fs::create_dir_all(root.join("crates/x/tests/common")).unwrap();
|
|
git(&root, &["init", "--quiet"]).unwrap();
|
|
std::fs::write(root.join("crates/x/tests/smoke.rs"), "mod common;\n").unwrap();
|
|
std::fs::write(root.join("crates/x/tests/common/mod.rs"), "").unwrap();
|
|
git(&root, &["add", "."]).unwrap();
|
|
let base = git(&root, &["write-tree"]).unwrap();
|
|
std::fs::remove_file(root.join("crates/x/tests/smoke.rs")).unwrap();
|
|
let shared = "crates/x/tests/common/mod.rs";
|
|
let now = vec![shared.to_owned()];
|
|
assert!(with_root_routes(Overrides::new(), &now).get(shared).is_none_or(|r| r.is_empty()), "no root loads it now");
|
|
let then = base_files(&root, &base).unwrap();
|
|
let routes = with_root_routes(Overrides::new(), &then);
|
|
let parents: Vec<&str> = routes.get(shared).into_iter().flatten().map(|(p, _)| p.as_str()).collect();
|
|
assert_eq!(parents, ["crates/x/tests/smoke.rs"], "the deleted root loaded it at the base");
|
|
std::fs::remove_dir_all(root).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_follows_a_path_selected_by_cfg_attr() {
|
|
let files: HashMap<&str, &str> = [
|
|
("crates/x/src/lib.rs", "#[cfg_attr(unix, path = \"live.rs\")]\nmod platform;\n#[cfg(target_os = \"macos\")]\nmod live;\n"),
|
|
("crates/x/src/live.rs", ""),
|
|
("crates/x/src/platform.rs", ""),
|
|
]
|
|
.into_iter()
|
|
.collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s)));
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
let live = "crates/x/src/live.rs".to_owned();
|
|
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&live), &read, &overrides), ..ctx() };
|
|
assert_eq!(hits_in(&live, test, &ctx), [], "Linux loads live.rs through the cfg_attr path");
|
|
let platform = "crates/x/src/platform.rs".to_owned();
|
|
let gates = module_gates(std::slice::from_ref(&platform), &read, &overrides);
|
|
assert_eq!(gates.get(&platform).map(|g| g.preds.clone()), Some(vec!["not(any(unix))".to_owned()]), "the default path elsewhere");
|
|
}
|
|
|
|
#[test]
|
|
fn changed_lines_lists_both_paths_of_an_exact_rename() {
|
|
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
|
let root = std::env::temp_dir().join(format!("test-lint-rename-{}-{unique}", std::process::id()));
|
|
std::fs::create_dir_all(root.join("crates/x/src/bin")).unwrap();
|
|
git(&root, &["init", "--quiet"]).unwrap();
|
|
let src = "#[path = \"../shared.rs\"]\nmod shared;\nfn main() {}\n";
|
|
std::fs::write(root.join("crates/x/src/bin/tool.rs"), src).unwrap();
|
|
git(&root, &["add", "."]).unwrap();
|
|
let base = git(&root, &["write-tree"]).unwrap();
|
|
std::fs::create_dir_all(root.join("crates/x/src/disabled")).unwrap();
|
|
std::fs::rename(root.join("crates/x/src/bin/tool.rs"), root.join("crates/x/src/disabled/tool.rs")).unwrap();
|
|
git(&root, &["add", "-A"]).unwrap();
|
|
let changed = changed_lines(&root, &base).unwrap();
|
|
assert_eq!(changed.get("crates/x/src/bin/tool.rs"), Some(&None), "the old path counts as deleted");
|
|
assert_eq!(changed.get("crates/x/src/disabled/tool.rs"), Some(&None), "the new path counts as added");
|
|
std::fs::remove_dir_all(root).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_joins_inline_and_override_routes() {
|
|
for (lib, child) in [
|
|
("mod platform { mod child; }\nmod a;\n", "crates/x/src/platform/child.rs"),
|
|
("mod platform { mod nested { mod child; } }\nmod a;\n", "crates/x/src/platform/nested/child.rs"),
|
|
] {
|
|
let a = format!("#[cfg(target_os = \"macos\")]\n#[path = \"{}\"]\nmod other;\n", child.strip_prefix("crates/x/src/").unwrap_or(child));
|
|
let files = [("crates/x/src/lib.rs", lib), ("crates/x/src/a.rs", a.as_str())];
|
|
let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned());
|
|
let overrides = path_overrides(files);
|
|
let gates = module_gates(&[child.to_owned()], &read, &overrides);
|
|
let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in(child, test, &ctx), [], "the ungated inline route runs it");
|
|
for parent in ["crates/x/src/lib.rs", "crates/x/src/a.rs"] {
|
|
let changed = [(parent.to_owned(), Some([1].into_iter().collect()))].into_iter().collect();
|
|
assert!(gate_changed(gates.get(child), &changed), "both routes contribute their source lines: {parent}");
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_keeps_default_and_override_files_separate() {
|
|
let files = [
|
|
("crates/x/src/lib.rs", "mod a;\n"),
|
|
("crates/x/src/a.rs", "mod shared;\n#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod other;\n"),
|
|
];
|
|
let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned());
|
|
let overrides = path_overrides(files);
|
|
let paths = ["crates/x/src/shared.rs".to_owned(), "crates/x/src/a/shared.rs".to_owned()];
|
|
let gates = module_gates(&paths, &read, &overrides);
|
|
let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in(&paths[0], test, &ctx), [(2, "never-run")], "only the macOS override loads this file");
|
|
assert_eq!(hits_in(&paths[1], test, &ctx), [], "the default declaration loads the file under a/");
|
|
let changed = [("crates/x/src/a.rs".to_owned(), Some([1].into_iter().collect()))].into_iter().collect();
|
|
assert!(!gate_changed(gates.get(&paths[0]), &changed), "the default declaration belongs to the other file");
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_resolves_every_routes_ancestors() {
|
|
for (a, b, child) in [
|
|
("#[path = \"shared.rs\"]\nmod s;\n", "#[path = \"shared.rs\"]\nmod s;\n", "crates/x/src/shared.rs"),
|
|
("mod shared;\n", "#[path = \"a/shared.rs\"]\nmod s;\n", "crates/x/src/a/shared.rs"),
|
|
] {
|
|
for target in ["linux", "macos"] {
|
|
let lib = format!("#[cfg(target_os = \"macos\")]\nmod a;\n#[cfg(target_os = \"{target}\")]\nmod b;\n");
|
|
let files = [("crates/x/src/lib.rs", lib.as_str()), ("crates/x/src/a.rs", a), ("crates/x/src/b.rs", b)];
|
|
let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned());
|
|
let overrides = path_overrides(files);
|
|
let gates = module_gates(&[child.to_owned()], &read, &overrides);
|
|
let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
let expected = if target == "linux" { vec![] } else { vec![(2, "never-run")] };
|
|
assert_eq!(hits_in(child, test, &ctx), expected, "the second route's ancestors decide whether Linux runs it");
|
|
for (parent, line) in [
|
|
("crates/x/src/a.rs", if a.starts_with("#[path") { 2 } else { 1 }),
|
|
("crates/x/src/b.rs", 2),
|
|
("crates/x/src/lib.rs", 2),
|
|
("crates/x/src/lib.rs", 4),
|
|
] {
|
|
let changed = [(parent.to_owned(), Some([line].into_iter().collect()))].into_iter().collect();
|
|
assert!(gate_changed(gates.get(child), &changed), "every route and its ancestors: {parent}:{line}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn removed_module_routes_count_only_newly_off_tests() {
|
|
let a = "crates/x/src/a.rs";
|
|
let child = "crates/x/src/shared.rs";
|
|
let declaration = "#[path = \"shared.rs\"]\nmod s;\n";
|
|
let mac = "#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod s;\n";
|
|
let work_files = [("crates/x/src/lib.rs", "mod a;\nmod b;\n"), (a, ""), ("crates/x/src/b.rs", mac)];
|
|
let read_work = |p: &str| work_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned());
|
|
let overrides = path_overrides(work_files);
|
|
let paths = [child.to_owned()];
|
|
let gates = module_gates(&paths, &read_work, &overrides);
|
|
let work_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_work, &overrides), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
let hit = lint_file(child, test, &work_ctx).into_iter().find(|h| h.rule == Rule::NeverRun).unwrap();
|
|
for (before, ran) in [(declaration, true), (mac, false)] {
|
|
let base_files = [("crates/x/src/lib.rs", work_files[0].1), (a, before), ("crates/x/src/b.rs", mac)];
|
|
let read_base = |p: &str| base_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned());
|
|
let base_overrides = path_overrides(base_files);
|
|
let base_gates = module_gates(&paths, &read_base, &base_overrides);
|
|
let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() };
|
|
let files = work_files.iter().map(|(p, _)| (*p).to_owned()).chain(paths.iter().cloned()).collect::<Vec<_>>();
|
|
assert!(
|
|
descendants(&[a.to_owned()], &files, &overrides, &base_overrides, &|_| None, &|_| None).contains(&child.to_owned()),
|
|
"the removed route still reaches the shared tests"
|
|
);
|
|
for lines in [Some(BTreeSet::new()), Some([20].into_iter().collect()), None] {
|
|
let changed = [(a.to_owned(), lines)].into_iter().collect();
|
|
assert!(!gate_changed(gates.get(child), &changed), "the surviving route was not edited");
|
|
let parent_changed = route_gate_changed(child, gates.get(child), base_gates.get(child), &base_overrides, &changed);
|
|
assert!(parent_changed, "deletions and shifted lines still change a base route");
|
|
assert_eq!(parent_changed && !already_off(&lint_file(child, test, &base_ctx), test, test, &hit), ran);
|
|
assert!(
|
|
route_gate_changed(child, gates.get(child), None, &base_overrides, &changed),
|
|
"a base route parent counts even without inherited predicates"
|
|
);
|
|
}
|
|
let changed = [("crates/x/src/lib.rs".to_owned(), Some([20].into_iter().collect()))].into_iter().collect();
|
|
assert!(
|
|
route_gate_changed(child, gates.get(child), base_gates.get(child), &base_overrides, &changed),
|
|
"an edited base ancestor counts even when its old line numbers do not match"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn base_path_overrides_follow_declarations_before_a_move() {
|
|
let a = "crates/x/src/a.rs";
|
|
let b = "crates/x/src/b.rs";
|
|
let child = "crates/x/src/shared.rs";
|
|
let lib = "#[cfg(target_os = \"macos\")]\nmod a;\n#[cfg(target_os = \"macos\")]\nmod b;\n";
|
|
let declaration = "#[path = \"shared.rs\"]\nmod s;\n";
|
|
let base_files = [("crates/x/src/lib.rs", lib), (a, declaration), (b, "")];
|
|
let work_files = [("crates/x/src/lib.rs", lib), (a, ""), (b, declaration)];
|
|
let read_base = |p: &str| base_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned());
|
|
let read_work = |p: &str| work_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned());
|
|
let base_overrides = listed_path_overrides(&format!("before:{a}\0"), Some("before"), &read_base);
|
|
let work_overrides = listed_path_overrides(&format!("{b}\0"), None, &read_work);
|
|
let paths = [child.to_owned()];
|
|
let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() };
|
|
let work_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_work, &work_overrides), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in(child, test, &work_ctx), [(2, "never-run")]);
|
|
assert_eq!(hits_in(child, test, &base_ctx), [(2, "never-run")], "the test was already off before the equally gated declaration moved");
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_joins_two_inline_routes_from_one_file() {
|
|
let a = "#[cfg(target_os = \"macos\")]\nmod m {\n #[path = \"../shared.rs\"]\n mod s;\n}\nmod n {\n #[path = \"../shared.rs\"]\n mod s;\n}\n";
|
|
let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "mod a;\n"), ("crates/x/src/a.rs", a)].into_iter().collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s)));
|
|
let shared = "crates/x/src/a/shared.rs".to_owned();
|
|
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in(&shared, test, &ctx), [], "the ungated route through `n` runs it");
|
|
}
|
|
|
|
#[test]
|
|
fn a_detached_module_is_not_an_ungated_route() {
|
|
let decl = "#[path = \"shared.rs\"]\nmod s;\n";
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
let shared = "crates/x/src/shared.rs".to_owned();
|
|
for (lib, off) in [("#[cfg(target_os = \"macos\")]\nmod b;\n", true), ("mod a;\n#[cfg(target_os = \"macos\")]\nmod b;\n", false)] {
|
|
let files: HashMap<&str, &str> =
|
|
[("crates/x/src/lib.rs", lib), ("crates/x/src/a.rs", decl), ("crates/x/src/b.rs", decl)].into_iter().collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s)));
|
|
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() };
|
|
let want: &[(usize, &str)] = if off { &[(2, "never-run")] } else { &[] };
|
|
assert_eq!(hits_in(&shared, test, &ctx), want, "{lib}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_path_on_an_inline_module_sets_its_directory() {
|
|
let lib = "#[cfg(target_os = \"macos\")]\n#[path = \"platform_impl\"]\nmod platform {\n mod child;\n}\n";
|
|
let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", lib)].into_iter().collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let child = "crates/x/src/platform_impl/child.rs".to_owned();
|
|
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &Overrides::new()), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")]);
|
|
}
|
|
|
|
#[test]
|
|
fn cfg_values_compare_decoded_strings() {
|
|
let linux = &CI_TARGETS[0];
|
|
assert_eq!(cfg_value("target_os=\"\\x6cinux\"", linux), Some(true));
|
|
assert_eq!(cfg_value("target_os=\"\\u{6c}inux\"", linux), Some(true));
|
|
assert_eq!(cfg_value("target_os=r\"linux\"", linux), Some(true));
|
|
assert_eq!(cfg_value("target_os=r\"\\x6cinux\"", linux), Some(false), "a raw string is not decoded");
|
|
assert_eq!(cfg_value("target_family=r#\"unix\"#", linux), Some(true));
|
|
assert_eq!(cfg_value("target_family=r#\"\"unix\"\"#", linux), Some(false), "quotes inside a raw string are part of the value");
|
|
}
|
|
|
|
#[test]
|
|
fn path_override_listings_are_nul_separated() {
|
|
let files: HashMap<&str, &str> =
|
|
[("crates/x/src/a.rs", "#[path = \"s.rs\"]\nmod s;\n"), ("crates/x/src/caf\u{e9}.rs", "#[path = \"t.rs\"]\nmod t;\n")]
|
|
.into_iter()
|
|
.collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let got = listed_path_overrides("base:crates/x/src/a.rs\0base:crates/x/src/caf\u{e9}.rs\0", Some("base"), &read);
|
|
assert!(got.contains_key("crates/x/src/s.rs"), "{got:?}");
|
|
assert!(got.contains_key("crates/x/src/t.rs"), "{got:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn deleted_files_are_kept_as_changed() {
|
|
let diff = "diff --git a/crates/x/src/bin/tool.rs b/crates/x/src/bin/tool.rs\ndeleted file mode 100644\n--- a/crates/x/src/bin/tool.rs\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-#[path = \"../shared.rs\"]\n-mod shared;\n";
|
|
let got = parse_diff(diff);
|
|
assert_eq!(got.get("crates/x/src/bin/tool.rs"), Some(&None), "{got:?}");
|
|
let base: Overrides = [("crates/x/src/shared.rs".to_owned(), vec![("crates/x/src/bin/tool.rs".to_owned(), vec![])])].into_iter().collect();
|
|
let seeds: Vec<String> = got.keys().cloned().collect();
|
|
let files = ["crates/x/src/shared.rs".to_owned()];
|
|
assert_eq!(descendants(&seeds, &files, &Overrides::new(), &base, &|_| None, &|_| None), ["crates/x/src/shared.rs"]);
|
|
}
|
|
|
|
#[test]
|
|
fn a_changed_file_reaches_the_files_its_path_loaded_modules_load() {
|
|
let files: Vec<String> = ["src/solids/graphics.rs", "src/solids/map_art.rs", "src/solids/tests_map_art.rs", "src/solids/other.rs"]
|
|
.into_iter()
|
|
.map(String::from)
|
|
.collect();
|
|
let sources = [
|
|
("src/solids/graphics.rs", "#[path = \"map_art.rs\"]\nmod art;\n"),
|
|
("src/solids/map_art.rs", "#[path = \"tests_map_art.rs\"]\nmod tests;\n"),
|
|
];
|
|
let overrides = path_overrides(sources);
|
|
let read = |p: &str| sources.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned());
|
|
let found = descendants(&["src/solids/graphics.rs".to_owned()], &files, &overrides, &Overrides::new(), &read, &|_| None);
|
|
assert_eq!(found, ["src/solids/map_art.rs", "src/solids/tests_map_art.rs"], "through map_art.rs, and not other.rs");
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_counts_every_line_of_a_multiline_test_gate() {
|
|
let src =
|
|
"#[cfg(all(\n unix,\n target_os = \"macos\",\n))]\nmod mac {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n";
|
|
let found = lint_file("crates/x/src/tests.rs", src, &ctx());
|
|
let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap();
|
|
assert!(touches(hit, Some(&[3].into_iter().collect())), "an edit inside the predicate");
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_skips_later_attributes_and_true_gates() {
|
|
let case = "#[cfg(windows)]\n#[test_case(1; \"one\")]\nfn t(n: usize) {\n assert_eq!(f(n), 2);\n}\n";
|
|
assert_eq!(only("never-run", case), [(3, "never-run")], "a `;` inside a later attribute");
|
|
let commented = "#[cfg(target_os = /* supported */ \"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", commented), [], "a comment inside the predicate");
|
|
let unix = "#[cfg(unix)]\nmod u {\n #[cfg(target_os = \"macos\")]\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n";
|
|
let found = lint_file("crates/x/src/tests.rs", unix, &ctx());
|
|
let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap();
|
|
assert!(!touches(hit, Some(&[1].into_iter().collect())), "cfg(unix) holds on Linux and FreeBSD");
|
|
assert!(touches(hit, Some(&[3].into_iter().collect())), "the macOS-only cfg on the test");
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_takes_every_declaration_of_a_module() {
|
|
let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(windows)]\nmod child;\n#[cfg(unix)]\nmod child;\n")].into_iter().collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let both = Ctx { module_cfgs: module_cfgs(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new()), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in("crates/x/src/child.rs", test, &both), [], "the unix declaration builds it on Linux");
|
|
let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(windows)]\nmod child;\n")].into_iter().collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let windows = Ctx { module_cfgs: module_cfgs(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new()), ..ctx() };
|
|
assert_eq!(hits_in("crates/x/src/child.rs", test, &windows), [(2, "never-run")]);
|
|
}
|
|
|
|
#[test]
|
|
fn never_run_hits_cover_the_attribute_that_turns_the_test_off() {
|
|
let src = "#[cfg(target_os = \"macos\")]\nmod mac {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n";
|
|
let found = lint_file("crates/x/src/tests.rs", src, &ctx());
|
|
let hit = found.iter().find(|h| h.rule == Rule::NeverRun).map(|h| (h.first, h.line, h.gates.clone()));
|
|
assert_eq!(hit, Some((3, 4, vec![1])));
|
|
assert!(touches(found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(), Some(&[1].into_iter().collect())), "a change to the cfg alone");
|
|
let helper =
|
|
"#[cfg(target_os = \"macos\")]\nmod mac {\n fn helper() {}\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n";
|
|
let found = lint_file("crates/x/src/tests.rs", helper, &ctx());
|
|
let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap();
|
|
assert!(!touches(hit, Some(&[3].into_iter().collect())), "a helper between the module cfg and the test");
|
|
let two = "#[cfg(target_os = \"macos\")]\nmod mac {\n // test-lint: allow never-run checks the macOS menu bar\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\n";
|
|
let left: Vec<usize> = lint_file("crates/x/src/tests.rs", two, &ctx()).iter().filter(|h| h.rule == Rule::NeverRun).map(|h| h.line).collect();
|
|
assert_eq!(left, [9], "an allow above one test leaves the next one reported");
|
|
}
|
|
|
|
#[test]
|
|
fn exact_pixels_compare_a_rect_with_numbers() {
|
|
let ui = |body: &str| format!("use egui::Rect;\n#[test]\nfn t() {{\n {body}\n}}\n");
|
|
let px = |body: &str| only("exact-pixel", &ui(body));
|
|
assert_eq!(px("assert_eq!(button_rect.min.x, 12.0);"), [(4, "exact-pixel")]);
|
|
assert_eq!(px("assert_eq!(resp.rect, Rect::from_min_size(pos2(0.0, 20.0), vec2(80.0, 24.0)));"), [(4, "exact-pixel")]);
|
|
assert_eq!(px("assert!(rect.width() == 120.0);"), [(4, "exact-pixel")]);
|
|
assert_eq!(px("assert!(panel_rect.contains_rect(button_rect));"), [], "a relationship");
|
|
assert_eq!(px("assert!(rect.width() >= SPACING);"), []);
|
|
assert_eq!(px("assert_eq!(left_rect.width() - right_rect.width(), 0.0);"), [], "two rects compared by their difference");
|
|
assert_eq!(px("assert_eq!(left_rect.width(), 120.0);"), [(4, "exact-pixel")]);
|
|
assert_eq!(px("assert_eq!(rects.len(), 3);"), [], "a count");
|
|
assert_eq!(px("assert_eq!(correct, 3);"), [], "a word that only contains rect");
|
|
assert_eq!(px("assert_eq!(tabs_rect(&app).min.y, 0.0);"), [(4, "exact-pixel")], "a call that returns a rect");
|
|
assert_eq!(px("assert_eq!(doc.artboards[1].rect.width(), 100.0);"), [], "document geometry in a UI test");
|
|
assert_eq!(px("assert_eq!(dock_rect.width(), 120.0);"), [(4, "exact-pixel")], "a name that only starts with doc");
|
|
assert_eq!(px("assert_eq!((rect.x0, rect.y0), (200.0, 200.0));"), [], "document corners");
|
|
assert_eq!(px("assert_eq!(rgb8(&fill_color(&app, rect)), [255, 255, 255]);"), [], "a rect passed on");
|
|
assert_eq!(px("assert_eq!(count_items(button_rect), 3);"), [], "a rect passed to a call");
|
|
assert_eq!(px("assert_eq!(column_for_x(button_rect.min.x), 2);"), [], "a coordinate passed to a call");
|
|
assert_eq!(px("assert_eq!((button_rect.width()), 120.0);"), [(4, "exact-pixel")], "grouping parentheses");
|
|
assert_eq!(px("assert_eq!(button_rect.width() / panel_rect.width(), 0.5);"), [], "a ratio");
|
|
let engine = "#[test]\nfn t() {\n assert_eq!(art_rect.width(), 10.0);\n}\n";
|
|
assert_eq!(only("exact-pixel", engine), [], "document geometry outside UI code");
|
|
}
|
|
|
|
#[test]
|
|
fn reads_source_covers_read_to_string_of_rust_files() {
|
|
let read = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", read), [(3, "reads-source")]);
|
|
let data = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", data), []);
|
|
let comment = "#[test]\nfn t() {\n let s = fs::read_to_string(/* formerly \"input.rs\" */ \"data.json\").unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment");
|
|
let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file");
|
|
let unknown = "#[test]\nfn t() {\n let name = \"data.json\";\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(name)).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", unknown), [], "a final component that is not a literal");
|
|
let joined =
|
|
"#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src\").join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", joined), [(3, "reads-source")], "a final join that names a .rs file");
|
|
let nested = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(if root.join(\"config.rs\").exists() { \"a.json\" } else { \"b.json\" })).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", nested), [], "a join inside the outer join's argument");
|
|
let extension = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"sample.rs\").with_extension(\"json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", extension), [], "a final extension that is not rs");
|
|
let to_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"lib.txt\").with_extension(\"rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", to_rs), [(3, "reads-source")], "a final extension of rs");
|
|
let ext_var = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"sample.rs\").with_extension(ext)).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", ext_var), [], "a final extension that is not a literal");
|
|
let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"fixtures/{}.txt\", \"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", formatted), [], "a format argument is not the file read");
|
|
let format_rs =
|
|
"#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/lib.rs\", dir)).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", format_rs), [(3, "reads-source")], "a format string that names a .rs file");
|
|
let grouped_ext = "#[test]\nfn t() {\n let s = fs::read_to_string((root.join(\"sample.rs\").with_extension(ext))).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", grouped_ext), [], "grouping around the argument hides no step");
|
|
let grouped_rs =
|
|
"#[test]\nfn t() {\n let s = fs::read_to_string(&(root.join(\"src/lib.rs\"))).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", grouped_rs), [(3, "reads-source")], "a grouped join that names a .rs file");
|
|
let computed = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\".trim_end_matches(\".rs\"))).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", computed), [], "a computed file name is not its last literal");
|
|
let wrapped = "#[test]\nfn t() {\n let s = fs::read_to_string(Path::new(\"src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", wrapped), [(3, "reads-source")], "a literal inside Path::new");
|
|
let split = "#[test]\nfn t() {\n let s = fs::read_to_string(\n \"src/lib.rs\",\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
|
let found = lint_file("crates/x/src/tests.rs", split, &ctx());
|
|
let hit = found.iter().find(|h| h.rule == Rule::ReadsSource).unwrap();
|
|
assert_eq!((hit.line, hit.last), (3, 5), "the span runs through the path on the next line");
|
|
assert!(touches(hit, Some(&[4].into_iter().collect())));
|
|
}
|
|
|
|
#[test]
|
|
fn weak_predicates_keep_the_polarity_of_a_negation() {
|
|
assert!(weak_predicate("parse(input).is_ok()"));
|
|
assert!(weak_predicate("!xs.is_empty()"));
|
|
assert!(!weak_predicate("!parse(input).is_ok()"), "a rejection");
|
|
assert!(!weak_predicate("!x.is_some()"), "an absence");
|
|
assert!(weak_predicate("!!x.is_some()"));
|
|
}
|
|
|
|
#[test]
|
|
fn negated_membership_checks_are_not_presence_checks() {
|
|
assert!(!weak_predicate("!errors_for(c).contains(&Error::Unexpected)"));
|
|
assert!(!weak_predicate("!map.contains_key(&k)"));
|
|
assert!(weak_predicate("!items.is_empty()"));
|
|
assert!(weak_predicate("errors_for(c).contains(&Error::Expected)"));
|
|
}
|
|
|
|
#[test]
|
|
fn a_for_binding_shadows_the_outer_one_in_its_body() {
|
|
let looped = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n assert_eq!(n, 1);\n }\n}\n";
|
|
assert_eq!(only("fixture-only", looped), []);
|
|
let broken = "#[test]\nfn t() {\n let n = 0;\n for n in\n results()\n {\n assert_eq!(n, 1);\n }\n}\n";
|
|
assert_eq!(only("fixture-only", broken), [], "a line break after `in`");
|
|
let after = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n";
|
|
assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop");
|
|
let mutable = "#[test]\nfn t() {\n let n = 0;\n for mut n in results() {\n n += 1;\n assert_eq!(n, 2);\n }\n}\n";
|
|
assert_eq!(only("fixture-only", mutable), [], "`mut n` binds `n`");
|
|
let destructured = "#[test]\nfn t() {\n let n = 0;\n for Row { n } in rows() {\n assert_eq!(n, 2);\n }\n}\n";
|
|
assert_eq!(only("fixture-only", destructured), [], "the braces of a struct pattern are not the loop body");
|
|
let mut_after = "#[test]\nfn t() {\n let n = 0;\n for mut n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n";
|
|
assert_eq!(only("fixture-only", mut_after), [(2, "fixture-only")], "the outer binding after a `mut` loop");
|
|
}
|
|
|
|
#[test]
|
|
fn a_closure_parameter_shadows_the_outer_binding_in_its_body() {
|
|
let closure = "#[test]\nfn t() {\n let n = 0;\n results().into_iter().for_each(|n| assert_eq!(n, 1));\n}\n";
|
|
assert_eq!(only("fixture-only", closure), []);
|
|
let block = "#[test]\nfn t() {\n let n = 0;\n results().into_iter().for_each(move |n| {\n assert_eq!(n, 1);\n });\n}\n";
|
|
assert_eq!(only("fixture-only", block), [], "a block body");
|
|
let captured = "#[test]\nfn t() {\n let n = 0;\n results().into_iter().for_each(|m| assert_eq!(n, 0));\n}\n";
|
|
assert_eq!(only("fixture-only", captured), [(2, "fixture-only")], "an unshadowed name is the captured fixture");
|
|
}
|
|
|
|
#[test]
|
|
fn nested_cfg_attr_gates_apply() {
|
|
let nested = "#[cfg_attr(unix, cfg_attr(test, cfg(target_os = \"macos\")))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", nested), [(3, "never-run")]);
|
|
let unknown = "#[cfg_attr(unix, cfg_attr(feature = \"gpu\", cfg(target_os = \"macos\")))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", unknown), []);
|
|
let bracket = "#[cfg(any(target_os = \"(\", unix))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", bracket), [], "a bracket inside a string value");
|
|
let comma = "#[cfg_attr(target_os = \",\", cfg(windows))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(only("never-run", comma), [], "a comma inside the condition's value");
|
|
let src = "#[cfg_attr(unix, path = \"a,b.rs\")]\nmod x;\n";
|
|
assert_eq!(cfg_attr_paths(&mask(src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "a,b.rs".to_owned())]);
|
|
let raw = "#[cfg_attr(unix, path = r#\"a.rs\"#)]\nmod x;\n";
|
|
assert_eq!(cfg_attr_paths(&mask(raw), raw.as_bytes(), 0, raw.len()), [("unix".to_owned(), "a.rs".to_owned())]);
|
|
let escaped = "#[cfg_attr(unix, path = \"\\x61.rs\")]\nmod x;\n";
|
|
assert_eq!(cfg_attr_paths(&mask(escaped), escaped.as_bytes(), 0, escaped.len()), [("unix".to_owned(), "a.rs".to_owned())]);
|
|
let raw_escape = "#[cfg_attr(unix, path = r\"\\x61.rs\")]\nmod x;\n";
|
|
assert_eq!(cfg_attr_paths(&mask(raw_escape), raw_escape.as_bytes(), 0, raw_escape.len()), [("unix".to_owned(), "\\x61.rs".to_owned())]);
|
|
}
|
|
|
|
#[test]
|
|
fn conditional_paths_decode_string_continuations() {
|
|
for newline in ["\n", "\r\n"] {
|
|
let src = format!("#[cfg_attr(unix, path = \"chi\\{newline} \t\r\n ld.rs\")]\nmod c;\n");
|
|
assert_eq!(cfg_attr_paths(&mask(&src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "child.rs".to_owned())]);
|
|
}
|
|
let src = "#[cfg_attr(unix, path = \"child file.rs\")]\nmod c;\n";
|
|
assert_eq!(cfg_attr_paths(&mask(src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "child file.rs".to_owned())]);
|
|
let raw = "#[cfg_attr(unix, path = r\"chi\\\n ld.rs\")]\nmod c;\n";
|
|
assert_eq!(cfg_attr_paths(&mask(raw), raw.as_bytes(), 0, raw.len()), [("unix".to_owned(), "chi\\\n ld.rs".to_owned())]);
|
|
}
|
|
|
|
#[test]
|
|
fn conditional_paths_keep_sibling_cfg_gates_with_brackets_in_filenames() {
|
|
let files: HashMap<&str, &str> =
|
|
[("crates/x/src/lib.rs", "#[cfg_attr(unix, path = \"mac[.rs\", cfg(target_os = \"macos\"))]\nmod platform;\n")].into_iter().collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s)));
|
|
let child = "crates/x/src/mac[.rs".to_owned();
|
|
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &overrides), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")]);
|
|
}
|
|
|
|
#[test]
|
|
fn path_attributes_accept_raw_strings() {
|
|
for src in ["#[path = r\"shared.rs\"]\nmod s;\n", "#[path = r#\"shared.rs\"#]\nmod s;\n", "#[path = \"shared.rs\"]\nmod s;\n"] {
|
|
assert_eq!(path_attr(&mask(src), src.as_bytes(), 0, src.len()).as_deref(), Some("shared.rs"), "{src}");
|
|
}
|
|
let files: HashMap<&str, &str> = [
|
|
("crates/x/src/lib.rs", "mod a;\nmod b;\n"),
|
|
("crates/x/src/a.rs", "#[path = r\"shared.rs\"]\nmod s;\n"),
|
|
("crates/x/src/b.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod s;\n"),
|
|
]
|
|
.into_iter()
|
|
.collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s)));
|
|
let shared = "crates/x/src/shared.rs".to_owned();
|
|
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in(&shared, test, &ctx), [], "the raw-string route runs it on Linux");
|
|
}
|
|
|
|
#[test]
|
|
fn path_attributes_decode_escapes_in_ordinary_strings() {
|
|
let escaped = "#[path = \"\\x63hild.rs\"]\nmod c;\n";
|
|
assert_eq!(path_attr(&mask(escaped), escaped.as_bytes(), 0, escaped.len()).as_deref(), Some("child.rs"));
|
|
let raw = "#[path = r\"\\x63hild.rs\"]\nmod c;\n";
|
|
assert_eq!(path_attr(&mask(raw), raw.as_bytes(), 0, raw.len()).as_deref(), Some("\\x63hild.rs"), "a raw string keeps its backslash");
|
|
}
|
|
|
|
#[test]
|
|
fn an_escaped_plain_path_after_a_cfg_attr_path_is_the_fallback_route() {
|
|
// Linux loads `child.rs` through the plain attribute, the fallback of the `cfg_attr` override.
|
|
let files: HashMap<&str, &str> =
|
|
[("crates/x/src/lib.rs", "#[cfg_attr(windows, path = \"child.rs\")]\n#[path = \"\\x63hild.rs\"]\nmod c;\n")].into_iter().collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s)));
|
|
let child = "crates/x/src/child.rs".to_owned();
|
|
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &overrides), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in(&child, test, &ctx), [], "the plain attribute's route runs it on Linux");
|
|
}
|
|
|
|
#[test]
|
|
fn a_module_loaded_by_two_roots_runs_if_either_runs_it() {
|
|
let files: HashMap<&str, &str> = [
|
|
("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod shared;\n"),
|
|
("crates/x/src/main.rs", "mod shared;\n"),
|
|
("crates/x/src/shared.rs", ""),
|
|
]
|
|
.into_iter()
|
|
.collect();
|
|
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
|
let ctx = Ctx { module_cfgs: module_cfgs(&["crates/x/src/shared.rs".to_owned()], &read, &Overrides::new()), ..ctx() };
|
|
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
|
assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []);
|
|
}
|
|
|
|
#[test]
|
|
fn census_follows_the_calls_that_run_for_each_entry() {
|
|
let census_in = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
|
let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n");
|
|
let census = |body: &str| census_in(&loop_of(body));
|
|
assert_eq!(census("assert!(menu(c).is_some() || verify_fallback(c).is_ok());"), [(2, "census")], "a helper after || can be skipped");
|
|
assert_eq!(census("assert!(menu(c).is_some() && verify_fallback(c).is_ok());"), [], "a helper after && runs");
|
|
assert_eq!(census("assert!(menu(c).is_some()); { let c = fallback(); app.run(c); }"), [(2, "census")], "a shadowed entry name");
|
|
assert_eq!(census("assert!(menu(c).is_some()); app.run(c);"), [], "the entry itself");
|
|
assert_eq!(census("let _run = || app.run(c); assert!(menu(c).is_some());"), [(2, "census")], "a closure that is never called");
|
|
assert_eq!(
|
|
census("let _run = || { let r = app.run(c); r }; assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a block closure that is never called"
|
|
);
|
|
assert_eq!(census("let run = || { let r = app.run(c); r }; assert!(run().is_ok());"), [], "a block closure the loop calls");
|
|
assert_eq!(
|
|
census("let params = fallback(); app.run(params); let params = c; assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a binding from the entry does not reach back to an earlier use of its name"
|
|
);
|
|
assert_eq!(
|
|
census("{ let params = c; } app.run(params); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a binding from the entry ends with its block"
|
|
);
|
|
assert_eq!(census("app.run(options.c); assert!(menu(c).is_some());"), [(2, "census")], "a field with the entry's name");
|
|
assert_eq!(census("assert!(app.run::<Mode>(c).is_ok());"), [], "a call with a turbofish");
|
|
assert_eq!(census("assert!(menu::<Mode>(c).is_some());"), [(2, "census")], "an entry-only call with a turbofish");
|
|
assert_eq!(census("assert!(render(c, -offset).is_ok());"), [], "a negated variable is another input");
|
|
assert_eq!(census("assert!(render(c, -2).is_ok());"), [(2, "census")], "a negative literal is not");
|
|
assert_eq!(
|
|
census("let _ = menu(c).is_some() || { app.run(c).is_ok() }; assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a block on the right of || can be skipped"
|
|
);
|
|
assert_eq!(
|
|
census("let _ = menu(c).is_some() || { foo(); app.run(c).is_ok() }; assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a semicolon keeps the enclosing ||"
|
|
);
|
|
assert_eq!(census("assert!(menu(c).is_some() && { foo(); app.run(c).is_ok() });"), [], "a semicolon keeps the enclosing &&");
|
|
assert_eq!(
|
|
census("let _ = (menu(c).is_some() || other(c).is_some()) && { app.run(c).is_ok() }; assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a discarded conjunction can skip the block when its left side is false"
|
|
);
|
|
assert_eq!(census("assert!(menu(c).is_some()); if first || second {} app.run(c);"), [], "an || in a finished if does not skip the call");
|
|
assert_eq!(
|
|
census("let entry = c; let c = fallback(); let c = entry; assert!(menu(c).is_some()); app.run(c);"),
|
|
[],
|
|
"a name rebound from the entry is the entry again"
|
|
);
|
|
assert_eq!(
|
|
census("let entry = c; let c = fallback(); { let c = entry; } assert!(menu(entry).is_some()); app.run(c);"),
|
|
[(2, "census")],
|
|
"an inner entry binding does not end the outer fallback binding"
|
|
);
|
|
assert_eq!(
|
|
census("let entry = c; let c = fallback(); { let c = entry; app.run(c); } assert!(menu(entry).is_some());"),
|
|
[],
|
|
"the inner entry binding is live inside its block"
|
|
);
|
|
assert_eq!(
|
|
census("let Row { c: other } = fallback(); assert!(menu(c).is_some()); app.run(c);"),
|
|
[],
|
|
"a field label does not rebind the entry"
|
|
);
|
|
let receiver = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(k.parse(), k);\n }\n}\n";
|
|
assert_eq!(census_in(receiver), [(2, "census")], "a round trip with the entry as receiver");
|
|
let fixed = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(registry.lookup(\"baseline\"), k);\n }\n}\n";
|
|
assert_eq!(census_in(fixed), [], "a lookup of a fixed key");
|
|
}
|
|
|
|
#[test]
|
|
fn census_follows_conditions_and_scopes_around_the_call() {
|
|
let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n");
|
|
let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
|
assert_eq!(
|
|
census("let _ = false && app.run(c).is_ok(); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a discarded conjunction can skip the call"
|
|
);
|
|
assert_eq!(
|
|
census("let ok = ready && app.run(c).is_ok(); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a bound conjunction can skip the call"
|
|
);
|
|
assert_eq!(census("debug_assert!(menu(c).is_some() && app.run(c).is_ok());"), [], "an asserted conjunction requires the call");
|
|
assert_eq!(
|
|
census("assert!(other(c).is_some() && app.run(c).is_ok() || menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"an || after the conjunction lets the assertion pass without it"
|
|
);
|
|
assert_eq!(census("let _ = &&app.run(c); assert!(menu(c).is_some());"), [], "a double borrow does not short-circuit the call");
|
|
assert_eq!(
|
|
census("let run = || app.run(c); assert!(menu(c).is_some() || run().is_ok());"),
|
|
[(2, "census")],
|
|
"a closure invocation after || can be skipped"
|
|
);
|
|
assert_eq!(
|
|
census("let run = || { app.run(c) }; assert!(menu(c).is_some() || run().is_ok());"),
|
|
[(2, "census")],
|
|
"a block closure invocation after || can be skipped"
|
|
);
|
|
assert_eq!(census("let run = || app.run(c); assert!(run().is_ok());"), [], "a closure invocation required by the assertion runs");
|
|
assert_eq!(
|
|
census("let run = || app.run(c); other.run(); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a method of the same name does not call the closure"
|
|
);
|
|
assert_eq!(
|
|
census("let run = || app.run(c).and(run()); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a recursive closure does not establish that its body runs"
|
|
);
|
|
assert_eq!(census("if false { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "an if can skip the call");
|
|
assert_eq!(census("if flag {} else { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "an else can skip the call");
|
|
assert_eq!(
|
|
census("match flag { true => { app.run(c); }, false => {} } assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a match arm can skip the call"
|
|
);
|
|
assert_eq!(census("while flag { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "a while can skip the call");
|
|
assert_eq!(census("let entry = c; { let c = entry; app.run(c); } assert!(menu(c).is_some());"), [], "a plain block runs");
|
|
assert_eq!(census("for c in defaults() { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "a nested loop shadows the entry");
|
|
assert_eq!(census("for c in app.defaults(c) { app.run(c); } assert!(menu(c).is_some());"), [], "the loop source reads the outer entry");
|
|
assert_eq!(
|
|
census("for c in defaults() { let params = c; app.run(params); } assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a nested binding stays shadowed through aliases"
|
|
);
|
|
assert_eq!(census("for c in defaults() {} app.run(c); assert!(menu(c).is_some());"), [], "the nested loop's shadow ends with its body");
|
|
assert_eq!(census("for x in 0..3 { app.run(c, x); } assert!(menu(c).is_some());"), [], "a nested loop body runs the call");
|
|
assert_eq!(
|
|
census("let run = |c| app.run(c); run(default()); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a closure parameter shadows the entry"
|
|
);
|
|
assert_eq!(
|
|
census("let run = |other| app.run(c); run(default()); assert!(menu(c).is_some());"),
|
|
[],
|
|
"another closure parameter keeps the entry"
|
|
);
|
|
assert_eq!(
|
|
census("let run = |c| { app.run(c); }; run(default()); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a block closure parameter shadows the entry"
|
|
);
|
|
assert_eq!(
|
|
census("let run = |other| { app.run(c); }; run(default()); assert!(menu(c).is_some());"),
|
|
[],
|
|
"a called block closure keeps its capture"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn census_follows_block_initializers_argument_guards_and_parameterized_closures() {
|
|
let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n");
|
|
let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
|
assert_eq!(census("let result = { verify(c) }; assert!(result.is_ok());"), [], "a block initializer runs its helper");
|
|
assert_eq!(
|
|
census("let _future = async { app.run(c); }; assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"an unpolled async block does not run its body"
|
|
);
|
|
assert_eq!(
|
|
census("let result = if ready { verify(c) } else { Ok(()) }; assert!(result.is_ok());"),
|
|
[(2, "census")],
|
|
"a conditional initializer can skip its helper"
|
|
);
|
|
assert_eq!(
|
|
census("let _ = false && accept(0, app.run(c)); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"an enclosing conjunction survives argument commas"
|
|
);
|
|
assert_eq!(census("let _ = accept(flag || other, app.run(c)); assert!(menu(c).is_some());"), [], "a sibling argument cannot skip the call");
|
|
assert_eq!(
|
|
census("let _ = ready || accept(0, app.run(c)); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"an enclosing disjunction survives argument commas"
|
|
);
|
|
assert_eq!(
|
|
census("let _ = ready && accept((flag || other, 0), app.run(c)); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a nested sibling keeps the enclosing guard"
|
|
);
|
|
assert_eq!(
|
|
census("assert!(menu(c).is_some() && accept(0, app.run(c)).is_some());"),
|
|
[],
|
|
"an asserted enclosing conjunction requires the argument"
|
|
);
|
|
assert_eq!(census("let _ = accept(0, { app.run(c) }); assert!(menu(c).is_some());"), [], "an argument block runs");
|
|
assert_eq!(
|
|
census("let _run = |_: ()| app.run(c); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"an uncalled typed closure can skip its body"
|
|
);
|
|
assert_eq!(census("let run = |_: ()| app.run(c); assert!(run(()).is_ok());"), [], "an asserted typed closure invocation runs its body");
|
|
assert_eq!(
|
|
census("let run = move |x| app.run(c, x); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"an uncalled move closure can skip its body"
|
|
);
|
|
assert_eq!(census("let run = move |x| app.run(c, x); assert!(run(0).is_ok());"), [], "an asserted move closure invocation runs its body");
|
|
assert_eq!(
|
|
census("let run = |_: ()| app.run(c); assert!(menu(c).is_some() || run(()).is_ok());"),
|
|
[(2, "census")],
|
|
"a guarded typed closure invocation can skip its body"
|
|
);
|
|
assert_eq!(
|
|
census("let run = |c: Command| app.run(c); run(default()); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a typed closure parameter shadows the entry"
|
|
);
|
|
assert_eq!(
|
|
census("app.run(defaults::c); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a path segment named like the entry does not read it"
|
|
);
|
|
assert_eq!(census("app.run(c); assert!(menu(c).is_some());"), [], "a plain argument reads the entry");
|
|
assert_eq!(census("let input = { prepare(); c }; assert!(render(input, offset).is_ok());"), [], "a block initializer's tail binds the entry");
|
|
assert_eq!(census("assert!(app.run /* note */ (c).is_ok());"), [], "a comment before the arguments keeps the call");
|
|
assert_eq!(
|
|
census("let input = { prepare(); let _ = c; fixed }; assert!(render(input, offset).is_ok()); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"a block initializer binds its tail, not earlier statements"
|
|
);
|
|
assert_eq!(
|
|
census("if let Some(input) = fallback() { prepare(); } menu(c); assert!(render(input, offset).is_ok()); assert!(menu(c).is_some());"),
|
|
[(2, "census")],
|
|
"an if let initializer ends at its block"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn census_leaves_out_loops_that_feed_the_entry_into_a_computation() {
|
|
let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
|
let run = "#[test]\nfn t() {\n let mut app = app();\n for k in Kind::ALL {\n assert!(app.session.execute(CMD, &json!({\"way\": k})).is_ok());\n }\n}\n";
|
|
assert_eq!(census(run), [], "a command run for each entry");
|
|
let split = "#[test]\nfn t() {\n let mut app = app();\n for k in Kind::ALL {\n assert!(app\n .run(k)\n .is_ok());\n }\n}\n";
|
|
assert_eq!(census(split), [], "a chain split over lines keeps its receiver");
|
|
let rendered = "#[test]\nfn t() {\n let d = doc();\n for level in Level::ALL {\n let ps = export(&d, &Options { level, ..opts() });\n assert!(ps.contains(\"op\"));\n }\n}\n";
|
|
assert_eq!(census(rendered), [], "a file written for each entry");
|
|
let bound = "#[test]\nfn t() {\n for (_, kind) in KINDS {\n let params = json!({\"k\": kind});\n assert!(validate_params(SCHEMA, ¶ms).is_ok());\n }\n}\n";
|
|
assert_eq!(census(bound), [], "a value bound from the entry, checked against a schema");
|
|
let lookup = "#[test]\nfn t() {\n let names = names();\n for c in COMMANDS {\n assert!(names.contains(c));\n }\n}\n";
|
|
assert_eq!(census(lookup), [(2, "census")], "a lookup in other state is still a census");
|
|
let alone = "#[test]\nfn t() {\n for c in COMMANDS {\n let m = menu(c);\n assert!(m.is_some());\n }\n}\n";
|
|
assert_eq!(census(alone), [(2, "census")], "a call on the entry alone is a lookup");
|
|
let constant =
|
|
"#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c, 2, \"x\", r\"y\", b'z', br#\"w\"#).is_some());\n }\n}\n";
|
|
assert_eq!(census(constant), [(2, "census")], "literal arguments are not other inputs");
|
|
let message = "#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c).is_some(), \"{}\", app.describe(c));\n }\n}\n";
|
|
assert_eq!(census(message), [(2, "census")], "a call in a failure message runs only after a failure");
|
|
let closure = "#[test]\nfn t() {\n let tree = tree();\n for p in PLACES {\n let m = tree.iter().find(|t| t == p).map(|(_, items)| items.len());\n assert!(m.is_some());\n }\n}\n";
|
|
assert_eq!(census(closure), [(2, "census")], "a closure passed along a lookup is not another input");
|
|
let registry = "#[test]\nfn t() {\n let registry = registry();\n for k in Kind::ALL {\n assert_eq!(registry.lookup(k.id()), Some(k));\n }\n}\n";
|
|
assert_eq!(census(registry), [(2, "census")], "a lookup on a table receiver is still a round trip");
|
|
let parsed = "#[test]\nfn t(text: &str) {\n for u in Unit::ALL {\n assert!(u.parse(text).is_some());\n }\n}\n";
|
|
assert_eq!(census(parsed), [], "parsing other input with each entry computes a result");
|
|
let skipped = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!(menu(c).is_some() || app.run(c).is_ok());\n }\n}\n";
|
|
assert_eq!(census(skipped), [(2, "census")], "a call after || may never run");
|
|
let joined = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!(menu(c).is_some() && app.run(c).is_ok());\n }\n}\n";
|
|
assert_eq!(census(joined), [], "a call after && runs whenever the assertion passes");
|
|
let grouped = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!((menu(c).is_some() || other(c).is_some()) && app.run(c).is_ok());\n }\n}\n";
|
|
assert_eq!(census(grouped), [], "an || inside an earlier group does not skip the call");
|
|
let deferred = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let mut run = || app.run(c);\n assert!(run().is_ok());\n }\n}\n";
|
|
assert_eq!(census(deferred), [], "a zero-argument closure feeds the entry into a computation");
|
|
let moved = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let mut run = move || app.run(c);\n assert!(run().is_ok());\n }\n}\n";
|
|
assert_eq!(census(moved), [], "a move closure feeds the entry into a computation");
|
|
let deferred_async = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let run = async || app.run(c);\n assert!(block_on(run()).is_ok());\n }\n}\n";
|
|
assert_eq!(census(deferred_async), [], "an async closure feeds the entry into a computation");
|
|
let sibling = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let result = (flag || other, app.run(c));\n assert!(result.1.is_ok());\n }\n}\n";
|
|
assert_eq!(census(sibling), [], "an || in a sibling tuple element does not skip the call");
|
|
}
|
|
|
|
#[test]
|
|
fn census_keeps_diagnostics_for_fixed_range_arguments() {
|
|
for range in ["1..4", "1..=4", "-4..-1", "1..(2 + 2)"] {
|
|
let src =
|
|
format!("#[test]\nfn t() {{\n for k in Kind::ALL {{\n assert_eq!(Kind::from_id(k.id(), {range}), Some(k));\n }}\n}}\n");
|
|
assert_eq!(only("census", &src), [(2, "census")], "{range}");
|
|
}
|
|
for range in ["1..limit", "1..=limit", "start..4", "1..(limit + 2)"] {
|
|
let src =
|
|
format!("#[test]\nfn t() {{\n for k in Kind::ALL {{\n assert_eq!(Kind::from_id(k.id(), {range}), Some(k));\n }}\n}}\n");
|
|
assert_eq!(only("census", &src), [], "{range}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn numeric_literals_are_one_token() {
|
|
for s in ["1", "0x1F", "2.5f32", "1_000", "1e-3", "7usize"] {
|
|
assert!(numeric_literal(s), "{s}");
|
|
}
|
|
for s in ["1+offset", "1..limit", "1usize-offset", "1<<4"] {
|
|
assert!(!numeric_literal(s), "{s}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_suffix_check_reads_source_only_when_the_checked_file_is_read() {
|
|
let name = "#[test]\nfn t() {\n assert!(generated_name().ends_with(\".rs\"));\n}\n";
|
|
assert_eq!(only("reads-source", name), [], "a suffix check on a generated name");
|
|
let names = "#[test]\nfn t() {\n assert!(generated_names().iter().all(|name| name.ends_with(\".rs\")));\n}\n";
|
|
assert_eq!(only("reads-source", names), [], "a suffix predicate over generated names");
|
|
let other_read = "#[test]\nfn t() {\n assert!(generated_name().ends_with(\".rs\"));\n}\n#[test]\nfn u() {\n assert!(fs::read_to_string(\"data.json\").unwrap().contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", other_read), [], "another test reads a file the suffix check did not name");
|
|
let same_name = "#[test]\nfn t() {\n let p = generated_name();\n assert!(p.ends_with(\".rs\"));\n}\n#[test]\nfn u() {\n let p = data_path();\n assert!(fs::read_to_string(p).unwrap().contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", same_name), [], "another test reads its own local of the same name");
|
|
let read = "#[test]\nfn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert!(fs::read_to_string(p).unwrap().contains(\"x\"));\n}\n";
|
|
assert_eq!(only("reads-source", read), [(4, "reads-source")], "the test reads the file");
|
|
let src = "#[test]\nfn t() {\n let path = newest();\n if path.to_string_lossy().ends_with(\".rs\") {\n assert!(fs::read_to_string(&path).unwrap().contains(\"x\"));\n }\n}\n";
|
|
assert_eq!(only("reads-source", src), [(4, "reads-source")], "the converted path is read");
|
|
let src = "#[test]\nfn t() {\n let path = newest();\n assert!(path.to_string_lossy().ends_with(\".rs\"));\n}\n";
|
|
assert_eq!(only("reads-source", src), [], "the converted path is not read");
|
|
let src = "#[test]\nfn t() {\n assert!(generated_name().to_string_lossy().ends_with(\".rs\"));\n}\n";
|
|
assert_eq!(only("reads-source", src), [], "a conversion of a generated name");
|
|
let src = "#[test]\nfn t() {\n assert!(generated_name().to_string_lossy().ends_with(\".rs\"));\n assert_eq!(fs::read_to_string(other_path()).unwrap(), \"x\");\n}\n";
|
|
assert_eq!(only("reads-source", src), [(3, "reads-source")], "the same function reads a file, regardless of the receiver");
|
|
let src = "#[test]\nfn t() {\n let entry = newest();\n if entry.path.to_string_lossy().ends_with(\".rs\") {\n assert!(fs::read_to_string(&entry.path).unwrap().contains(\"x\"));\n }\n}\n";
|
|
assert_eq!(only("reads-source", src), [(4, "reads-source")], "the test reads the checked field");
|
|
let src = "#[test]\nfn t() {\n assert!(entry.path.to_string_lossy().ends_with(\".rs\"));\n assert_eq!(load(&entry.path), \"x\");\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n";
|
|
assert_eq!(only("reads-source", src), [(3, "reads-source")], "a separate helper reads the checked field");
|
|
let src = "fn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n#[cfg(test)]\nmod tests {\n #[test]\n fn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert_eq!(load(&p), \"x\");\n }\n}\n";
|
|
assert_eq!(only("reads-source", src), [(9, "reads-source")], "a helper outside the test module reads the checked file");
|
|
let found: Vec<_> = hits_in("crates/x/src/lib.rs", src, &ctx()).into_iter().filter(|h| h.1 == "reads-source").collect();
|
|
assert_eq!(found, [(9, "reads-source")], "the reading helper is outside the test regions of a regular source file");
|
|
let src = "#[test]\nfn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert_eq!(load::<String>(&p), \"x\");\n}\n#[cfg(test)]\nfn load<T>(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n";
|
|
assert_eq!(only("reads-source", src), [(4, "reads-source")], "a generic helper reads the checked file");
|
|
let src = "#[test]\nfn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert_eq!(std::fs::read::<_>(&p).unwrap().len(), 1);\n}\n";
|
|
assert_eq!(only("reads-source", src), [(4, "reads-source")], "a read with a turbofish");
|
|
let src = "#[test]\nfn t() {\n assert!(entry.path.to_string_lossy().ends_with(\".rs\"));\n assert_eq!(load(&other.path), \"x\");\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n";
|
|
assert_eq!(only("reads-source", src), [(3, "reads-source")], "the helper reads a file, regardless of its argument");
|
|
let derived_helper = "#[test]\nfn t() {\n let path = newest();\n let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();\n assert!(name.ends_with(\".rs\"));\n assert_eq!(load(&path), \"x\");\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n";
|
|
assert_eq!(only("reads-source", derived_helper), [(5, "reads-source")], "the test calls a reading helper after checking a derived name");
|
|
let other_call = "#[test]\nfn t() {\n assert!(path.ends_with(\".rs\"));\n}\n#[test]\nfn u() {\n assert_eq!(load(&path), \"x\");\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n";
|
|
assert_eq!(only("reads-source", other_call), [], "only another test calls the reading helper");
|
|
let declared = "#[test]\nfn t() {\n fn read() -> u8 {\n 1\n }\n assert!(generated_name().ends_with(\".rs\"));\n}\n";
|
|
assert_eq!(only("reads-source", declared), [], "a function named read is declared, not called");
|
|
let helper = "#[cfg(test)]\nmod tests {\n fn load(p: &Path) -> String {\n if p.ends_with(\".rs\") {\n return fs::read_to_string(p).unwrap();\n }\n String::new()\n }\n #[test]\n fn t() {\n assert_eq!(load(newest()), \"x\");\n }\n}\n";
|
|
assert_eq!(only("reads-source", helper), [(4, "reads-source")], "a helper in the test module reads the file");
|
|
let split = "#[test]\nfn t() {\n for p in listing() {\n if !p.ends_with(\".rs\") {\n continue;\n }\n assert_eq!(load(&p), \"x\");\n }\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n";
|
|
assert_eq!(only("reads-source", split), [(4, "reads-source")], "a separate test helper reads the file");
|
|
let walk = "#[test]\nfn t() {\n for entry in std::fs::read_dir(&d).unwrap() {\n let path = entry.unwrap().path();\n let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();\n if !name.ends_with(\".rs\") {\n continue;\n }\n assert!(check(&path));\n }\n}\n";
|
|
assert_eq!(only("reads-source", walk), [(6, "reads-source")], "a suffix check in a loop over a directory listing");
|
|
let derived = "#[test]\nfn t() {\n let path = newest();\n let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();\n if name.ends_with(\".rs\") {\n assert!(std::fs::read_to_string(&path).unwrap().contains(\"x\"));\n }\n}\n";
|
|
assert_eq!(only("reads-source", derived), [(5, "reads-source")], "the checked name comes from the path that is read");
|
|
let generated =
|
|
"#[test]\nfn t() {\n for n in 0..3 {\n let name = generated_name(n);\n assert!(name.ends_with(\".rs\"));\n }\n}\n";
|
|
assert_eq!(only("reads-source", generated), [], "a loop over generated names lists no files");
|
|
let nested = "#[test]\nfn t() {\n let n = files.iter().filter(|p| p.to_str().is_some_and(|s| s.ends_with(\".rs\"))).count();\n assert_eq!(n, 4);\n}\n";
|
|
assert_eq!(only("reads-source", nested), [(3, "reads-source")], "a suffix check nested inside the closure of a listing filter");
|
|
}
|
|
|
|
#[test]
|
|
fn suffix_selected_source_reads_include_streams() {
|
|
for read in ["File::open(p)", "File :: open(p)", "reader.read_to_end(&mut bytes)", "reader.read_to_string(&mut text)", "fs::read(p)"] {
|
|
let src = format!(
|
|
"#[test]\nfn t() {{\n let p = newest();\n if p.ends_with(\".rs\") {{\n let got = {read};\n assert_eq!(check(got), 1);\n }}\n}}\n"
|
|
);
|
|
assert_eq!(only("reads-source", &src), [(4, "reads-source")], "{read}");
|
|
assert_eq!(only("reads-source", &src.replace(".rs", ".svg")), [], "{read}");
|
|
}
|
|
let name = "#[test]\nfn t() {\n let p = newest();\n assert_eq!(p.ends_with(\".rs\"), wanted());\n}\n";
|
|
assert_eq!(only("reads-source", name), [], "the suffix check's result is compared, and nothing is read");
|
|
}
|
|
|
|
#[test]
|
|
fn a_file_whose_last_route_was_removed_is_lost() {
|
|
let child = "crates/x/src/a/child.rs";
|
|
let paths = [child.to_owned()];
|
|
let base = [("crates/x/src/lib.rs", "mod a;\n"), ("crates/x/src/a.rs", "mod child;\n")];
|
|
let read_base = |p: &str| base.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned());
|
|
for (lib, lost) in [("", true), ("mod a;\n", false), ("#[path = \"a/child.rs\"]\nmod again;\n", false)] {
|
|
let head = [("crates/x/src/lib.rs", lib), ("crates/x/src/a.rs", "mod child;\n")];
|
|
let read = |p: &str| head.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned());
|
|
let found = lost_routes(&paths, &read, &path_overrides(head), &read_base, &Overrides::new());
|
|
assert_eq!(found.contains_key(child), lost, "{lib:?}");
|
|
if lost {
|
|
assert!(found[child].iter().any(|p| p == "crates/x/src/lib.rs"), "the removed declaration's file is a base route");
|
|
}
|
|
}
|
|
let common = "crates/x/tests/common/mod.rs".to_owned();
|
|
let smoke = [("crates/x/tests/smoke.rs", "mod common;\n")];
|
|
let read_smoke = |p: &str| smoke.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned());
|
|
let smoke_routes = with_root_routes(path_overrides(smoke), &[smoke[0].0.to_owned(), common.clone()]);
|
|
let deleted = lost_routes(
|
|
std::slice::from_ref(&common),
|
|
&|_| None,
|
|
&with_root_routes(Overrides::new(), std::slice::from_ref(&common)),
|
|
&read_smoke,
|
|
&smoke_routes,
|
|
);
|
|
assert_eq!(deleted.get(&common).map(Vec::as_slice), Some(&[smoke[0].0.to_owned()][..]), "the deleted target root was its only route");
|
|
let kept = lost_routes(std::slice::from_ref(&common), &read_smoke, &smoke_routes, &read_smoke, &smoke_routes);
|
|
assert!(kept.is_empty(), "the target root still loads it");
|
|
let never_loaded = [("crates/x/src/lib.rs", ""), ("crates/x/src/a.rs", "mod child;\n")];
|
|
let read = |p: &str| never_loaded.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned());
|
|
assert!(lost_routes(&paths, &read, &Overrides::new(), &read, &Overrides::new()).is_empty(), "a file no target loaded at the base either");
|
|
let ctx = Ctx { module_cfgs: [(child.to_owned(), vec!["any()".to_owned()])].into_iter().collect(), ..ctx() };
|
|
assert_eq!(hits_in(child, "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n", &ctx), [(2, "never-run")]);
|
|
}
|
|
}
|