diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 1c9af7db00..9ad742749e 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -35,8 +35,9 @@ commands: cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) test-lint [--base ] [--all] weak tests in the lines changed since the base: fail on self-compares, reasonless - #[ignore] and sleeps; list only is_ok/is_some checks, unguarded .all(), no assertion, - early returns, unset env gates... (xtask/src/test_lint.rs); --all lists every hit + #[ignore], sleeps, reads of Rust source and tests no CI target runs; list only + is_ok/is_some checks, unguarded .all(), no assertion, early returns, unset env + gates, constant echoes, exact pixels... (xtask/src/test_lint.rs); --all lists every hit by crate and never fails i18n-report list the strings each language's catalog lacks, shown in English (fails only on a broken scan; ci runs it too) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 2a839af6be..10eaf15294 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -37,14 +37,27 @@ //! string literals, `echo` or `printf` output that is not written to `$GITHUB_ENV`, and variable //! reads do not; //! * `sleep`: `thread::sleep` in test code, or a bare `sleep(…)` in a file that imports it; -//! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, or a walk -//! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`]; +//! * `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 walk that keeps files ending in `.rs`), +//! 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. +//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table; +//! * `mirror`: `assert_eq!(f(a), f(b) …)`, 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; +//! * `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); +//! * `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, …))]`, @@ -58,8 +71,9 @@ //! rules about a whole test it can be on any line from the line above the test attribute to the //! `fn` line. An allow without a reason exempts nothing. //! -//! `cargo xtask test-lint` fails on hits of `self-compare`, `ignore-without-reason` and `sleep` in -//! the lines and tests changed since a base, and lists the other rules' hits there without failing. The base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's +//! `cargo xtask test-lint` fails on hits of `self-compare`, `ignore-without-reason`, `sleep`, +//! `reads-source` and `never-run` in the lines and tests changed since a base, and lists the other +//! rules' hits there without failing. The base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's //! merge commit is checked out, and a shallow checkout fetches that parent); elsewhere the merge //! base of `HEAD` and `upstream/main` or `origin/main`. Uncommitted and untracked files count as //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the @@ -127,10 +141,15 @@ pub enum Rule { Sleep, ReadsSource, Census, + Mirror, + ConstantEcho, + FixtureOnly, + NeverRun, + ExactPixel, } impl Rule { - pub const ALL: [Rule; 11] = [ + pub const ALL: [Rule; 16] = [ Rule::AllUnguarded, Rule::OnlyWeak, Rule::SelfCompare, @@ -142,6 +161,11 @@ impl Rule { Rule::Sleep, Rule::ReadsSource, Rule::Census, + Rule::Mirror, + Rule::ConstantEcho, + Rule::FixtureOnly, + Rule::NeverRun, + Rule::ExactPixel, ]; pub fn id(self) -> &'static str { @@ -157,6 +181,11 @@ impl Rule { 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", } } @@ -173,12 +202,19 @@ impl Rule { 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) + matches!(self, Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep | Rule::ReadsSource | Rule::NeverRun) } fn from_id(id: &str) -> Option { @@ -213,10 +249,19 @@ impl Hit { } } -/// What the rules need beyond the file: asserting helper names by crate and the variables CI sets. +/// 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>, pub ci_env: HashSet, + pub module_cfgs: HashMap>, +} + +/// A source file read from the work tree, or `None` when it is missing or larger than [`MAX_FILE`]. +fn read_small(root: &Path, path: &str) -> Option { + let full = root.join(path); + (std::fs::metadata(&full).ok()?.len() <= MAX_FILE).then(|| std::fs::read_to_string(full).ok()).flatten() } pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { @@ -226,7 +271,8 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); if opts.all { let sources = read_all(root, &files)?; - let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env }; + let module_cfgs = module_cfgs(&files, &|p| read_small(root, p)); + let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs }; let hits: Vec = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); print!("{}", report(&hits, sources.len())); return Ok(()); @@ -236,8 +282,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let changed: BTreeMap>> = changed.into_iter().filter(|(p, _)| is_scanned(p)).collect(); let crates: BTreeSet = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); let helper_files: Vec = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); - let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env }; let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); + let module_cfgs = module_cfgs(&present, &|p| read_small(root, p)); + let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { for hit in lint_file(&path, &src, &ctx) { @@ -1241,7 +1288,9 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { hits.extend(early_returns(&v)); hits.extend(env_gates(&v, ctx)); hits.extend(census(&v, helpers)); - hits.extend([only_weak(&v), exit_status_only(&v), no_assertion(&v)].into_iter().flatten()); + 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 } @@ -2816,7 +2865,12 @@ fn reads_source_hits(file: &File) -> Vec { } let m = &file.m; let mut out = vec![]; - for (word, note) in [(&b"include_str"[..], "includes a .rs file as text"), (&b"ends_with"[..], "keeps files ending in .rs")] { + 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 }; @@ -2824,7 +2878,12 @@ fn reads_source_hits(file: &File) -> Vec { // An ordinary or raw string literal: `".rs"`, `r".rs"`, `r#"…/lib.rs"#`. let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); let literal = raw.unwrap_or(&arg); - let rs = if word == b"ends_with" { literal == "\".rs\"" } else { arg.trim_end_matches('#').ends_with(".rs\"") }; + let rs = match word { + b"ends_with" => literal == "\".rs\"", + // A path literal anywhere in the argument: `root.join("src/lib.rs")`, `concat!(…, "/x.rs")`. + b"read_to_string" => false, + _ => arg.trim_end_matches('#').ends_with(".rs\""), + }; if rs { out.push(file.hit(at, Rule::ReadsSource, file.test_at(at), note.into())); } @@ -2833,12 +2892,450 @@ fn reads_source_hits(file: &File) -> Vec { out } +// ---- 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, + } + } +} + +/// `assert_eq!(f(a), f(b))`: both sides start by calling the same function, so a fault in `f` can +/// move both sides together. Identical sides are `self-compare`'s. +fn mirrors(v: &View) -> Vec { + v.asserts + .iter() + .filter(|a| a.name.ends_with("_eq")) + .filter_map(|a| { + let (l, r) = (norm(&v.file.m[a.args.first()?.0..a.args.first()?.1]), norm(&v.file.m[a.args.get(1)?.0..a.args.get(1)?.1])); + let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); + let name = head_call(l)?; + // The expected side derives its value from a second call with arithmetic; two calls + // compared as they are check that two inputs agree, which is a real check. + let derived = ["+", "-", "*", "/"].iter().any(|op| !top_level_at(r, op).is_empty()); + let last = name.rsplit("::").next().unwrap_or(name); + (l != r && derived && head_call(r) == Some(name) && !MIRROR_NEUTRAL.contains(&last)) + .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) -> Option { + 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 = …;` 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> { + 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 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 }); + } else if !plain { + // A pattern that binds the name (`let (a, b) = …`, `let Foo { a, .. } = …`). + let pattern = norm(&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); + } + } + } + found +} + +/// 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 { + let local = |name: &str| -> Option { + 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 { + 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" }; + +fn windows_runs(path: &str) -> bool { + path.starts_with("apps/vectorcraft/") || path == "crates/ui-egui/src/tests/printps.rs" +} + +/// 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 { + 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 top_level_at(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(')')) { + return cfg_value(arg, t).map(|v| !v); + } + // An ordinary or raw string value: `"linux"`, `r"linux"`, `r#"linux"#`. + let (key, value) = p.split_once('=').map_or((p, ""), |(k, v)| (k, v.strip_prefix('r').unwrap_or(v).trim_matches('#').trim_matches('"'))); + 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, + } +} + +/// The predicates of the `#[cfg(…)]` and `#![cfg(…)]` attributes whose item holds `pos`. +fn cfgs_over(file: &File, pos: usize) -> Vec { + let m = &file.m; + let mut out = vec![]; + for at in words(m, b"cfg", 0, m.len()) { + 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 + "cfg".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 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 { + let after = end + 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, + } + }; + if span.0 <= pos && pos <= span.1 { + // The source text: masking blanks the string literals `target_os = "macos"` needs. + out.push(file.src_norm((open + 1, close))); + } + } + out +} + +/// The module name a file declares and the files that may declare it with `mod ;`, or `None` +/// for a crate root (`lib.rs`, `main.rs`, `build.rs`, a file directly in `tests`, `benches` or +/// `examples`). +fn module_parent(path: &str) -> Option<(&str, Vec)> { + let (dir, file) = path.rsplit_once('/')?; + let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| dir.ends_with(d)); + if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_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 = ["mod.rs", "lib.rs", "main.rs"].iter().map(|f| format!("{parent}/{f}")).collect(); + candidates.push(format!("{parent}.rs")); + Some((name, candidates)) +} + +/// The predicates of the `#[cfg(…)]` attributes on a `mod ;` declaration in `src`, or `None` +/// when `src` declares no such module. +fn declared_cfgs(src: &str, name: &str) -> Option> { + let m = mask(src); + let decl = words(&m, b"mod", 0, m.len()).into_iter().find(|&at| { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + &m[start..end] == name.as_bytes() && m.get(skip_ws(&m, end)) == Some(&b';') + })?; + let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let mut out = vec![]; + for at in words(&m, b"cfg", item, decl) { + let open = skip_ws(&m, at + 3); + let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + if let Some(close) = (attr && m.get(open) == Some(&b'(')).then(|| matching(&m, open)).flatten() { + out.push(norm(&src.as_bytes()[open + 1..close])); + } + } + Some(out) +} + +/// 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) -> HashMap> { + let mut out = HashMap::new(); + for path in paths { + let (mut preds, mut at) = (vec![], path.clone()); + for _ in 0..16 { + let Some((name, candidates)) = module_parent(&at) else { break }; + let Some((parent, found)) = candidates.into_iter().find_map(|c| read(&c).and_then(|s| declared_cfgs(&s, name)).map(|f| (c, f))) else { + break; + }; + preds.extend(found); + at = parent; + } + if !preds.is_empty() { + out.insert(path.clone(), preds); + } + } + out +} + +/// A test that a `cfg` compiles out on every target CI runs tests on. +fn never_run(v: &View, ctx: &Ctx) -> Option { + let mut preds = cfgs_over(v.file, v.t.fn_at); + preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); + if preds.is_empty() { + return None; + } + let windows = windows_runs(v.file.path).then_some(&WINDOWS_TARGET); + 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 = preds.iter().filter(|p| p.as_str() != "test").map(|p| format!("cfg({p})")).collect(); + return Some(v.whole(Rule::NeverRun, format!("{} leaves it out of every target CI tests on", shown.join(", ")))); + } + 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", "doc", ".x0", ".y0", ".x1", ".y1", "obox"].iter().any(|w| op.contains(w)) { + 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); + } + let rest = &op[after..]; + if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.starts_with(p)) { + 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 { + 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 { helpers: HashMap::new(), ci_env: ["SET_IN_CI".to_owned()].into_iter().collect() } + Ctx { ci_env: ["SET_IN_CI".to_owned()].into_iter().collect(), ..Ctx::default() } } /// The rule ids of `src`'s hits, as `(line, rule)`. @@ -3807,12 +4304,12 @@ mod tests { let src = "fn same(a: u8, b: u8) {\n assert_eq!(a, b);\n}\nfn twice(a: u8) {\n same(a, a);\n}\n#[test]\nfn t() {\n twice(f());\n}\n#[test]\n#[should_panic]\nfn p() {\n f();\n}\n#[test]\nfn q() {\n check_round_trip(f());\n}\n"; let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); assert!(helpers["crates/x"].contains("twice"), "{helpers:?}"); - let ctx = Ctx { helpers, ci_env: HashSet::new() }; + 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 { helpers: HashMap::new(), ci_env: HashSet::new() }), [(8, "no-assertion")]); + assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx::default()), [(8, "no-assertion")]); } #[test] @@ -3834,7 +4331,7 @@ mod tests { assert!(helpers["crates/x"].contains("same")); assert!(helpers["crates/x"].contains("twice")); assert!(!helpers["crates/x"].contains("idle")); - let ctx = Ctx { helpers, ci_env: HashSet::new() }; + let ctx = Ctx { helpers, ..Ctx::default() }; for call in ["same::(a, b)", "twice::>>(x)"] { let src = format!("#[test]\nfn t() {{\n {call};\n}}\n"); assert_eq!(hits_in("crates/x/tests/it.rs", &src, &ctx), [], "{call}"); @@ -4062,7 +4559,9 @@ mod tests { #[test] fn only_failing_rules_fail_the_check() { let failing: Vec<&str> = Rule::ALL.into_iter().filter(|r| r.fails()).map(Rule::id).collect(); - assert_eq!(failing, ["self-compare", "ignore-without-reason", "sleep"]); + assert_eq!(failing, ["self-compare", "ignore-without-reason", "sleep", "reads-source", "never-run"]); + let mac = "#[cfg(target_os = \"macos\")]\n#[test]\nfn mac() {\n assert_eq!(f(), 1);\n}\n"; + assert!(finish(&lint_file("crates/x/src/tests.rs", mac, &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"; @@ -4128,11 +4627,11 @@ mod tests { fn workflow_mentions_do_not_suppress_unset_gates() { let src = "#[test]\nfn t() {\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; for workflow in ["if: env.MY_SAMPLES != ''", "run: echo $MY_SAMPLES", "# MY_SAMPLES=value"] { - let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + 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 { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + let ctx = Ctx { ci_env: upper_words(workflow).collect(), ..Ctx::default() }; assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [], "{workflow}"); } } @@ -4174,10 +4673,10 @@ mod tests { let src = "mod a {\n pub fn exercise() { assert_eq!(f(), 1); }\n}\nmod b {\n pub fn exercise() { f(); }\n}\n#[test]\nfn t() {\n b::exercise();\n}\n"; let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); assert!(!helpers["crates/x"].contains("exercise"), "{helpers:?}"); - assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers, ci_env: HashSet::new() }), [(8, "no-assertion")]); + 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, ci_env: HashSet::new() }), []); + assert_eq!(hits_in("crates/x/tests/it.rs", &both, &Ctx { helpers, ..Ctx::default() }), []); } #[test] @@ -4246,7 +4745,7 @@ mod tests { fn single_letter_variables_set_in_ci_count() { let src = "#[test]\nfn t() {\n let dir = std::env::var(\"X\");\n assert_eq!(f(dir), 3);\n}\n"; assert_eq!(hits(src), [(3, "env-gate-unset")]); - let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words("env:\n X: 1\n").collect() }; + 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), []); } @@ -4310,4 +4809,131 @@ mod tests { assert_eq!(found.iter().map(|h| (h.rule, h.line, h.first, h.last)).collect::>(), [(Rule::IgnoreWithoutReason, 2, 2, 3)]); assert!(touches(&found[0], Some(&[3].into_iter().collect())), "a change to the reason alone"); } + + 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 both spellings parse to one value\n assert_eq!(parse(\"a\"), parse(\"A\"));\n}\n"; + assert_eq!(only("mirror", allowed), []); + } + + #[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 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"); + } + + #[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_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 = ["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); + 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 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!(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!((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"); + 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), []); + } }