From 25756e1b8d38fc93ef8b6c5989253b4a00fc4fd3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 04:43:33 -0800 Subject: [PATCH] xtask: test-lint fails on four rules; all-unguarded skips collections that cannot be empty Replayed over the last 300 merges of main, all-unguarded failed good pull requests on collections that cannot be empty. It now leaves out: - plain locals bound to an array type of a positive length, to a non-empty array literal or vec![...], or to a literal range followed only by methods that keep an item (map, iter, rev, collect into a known collection ...); counts may be consts of the file - locals filled by a push or insert on every pass of a loop over such a source - fields and const or static items the file declares only as arrays of a positive length - collections compared with a non-empty literal through such methods, directly or through a local built from them, and assertions on a local bound to a count or length - .windows(k) and .chunks_exact(k) when the collection has k items Later code that may remove items or replace the collection cancels the exemption. Only only-weak, self-compare, ignore-without-reason and sleep fail the check now. The other rules list their hits on changed lines without failing. On the same 300 merges, 1 would fail (an only-weak test), and the 3 all-unguarded hits are tests an empty result passes. On main at 07037afda8, all-unguarded lists 392 hits instead of 433. --- docs/development.md | 2 +- xtask/src/main.rs | 7 +- xtask/src/test_lint.rs | 1164 ++++++++++++++++++++++++++++++++++++---- 3 files changed, 1065 insertions(+), 108 deletions(-) diff --git a/docs/development.md b/docs/development.md index 26058129e7..cfd02bacc8 100644 --- a/docs/development.md +++ b/docs/development.md @@ -351,7 +351,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) fails on tests that a wrong result can pass, in the lines and tests changed since a base: `assert!(….all(…))` with no length or emptiness check, a test whose only checks are `is_ok`, `is_some` or `!is_empty`, `assert_eq!(x, x)`, a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, `#[ignore]` without a reason, an environment variable that no CI leg sets, `thread::sleep` in test code, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on a test whose only checks are `is_ok`, `is_some` or `!is_empty` (`only-weak`), `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/main.rs b/xtask/src/main.rs index f48f088aa8..addf9cb7e1 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -34,9 +34,10 @@ commands: brands check that user-visible text (labels, params docs, MCP, docs, packaging) names no other vendor's products cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) test-lint [--base ] [--all] - fail on weak tests (unguarded .all(), only is_ok/is_some checks, no assertion, early - returns, unset env gates, sleeps...) in the lines changed since the base - (xtask/src/test_lint.rs); --all lists every hit by crate and never fails + weak tests in the lines changed since the base: fail on only is_ok/is_some checks, + self-compares, reasonless #[ignore] and sleeps; list unguarded .all(), no assertion, + early returns, unset env gates... (xtask/src/test_lint.rs); --all lists every hit + by crate and never fails i18n-report list the strings each language's catalog lacks, shown in English (fails only on a broken scan; ci runs it too) ui-commands regenerate crates/mcp/src/ui_catalog.rs from desktop UI_COMMANDS; --check fails on drift diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 8664403997..60363000fd 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -9,9 +9,15 @@ //! 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. Non-empty array literals and plain local -//! names bound to them in the test, optionally through `.map(…)`, are also left out. Empty arrays -//! still count. A change anywhere in the test counts as a change to the hit; +//! 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 @@ -50,6 +56,7 @@ //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the //! workspace by crate and rule, and does not fail. +use std::cell::OnceCell; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::path::Path; use std::process::Command; @@ -156,6 +163,11 @@ impl Rule { } } + /// Whether a hit on a changed line fails the command. The other rules only report. + pub fn fails(self) -> bool { + matches!(self, Rule::OnlyWeak | Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep) + } + fn from_id(id: &str) -> Option { Rule::ALL.into_iter().find(|r| r.id() == id) } @@ -254,20 +266,33 @@ impl Options { 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") }; - if counted.is_empty() { - println!("test-lint: no hits in the changed lines of {files} Rust file(s) since {base}{older}"); + let (failing, reported): (Vec<&Hit>, Vec<&Hit>) = counted.iter().partition(|h| h.rule.fails()); + if !reported.is_empty() { + println!( + "test-lint: {} hit(s) of report-only rules in the lines changed since {base} (they do not fail the check):\n {}", + reported.len(), + listing(&reported).join("\n ") + ); + } + if failing.is_empty() { + println!("test-lint: no failing hits in the changed lines of {files} Rust file(s) since {base}{older}"); return Ok(()); } - let mut out: Vec = counted.iter().map(Hit::show).collect(); - let rules: BTreeSet = counted.iter().map(|h| h.rule).collect(); - out.extend(rules.iter().map(|r| format!("{}: {}", r.id(), r.advice()))); Err(format!( "{} test-lint hit(s) in the lines changed since {base}{older} (exempt a line with `// {ALLOW} `):\n {}", - counted.len(), - out.join("\n ") + failing.len(), + listing(&failing).join("\n ") )) } +/// Each hit, then the advice for each rule they break. +fn listing(hits: &[&Hit]) -> Vec { + let mut out: Vec = hits.iter().map(|h| h.show()).collect(); + let rules: BTreeSet = hits.iter().map(|h| h.rule).collect(); + out.extend(rules.iter().map(|r| format!("{}: {}", r.id(), r.advice()))); + out +} + /// `--all`: counts by crate and rule, then every hit. fn report(hits: &[Hit], files: usize) -> String { let mut by_crate: BTreeMap> = BTreeMap::new(); @@ -1113,21 +1138,26 @@ impl View<'_> { const PLAIN_ASSERTS: &[&str] = &["assert", "debug_assert", "prop_assert"]; +/// Calls whose result says how many items a collection has. +const SIZE_CHECKS: &[&str] = &[".len()", ".is_empty()", ".count()", ".first()", ".any(", ".next()", ".last()"]; + fn all_unguarded(v: &View) -> Vec { let mut body = v.body_without_messages(); strip_all_predicates(&mut body); + let locals = bindings(&body); let checked = v.asserts.iter().any(|a| { a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { - let arg = norm(&body[from - v.t.open..to - v.t.open]); - [".len()", ".is_empty()", ".count()", ".first()", ".any(", ".next()", ".last()"].iter().any(|g| arg.contains(g)) + 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) }) }); - if checked || first_item_guard(&body) { + 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])) + .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); @@ -1157,10 +1187,10 @@ fn strip_all_predicates(body: &mut [u8]) { } /// Whether test code accesses a first item in a way that fails on an empty collection. -fn first_item_guard(body: &[u8]) -> bool { +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, _)| !on_array_literal(&compact[..at + 3])); + 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) } @@ -1179,27 +1209,27 @@ fn panicking_first_binding(body: &[u8]) -> bool { /// 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 non-empty array literal or a local -/// name bound to or previously compared equal to one. -fn unguarded_all(cond: &str, body: &[u8]) -> bool { - all_with_polarity(cond, true, body) +/// 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]) -> bool { +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); + 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) || all_with_polarity(&cond[at + 2..], positive, body); + 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); + return all_with_polarity(expr, !positive, body, sizes); } if let Some(expr) = cond.strip_prefix('!') { - return all_with_polarity(expr, !positive, body); + return all_with_polarity(expr, !positive, body, sizes); } - positive && positive_all(cond, body) + positive && positive_all(cond, body, sizes) } /// Finds a boolean operator outside parentheses, brackets and braces. @@ -1215,13 +1245,14 @@ fn boolean_split(cond: &str) -> Option { None } -fn positive_all(cond: &str, test_body: &[u8]) -> bool { +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); - !none_match && !on_array_literal(&cond[..i]) && !on_bound_array(&cond[..i], test_body) && !on_equal_array(&cond[..i], test_body) + let (receiver, need) = receiver_need(&cond[..i], sizes); + !none_match && least_items(receiver, test_body, sizes) < need }) } @@ -1274,33 +1305,217 @@ fn whole_negation(body: &str) -> bool { !rest.is_empty() } -/// Whether an earlier equality assertion compares this plain local receiver with a non-empty literal. -fn on_equal_array(receiver: &str, body: &[u8]) -> bool { - let name = array_receiver(receiver); - if name.is_empty() || name.as_bytes()[0].is_ascii_digit() || !name.bytes().all(is_ident) { - return false; - } - macro_calls(body, 0, body.len()).iter().any(|a| { - if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) { - return false; +/// 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); } - let Some(&(lf, lt)) = a.args.first() else { return false }; - let Some(&(rf, rt)) = a.args.get(1) else { return false }; - let (left, right) = (norm(&body[lf..lt]), norm(&body[rf..rt])); - (collection_operand(&left) == name && non_empty_literal(&right)) || (collection_operand(&right) == name && non_empty_literal(&left)) + body[start..].starts_with(name) && !body.get(start + name.len()).copied().is_some_and(is_ident) }) } +/// Methods that give at least one item for each distinct item they are given, and none from none, +/// with `collect` restricted to known collection targets. +const KEEPING: &[&str] = &["map", "iter", "into_iter", "cloned", "copied", "enumerate", "rev", "collect", "to_vec", "to_owned", "clone"]; + +/// Whether a normalized type names a collection that keeps an item of a non-empty iterator. +fn known_collection(ty: &str) -> bool { + let (name, args) = ty.split_once('<').map_or((ty, None), |(name, args)| (name, args.strip_suffix('>'))); + match name { + "Vec" | "std::vec::Vec" | "String" | "std::string::String" => true, + "Box" | "std::boxed::Box" => args.is_some_and(|args| { + args.starts_with('[') && matching(args.as_bytes(), 0) == Some(args.len() - 1) && !has_top_level(&args.as_bytes()[1..args.len() - 1], b';') + }), + _ => matches!( + name.strip_prefix("std::collections::").unwrap_or(name), + "VecDeque" | "HashSet" | "BTreeSet" | "HashMap" | "BTreeMap" | "BinaryHeap" | "LinkedList" + ), + } +} + +/// `operand` (masked, whitespace-free) without trailing calls of [`KEEPING`] methods: the +/// collection a compared or bound value was built from. Only the final call may use an +/// inferred `collect` target, when the caller knows it is a collection. +fn keeping_base(operand: &str, inferred_collect: bool) -> &str { + let mut op = operand; + while op.ends_with(')') { + let b = op.as_bytes(); + let mut depth = 0usize; + let Some(open) = (0..b.len()).rev().find(|&i| { + match b[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' => depth = depth.saturating_sub(1), + _ => {} + } + depth == 0 + }) else { + break; + }; + let mut head = &op[..open]; + let mut target = None; + if head.ends_with('>') { + let Some(turbofish) = head.rfind("::<") else { break }; + target = Some(&head[turbofish + 3..head.len() - 1]); + head = &head[..turbofish]; + } + let Some((rest, method)) = head.rsplit_once('.') else { break }; + if !KEEPING.contains(&method) || (method == "collect" && !target.map_or(inferred_collect && op.len() == operand.len(), known_collection)) { + break; + } + op = rest; + } + op +} + +/// Plain locals of the test bound (`let name = …;`, latest binding) to `receiver` through +/// [`KEEPING`] methods only, so they have no more distinct items than it, when no later code may +/// shrink or replace `receiver` ([`may_shrink`]), paired with the end of each binding. +fn derived_locals(receiver: &str, body: &[u8]) -> Vec<(String, usize)> { + let name = array_receiver(receiver); + if !plain_local(name) { + return vec![]; + } + let mut latest: HashMap = HashMap::new(); + for at in words(body, b"let", 0, body.len()) { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); + } + let end = start + body[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || body[start].is_ascii_digit() { + continue; + } + let stop = statement_end(body, end); + let stmt = norm(&body[end..stop]); + let (annotation, from) = stmt.split_once('=').unwrap_or(("", "")); + let inferred_collect = annotation.strip_prefix(':').is_some_and(known_collection); + let base = keeping_base(from, inferred_collect); + let derived = base != from && collection_operand(base) == name && !may_shrink(body, name.as_bytes(), stop); + latest.insert(String::from_utf8_lossy(&body[start..end]).into_owned(), (derived, stop)); + } + latest.into_iter().filter(|&(_, (derived, _))| derived).map(|(n, (_, stop))| (n, stop)).collect() +} + +/// The length a `const` or `static` item of the file declares for a plain name +/// (`const NAME: [T; N]`), taking the smallest length across all declarations of that name, +/// or 0 when any declaration has an unknown or non-array type. +fn item_len(receiver: &str, sizes: &Sizes) -> usize { + let name = array_receiver(receiver); + if !plain_local(name) { + return 0; + } + let file = sizes.file; + let mut len = None; + for at in words(file, name.as_bytes(), 0, file.len()) { + let before = file[..at].trim_ascii_end(); + let before = before.strip_suffix(b"mut").map_or(before, |b| b.trim_ascii_end()); + let keyword = |w: &[u8]| before.ends_with(w) && !before.len().checked_sub(w.len() + 1).is_some_and(|j| is_ident(before[j])); + if !keyword(b"const") && !keyword(b"static") { + continue; + } + let colon = skip_ws(file, at + name.len()); + let ty = skip_ws(file, colon + 1); + if file.get(colon) != Some(&b':') || file.get(ty) != Some(&b'[') { + return 0; + } + let Some(close) = matching(file, ty) else { return 0 }; + let count = repeat_count(&file[ty + 1..close], sizes).unwrap_or(0); + len = Some(len.map_or(count, |n: usize| n.min(count))); + } + len.unwrap_or(0) +} + +/// The receiver without its iterator method and the items it needs for `.all(…)` to see one: +/// `.windows(k)` and `.chunks_exact(k)` need `k`, anything else one. An unknown `k` needs more +/// than any collection has. +fn receiver_need<'a>(receiver: &'a str, sizes: &Sizes) -> (&'a str, usize) { + let r = array_receiver(receiver); + for (method, exact) in [(".windows(", true), (".chunks_exact(", true), (".chunks(", false)] { + let Some(at) = r.rfind(method) else { continue }; + let open = at + method.len() - 1; + if matching(r.as_bytes(), open) != Some(r.len() - 1) { + continue; + } + let need = match sizes.count(&r[open + 1..r.len() - 1]) { + Some(k) if k > 0 => { + if exact { + k + } else { + 1 + } + } + _ => usize::MAX, + }; + return (array_receiver(&r[..at]), need); + } + (r, 1) +} + +/// The length of the non-empty literal an earlier equality assertion compares this plain local +/// receiver with, or 0. For a derived local, its binding must reach the assertion unchanged. +fn equal_len(receiver: &str, body: &[u8], sizes: &Sizes, binding: Option) -> usize { + let name = array_receiver(receiver); + if !plain_local(name) { + return 0; + } + let lens = macro_calls(body, 0, body.len()).into_iter().filter_map(|a| { + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) { + return None; + } + let &(lf, lt) = a.args.first()?; + let &(rf, rt) = a.args.get(1)?; + if binding.is_some_and(|from| lf < from || may_change(&body[..lf], name.as_bytes(), from, false)) { + return None; + } + let end = a.args.last().map_or(rt, |&(_, to)| to); + if may_shrink(body, name.as_bytes(), end) { + return None; + } + let (left, right) = (norm(&body[lf..lt]), norm(&body[rf..rt])); + if collection_operand(keeping_base(&left, true)) == name { + Some(literal_len(&right, sizes)) + } else if collection_operand(keeping_base(&right, true)) == name { + Some(literal_len(&left, sizes)) + } else { + None + } + }); + lens.max().unwrap_or(0) +} + +/// Whether `name` is a plain local name: an identifier that does not start with a digit. +fn plain_local(name: &str) -> bool { + !name.is_empty() && !name.as_bytes()[0].is_ascii_digit() && name.bytes().all(is_ident) +} + /// Removes one borrow and a slice view from a compared operand. fn collection_operand(operand: &str) -> &str { let operand = operand.strip_prefix('&').unwrap_or(operand); operand.strip_suffix(".as_slice()").or_else(|| operand.strip_suffix("[..]")).unwrap_or(operand) } -/// Whether the whole operand is a non-empty array literal or `vec![…]`. -fn non_empty_literal(operand: &str) -> bool { +/// 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(); - b.first() == Some(&b'[') && matching(b, 0) == Some(b.len() - 1) && non_empty_array(&b[1..b.len() - 1]) + 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. @@ -1318,13 +1533,13 @@ fn arg_end(rest: &str) -> usize { .unwrap_or(rest.len()) } -/// Whether `receiver` (the text before `.all(`) ends with a non-empty array literal, through `.iter()` or -/// `.into_iter()`. -fn on_array_literal(receiver: &str) -> bool { +/// The length of the array literal `receiver` (the text before `.all(`) ends with, through +/// `.iter()` or `.into_iter()`, or `None` when it does not end with one. +fn array_literal_len(receiver: &str, sizes: &Sizes) -> Option { let r = array_receiver(receiver); let b = r.as_bytes(); if b.last() != Some(&b']') { - return false; + return None; } let mut depth = 0usize; for (j, &c) in b.iter().enumerate().rev() { @@ -1334,13 +1549,13 @@ fn on_array_literal(receiver: &str) -> bool { 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 && non_empty_array(&b[j + 1..b.len() - 1]); + return literal.then(|| array_len(&b[j + 1..b.len() - 1], sizes)); } } _ => {} } } - false + None } /// Removes the iterator method from an array receiver. @@ -1348,68 +1563,455 @@ fn array_receiver(receiver: &str) -> &str { receiver.strip_suffix(".iter()").or_else(|| receiver.strip_suffix(".into_iter()")).unwrap_or(receiver) } -/// Whether a plain local receiver's latest preceding binding initializes a non-empty array. -fn on_bound_array(receiver: &str, body: &[u8]) -> bool { - let name = array_receiver(receiver).as_bytes(); - if name.is_empty() || name[0].is_ascii_digit() || !name.iter().copied().all(is_ident) { - return false; +/// The fewest items a plain local receiver has after its latest preceding binding: 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; } - words(body, b"let", 0, body.len()).into_iter().rev().find_map(|at| array_binding(&body[at + 3..], name)).unwrap_or(false) + let name = name.as_bytes(); + let Some((len, end)) = words(body, b"let", 0, body.len()).into_iter().rev().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)) } -/// Checks a named binding, allowing `mut` and an array type annotation. -fn array_binding(mut rest: &[u8], name: &[u8]) -> Option { - rest = rest.trim_ascii_start(); - if rest.starts_with(b"mut") && rest.get(3).is_some_and(u8::is_ascii_whitespace) { - rest = rest[3..].trim_ascii_start(); +/// 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 = rest.iter().copied().take_while(|&c| is_ident(c)).count(); - if &rest[..end] != name { + let end = at + body[at..].iter().copied().take_while(|&c| is_ident(c)).count(); + if &body[at..end] != name { return None; } - rest = rest[end..].trim_ascii_start(); - if let Some(annotation) = rest.strip_prefix(b":") { - let annotation = annotation.trim_ascii_start(); - let close = (annotation.first() == Some(&b'[')).then(|| matching(annotation, 0)).flatten(); - let Some(close) = close else { return Some(false) }; - rest = annotation[close + 1..].trim_ascii_start(); + 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(rest.strip_prefix(b"=").is_some_and(array_initializer)) + Some((init.map_or(0, |init| expr_len(&norm(init), sizes, annotation.strip_prefix(':').unwrap_or(""))), stop)) } -/// Whether an initializer is a non-empty array literal, optionally followed by one `.map(…)`. -fn array_initializer(rest: &[u8]) -> bool { - let rest = rest.trim_ascii_start(); - let Some(close) = (rest.first() == Some(&b'[')).then(|| matching(rest, 0)).flatten() else { return false }; - if !non_empty_array(&rest[1..close]) { - return false; - } - let tail = rest[close + 1..].trim_ascii_start(); - if tail.starts_with(b";") { - return true; - } - let compact = norm(tail); - if !compact.starts_with(".map(") { - return false; - } - let Some(close) = matching(compact.as_bytes(), 4) else { return false }; - compact[close + 1..].starts_with(';') -} - -/// Whether an array's masked contents have an element and, for repetition, a positive literal count. -fn non_empty_array(contents: &[u8]) -> bool { - let mut at = 0; - while at < contents.len() { - match contents[at] { - b';' => return norm(&contents[at + 1..]).parse::().is_ok_and(|count| count > 0), - b'(' | b'[' | b'{' => { - let Some(close) = matching(contents, at) else { return false }; - at = close + 1; - } +/// 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, } } - !contents.trim_ascii().is_empty() + body.len() +} + +/// The fewest items a (masked, whitespace-free) expression yields: an array literal or `vec![…]`, +/// a literal range, either followed only by methods that keep at least one item of a non-empty +/// input (`map`, `iter`, `into_iter`, `cloned`, `copied`, `enumerate`, `rev`, `chain`, `to_vec`, +/// `to_owned`, `clone`, and `collect` into a known collection or `step_by`, after which at least +/// one is known). Only a final `collect` without a turbofish can use the binding's type. 0 for +/// anything else. +fn expr_len(e: &str, sizes: &Sizes, binding_type: &str) -> usize { + let e = e.strip_prefix("vec!").unwrap_or(e); + let b = e.as_bytes(); + let (mut n, mut rest) = match b.first() { + Some(b'[') => { + let Some(close) = matching(b, 0) else { return 0 }; + (array_len(&b[1..close], sizes), &e[close + 1..]) + } + Some(b'(') => { + let Some(close) = matching(b, 0) else { return 0 }; + (range_len(&e[1..close], sizes), &e[close + 1..]) + } + _ => return range_len(e, sizes), + }; + while !rest.is_empty() { + let Some(tail) = rest.strip_prefix('.') else { return 0 }; + let end = tail.bytes().take_while(|&c| is_ident(c)).count(); + let method = &tail[..end]; + let mut open = end; + if tail[open..].starts_with("::<") { + let mut depth = 0usize; + let Some(close) = tail[open + 2..].bytes().position(|c| { + depth = match c { + b'<' => depth + 1, + b'>' => depth.saturating_sub(1), + _ => depth, + }; + depth == 0 + }) else { + return 0; + }; + open += 2 + close + 1; + } + if tail.as_bytes().get(open) != Some(&b'(') { + return 0; + } + let Some(close) = matching(tail.as_bytes(), open) else { return 0 }; + match method { + "map" | "iter" | "into_iter" | "cloned" | "copied" | "enumerate" | "rev" | "chain" | "to_vec" | "to_owned" | "clone" => {} + "collect" => { + let target = if open > end { + &tail[end + 3..open - 1] + } else if close + 1 == tail.len() { + binding_type + } else { + "" + }; + if !known_collection(target) { + return 0; + } + n = n.min(1); + } + "step_by" => n = n.min(1), + _ => return 0, + } + rest = &tail[close + 1..]; + } + n +} + +/// The number of items in a range of integer literals or constants (`a..b`, `a..=b`); 0 for +/// anything else, an open range included. +fn range_len(e: &str, sizes: &Sizes) -> usize { + let (lo, hi, inclusive) = match e.split_once("..=") { + Some((lo, hi)) => (lo, hi, true), + None => match e.split_once("..") { + Some((lo, hi)) => (lo, hi, false), + None => return 0, + }, + }; + let value = |t: &str| match t.strip_prefix('-') { + Some(t) => sizes.count(t).and_then(|v| i128::try_from(v).ok()).map(|v| -v), + None => sizes.count(t).and_then(|v| i128::try_from(v).ok()), + }; + let (Some(lo), Some(hi)) = (value(lo), value(hi)) else { return 0 }; + let len = hi - lo + i128::from(inclusive); + usize::try_from(len).unwrap_or(0) +} + +/// The number of items in an array literal's masked contents: the count of a repetition, or the +/// elements of a list. +fn array_len(contents: &[u8], sizes: &Sizes) -> usize { + if let Some(count) = repeat_count(contents, sizes) { + return count; + } + if has_top_level(contents, b';') { + return 0; + } + split_args(contents, 0, contents.len()).len() +} + +/// The count of a repetition `[x; N]` (a literal or a `const` of the file), from its masked +/// contents; `None` when they are not a repetition, `Some(0)` when the count is not known. +fn repeat_count(contents: &[u8], sizes: &Sizes) -> Option { + let mut at = 0; + while at < contents.len() { + match contents[at] { + b';' => return Some(sizes.count(&norm(&contents[at + 1..])).unwrap_or(0)), + b'(' | b'[' | b'{' => at = matching(contents, at)? + 1, + _ => at += 1, + } + } + None +} + +/// Whether `c` occurs in `b` outside brackets. +fn has_top_level(b: &[u8], c: u8) -> bool { + let mut at = 0; + while at < b.len() { + match b[at] { + x if x == c => return true, + b'(' | b'[' | b'{' => match matching(b, at) { + Some(close) => at = close + 1, + None => return true, + }, + _ => at += 1, + } + } + false +} + +/// The fewest items a `for` loop after `from`, in the same block, adds to `name`: a loop over a +/// sized source ([`expr_len`]) whose own block (not a nested one) pushes or inserts into `name` +/// on every pass, with no `break`, `continue`, `return` or `?` in the loop. 0 when there is none. +fn loop_fill_len(body: &[u8], name: &[u8], from: usize, sizes: &Sizes) -> usize { + let mut best = 0; + for at in words(body, b"for", from, body.len()) { + if block_depth(&body[from..at]) != Some(0) { + continue; + } + let Some(&in_at) = words(body, b"in", at + 3, body.len()).first() else { continue }; + let Some(open) = (in_at + 2..body.len()).find(|&i| body[i] == b'{' && !has_open_bracket(&body[in_at + 2..i])) else { continue }; + let Some(close) = matching(body, open) else { continue }; + let source = expr_len(&norm(&body[in_at + 2..open]), sizes, ""); + let block = &body[open + 1..close]; + let exits = [&b"break"[..], b"continue", b"return"].iter().any(|w| !words(block, w, 0, block.len()).is_empty()) || contains(block, b"?"); + if source == 0 || exits { + continue; + } + let pushes = words(block, name, 0, block.len()).into_iter().any(|p| { + let before = block[..p].trim_ascii_end(); + let statement = matches!(before.last(), None | Some(b';' | b'{' | b'}')); + let call = norm(&block[p + name.len()..block.len().min(p + name.len() + 16)]); + statement && block_depth(&block[..p]) == Some(0) && [".push(", ".push_back(", ".insert("].iter().any(|m| call.starts_with(m)) + }); + if pushes { + best = best.max(source); + } + } + best +} + +/// The brace depth at the end of `b`, or `None` when it closes a block it did not open. +fn block_depth(b: &[u8]) -> Option { + let mut depth = 0usize; + for &c in b { + match c { + b'{' => depth += 1, + b'}' => depth = depth.checked_sub(1)?, + _ => {} + } + } + Some(depth) +} + +/// Whether `b` leaves a `(` or `[` open. +fn has_open_bracket(b: &[u8]) -> bool { + let mut depth = 0i32; + for &c in b { + match c { + b'(' | b'[' => depth += 1, + b')' | b']' => depth -= 1, + _ => {} + } + } + depth > 0 +} + +/// Whether code after `from` may remove items from `name` or replace it. +fn may_shrink(body: &[u8], name: &[u8], from: usize) -> bool { + may_change(body, name, from, true) +} + +/// Whether code after `from` may change the item count of `name`: an unknown method call, +/// an assignment, or a `&mut` borrow. Growth is harmless only for the source collection. +fn may_change(body: &[u8], name: &[u8], from: usize, allow_growth: bool) -> bool { + const PRESERVING: &[&str] = &[ + "iter", + "iter_mut", + "into_iter", + "len", + "is_empty", + "contains", + "get", + "get_mut", + "first", + "last", + "first_mut", + "last_mut", + "as_slice", + "as_ref", + "clone", + "to_vec", + "to_owned", + "windows", + "chunks", + "chunks_exact", + "sort", + "sort_by", + "sort_by_key", + "sort_unstable", + "sort_unstable_by", + "sort_unstable_by_key", + "reverse", + "binary_search", + "binary_search_by", + "binary_search_by_key", + "starts_with", + "ends_with", + "map", + "concat", + "join", + "keys", + "values", + ]; + const ADDING: &[&str] = &["push", "push_back", "push_front", "insert", "extend"]; + words(body, name, from, body.len()).into_iter().any(|p| { + let after = &body[skip_ws(body, p + name.len())..]; + let assigned = (after.starts_with(b"=") && !after.starts_with(b"==") && !after.starts_with(b"=>")) + || ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="].iter().any(|op| after.starts_with(op.as_bytes())); + let before = body[from..p].trim_ascii_end(); + let borrowed = before.strip_suffix(b"mut").is_some_and(|b| b.trim_ascii_end().ends_with(b"&")); + let called = if after.first() == Some(&b'.') { + let start = skip_ws(after, 1); + let end = start + after[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + let rest = &after[skip_ws(after, end)..]; + let method = &after[start..end]; + (rest.starts_with(b"(") || rest.starts_with(b"::<")) + && !PRESERVING.iter().any(|m| method == m.as_bytes()) + && !(allow_growth && ADDING.iter().any(|m| method == m.as_bytes())) + } else { + false + }; + assigned || borrowed || called + }) +} + +/// The length of a field the file declares as an array of a positive length (`name: [T; N]`), +/// for a receiver `….name`. 0 when any other `name:` in the file may start a type: anything but +/// an array, a lowercase name that is not a path or a primitive type (a value in a struct +/// expression), or a literal. +fn field_len(receiver: &str, sizes: &Sizes) -> usize { + let Some((owner, field)) = receiver.rsplit_once('.') else { return 0 }; + if owner.is_empty() || !plain_local(field) { + return 0; + } + const PRIMITIVE: &[&str] = &[ + "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "f32", "f64", "bool", "char", "str", "dyn", "impl", + "fn", "mut", "crate", "self", "super", + ]; + let file = sizes.file; + let mut least: Option = None; + for at in words(file, field.as_bytes(), 0, file.len()) { + let colon = skip_ws(file, at + field.len()); + if file.get(colon) != Some(&b':') || file.get(colon + 1) == Some(&b':') || at.checked_sub(1).is_some_and(|j| file[j] == b':') { + continue; + } + let ty = skip_ws(file, colon + 1); + let word_end = ty + file[ty..].iter().copied().take_while(|&c| is_ident(c)).count(); + let word = &file[ty..word_end]; + let value = match file.get(ty) { + Some(b'[') => false, + Some(c) if c.is_ascii_digit() || matches!(c, b'"' | b'\'' | b'-') => true, + Some(c) if c.is_ascii_lowercase() || *c == b'_' => { + let path = file[skip_ws(file, word_end)..].starts_with(b"::"); + !path && !PRIMITIVE.iter().any(|p| p.as_bytes() == word) + } + _ => return 0, + }; + if value { + continue; + } + let Some(close) = matching(file, ty) else { return 0 }; + match repeat_count(&file[ty + 1..close], sizes) { + Some(n) if n > 0 => least = Some(least.map_or(n, |l| l.min(n))), + Some(_) => return 0, + None => {} + } + } + least.unwrap_or(0) +} + +/// What the rules know about collection sizes in one masked file: its `const` counts, read on first use. +struct Sizes<'a> { + file: &'a [u8], + consts: OnceCell>, +} + +impl Sizes<'_> { + /// An unsigned integer literal (with `_` and an integer suffix allowed) or a `const` of the + /// file whose value is one. + fn count(&self, text: &str) -> Option { + int_literal(text).or_else(|| self.consts.get_or_init(|| file_consts(self.file)).get(text).copied()) + } +} + +fn int_literal(text: &str) -> Option { + let digits = text.bytes().take_while(|c| c.is_ascii_digit() || *c == b'_').count(); + let suffix = &text[digits..]; + let suffixes = ["", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize"]; + if digits == 0 || !text.as_bytes()[0].is_ascii_digit() || !suffixes.contains(&suffix) { + return None; + } + text[..digits].replace('_', "").parse().ok() +} + +/// `const NAME: T = ;` in a masked file; a name declared more than once keeps +/// its smallest value, and 0 when one of its values is not a literal. +fn file_consts(file: &[u8]) -> HashMap { + let mut out: HashMap = HashMap::new(); + for at in words(file, b"const", 0, file.len()) { + let start = skip_ws(file, at + 5); + let end = start + file[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || skip_ws(file, end) >= file.len() || file[skip_ws(file, end)] != b':' { + continue; + } + let stop = statement_end(file, end); + let stmt = norm(&file[end..stop]); + let Some((_, value)) = stmt.split_once('=') else { continue }; + let value = int_literal(value).unwrap_or(0); + let name = String::from_utf8_lossy(&file[start..end]).into_owned(); + let slot = out.entry(name).or_insert(value); + *slot = (*slot).min(value); + } + out +} + +/// A `let` of a plain name: the name, where the statement ends, and whether it binds an expression +/// that checks a size ([`SIZE_CHECKS`]). +struct Binding { + name: Vec, + end: usize, + counts: bool, +} + +/// Every `let` of a plain name in `body`, in order. +fn bindings(body: &[u8]) -> Vec { + words(body, b"let", 0, body.len()) + .into_iter() + .filter_map(|at| { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); + } + let end = start + body[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || body[start].is_ascii_digit() { + return None; + } + let stop = statement_end(body, end); + let stmt = norm(&body[end..stop]); + let counts = stmt.split_once('=').is_some_and(|(_, init)| SIZE_CHECKS.iter().any(|g| init.contains(g))); + Some(Binding { name: body[start..end].to_vec(), end: stop, counts }) + }) + .collect() +} + +/// Whether `body[from..to]` (an assertion operand) reads a local whose binding reaching that +/// point checks a size and was not assigned since. +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)) + }) + }) } /// Whether an assertion's (masked, whitespace-free) condition only says that there is a value. @@ -1803,7 +2405,7 @@ mod tests { 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.clone()", "xs[1..]", "&&xs"] { + 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}"); } @@ -1913,12 +2515,23 @@ mod tests { "[]", "[1; 0]", "[1; 0].map(|x| x + 1)", - "vec![1, 2]", + "vec![]", + "vec![1; 0]", + "vec![1; n]", "items()", "items().collect()", + "items().collect::>()", + "(0..0).collect::>()", + "(3..1).collect::>()", + "(0..n).collect::>()", + "(0..).take(3).collect::>()", + "[1, 2].iter().filter(|x| keep(x)).collect::>()", + "[1, 2].into_iter().zip(ys).collect::>()", + "[None::].into_iter().collect::>>()", + "[Err::(error())].into_iter().collect::, E>>()", "[1, 2].into_iter().collect()", - "[1, 2].map(|x| x + 1).into_iter().collect()", - "[1, 2].map(|x| x + 1).map(|x| x + 1)", + "[1, 2].into_iter().collect::()", + "[1, 2].into_iter().collect::>()", ] { for binding in [format!("let xs = {value};"), format!("let mut xs = {value};"), format!("let xs: [u8; 0] = {value};")] { let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); @@ -1976,6 +2589,333 @@ mod tests { } } + #[test] + fn all_skips_bindings_with_sized_initializers() { + let consts = "const N: usize = 3;\nconst NONE: usize = 0;\n"; + for binding in [ + "let xs = vec![1, 2];", + "let mut xs = vec![[1, 2]; 2];", + "let xs: Vec<_> = [1, 2].into_iter().collect();", + "let xs = [1, 2].map(|x| x + 1).map(|x| x + 1);", + "let xs: Vec = [1, 2].iter().copied().rev().collect();", + "let xs: Vec = (0..40u8).map(|n| px(n)).collect();", + "let xs = (1..=3).collect::>();", + "let xs = (-2..1).step_by(2).collect::>();", + "let xs: Vec<_> = (0..N).collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect::>().into_iter().collect();", + "let xs = [0.0; N];", + "let xs: [u8; 3] = items();", + "let xs: [u8; N] = items();", + ] { + let src = format!("{consts}#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(7, "all-unguarded")], "{binding} then cleared"); + } + for binding in [ + "let xs = (0..NONE).collect::>();", + "let xs = [0.0; NONE];", + "let xs: [u8; NONE] = [1];", + "let xs = (0..M).collect::>();", + "let xs = [None::].into_iter().collect::>>();", + "let xs = [Err::(error())].into_iter().collect::, E>>();", + "let xs: Option> = [1].into_iter().collect();", + "let xs: Result, E> = [1].into_iter().collect();", + "let xs = [1, 2].into_iter().collect();", + "let xs: Items = [1, 2].into_iter().collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect().clone();", + "let xs: Vec<_> = [1, 2].into_iter().collect().into_iter().collect();", + "let xs: Vec<_> = [None::].into_iter().collect::>>().into_iter().collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect::();", + ] { + let src = format!("{consts}#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(6, "all-unguarded")], "{binding}"); + } + for later in [ + "xs.retain(|x| keep(x));", + "xs = items();", + "take(&mut xs);", + "xs.truncate(0);", + "xs.pop();", + "xs.resize(0, 0);", + "xs.resize_with(0, f);", + "xs.pop_front();", + "xs.pop_back();", + "xs.unknown_method_that_may_shrink();", + "xs . unknown::();", + ] { + let src = format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n {later}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{later}"); + } + for op in ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="] { + let src = + format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n xs {op} other;\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{op}"); + } + for later in [ + "xs[0] = 5; use_it(&xs);", + "xs[1] = 5; use_it(&xs);", + "use_it(&xs);", + "use_it(xs);", + "use_it(xs == other);", + "match other { xs => use_it(xs), _ => () };", + "xs.push(3); xs.push_back(4); xs.push_front(5); xs.insert(0, 6); xs.extend(other);", + "xs.sort(); xs.sort_by(f); xs.sort_by_key(f); xs.sort_unstable(); xs.reverse();", + "use_it(xs.iter()); use_it(xs.iter_mut()); use_it(xs.into_iter());", + "use_it(xs.len()); use_it(xs.is_empty()); use_it(xs.contains(&1));", + "use_it(xs.get(0)); use_it(xs.get_mut(0)); use_it(xs.first()); use_it(xs.last());", + "use_it(xs.first_mut()); use_it(xs.last_mut()); use_it(xs.as_slice()); use_it(xs.as_ref());", + "use_it(xs.clone()); use_it(xs.to_vec()); use_it(xs.windows(2)); use_it(xs.chunks(2));", + "use_it(xs.binary_search(&1)); use_it(xs.starts_with(&[1])); use_it(xs.ends_with(&[2]));", + "use_it(xs.map(f)); use_it(xs.concat()); use_it(xs.join(sep)); use_it(xs.keys()); use_it(xs.values());", + ] { + let src = format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n {later}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{later}"); + } + } + + #[test] + fn all_collects_require_known_collection_targets() { + for target in [ + "Vec<_>", + "std::vec::Vec<_>", + "VecDeque<_>", + "std::collections::VecDeque<_>", + "HashSet<_>", + "std::collections::HashSet<_>", + "BTreeSet<_>", + "std::collections::BTreeSet<_>", + "HashMap<_, _>", + "std::collections::HashMap<_, _>", + "BTreeMap<_, _>", + "std::collections::BTreeMap<_, _>", + "BinaryHeap<_>", + "std::collections::BinaryHeap<_>", + "LinkedList<_>", + "std::collections::LinkedList<_>", + "String", + "std::string::String", + "Box<[_]>", + "std::boxed::Box<[_]>", + ] { + let source = if target.contains("Map") { "[(1, 2)]" } else { "['a', 'b']" }; + for binding in [ + format!("let xs = {source}.into_iter().collect::<{target}>();"), + format!("let xs: {target} = {source}.into_iter().collect();"), + format!("let xs = {source}.into_iter().collect::<{target}>().into_iter().collect::>();"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + } + } + } + + #[test] + fn all_skips_collections_every_pass_of_a_sized_loop_fills() { + for (source, fill) in [ + ("[1, 2, 3]", "xs.push(i);"), + ("0..3", "xs.push(i);"), + ("[[0, 1], [1, 0]]", "let s = Fill { a: 1 }.span(i);\n xs.push(s);"), + ("[1, 2].iter().enumerate()", "for j in items() { use_it(j); }\n xs.insert(i);"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let mut xs = vec![];\n for i in {source} {{\n {fill}\n }}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [], "{source}: {fill}"); + let after = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&after), [(line + 1, "all-unguarded")], "{source} then cleared"); + } + for (source, fill) in [ + ("items()", "xs.push(i);"), + ("0..0", "xs.push(i);"), + ("0..n", "xs.push(i);"), + ("[1, 2]", "if keep(i) { xs.push(i); }"), + ("[1, 2]", "if !keep(i) { continue; }\n xs.push(i);"), + ("[1, 2]", "let v = get(i)?;\n xs.push(v);"), + ("[1, 2]", "ys.iter().for_each(|y| xs.push(*y));"), + ("[1, 2]", "ys.push(i);"), + ("[1, 2]", "let mut xs = vec![];\n xs.push(i);"), + ("[1, 2].iter().filter(|x| keep(x))", "xs.push(i);"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let mut xs = vec![];\n for i in {source} {{\n {fill}\n }}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [(line, "all-unguarded")], "{source}: {fill}"); + } + let nested = "#[test]\nfn t() {\n let mut xs = vec![];\n if ready() {\n for i in [1, 2] {\n xs.push(i);\n }\n }\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(nested), [(9, "all-unguarded")], "a loop that may not run"); + } + + #[test] + fn all_skips_fields_the_file_declares_as_arrays() { + let test = "#[test]\nfn t() {\n let c = parse();\n assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v)));\n}\n"; + for decl in [ + "struct C { rgb: [f32; 3] }\n", + "const N: usize = 3;\nstruct C { pub rgb: [f32; N], alpha: Option }\n", + "struct C { rgb: [f32; 3] }\nfn c() -> C { C { rgb: rgb_of(\"x\"), alpha: 1 } }\n", + ] { + let src = format!("{decl}{test}"); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [], "{decl}"); + let other = format!("{decl}struct D {{ rgb: Vec }}\n{test}"); + assert_eq!(hits(&other), [(line + 1, "all-unguarded")], "another struct's rgb can be empty"); + } + for decl in + ["struct C { rgb: [f32; 0] }\n", "struct C { rgb: &'static [f32] }\n", "struct C { rgb: [f32; LEN] }\n", "struct C { other: [f32; 3] }\n"] + { + let src = format!("{decl}{test}"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{decl}"); + } + for other in ["std::vec::Vec", "Pixels", "u8", "(f32, f32)", "T"] { + let src = format!("struct C {{ rgb: [f32; 3] }}\nstruct D {{ rgb: {other} }}\n{test}"); + assert_eq!(hits(&src), [(6, "all-unguarded")], "another struct's rgb is {other}"); + } + let local = "struct C { rgb: [f32; 3] }\n#[test]\nfn t() {\n let rgb = parse();\n assert!(rgb.iter().all(|v| valid(v)));\n}\n"; + assert_eq!(hits(local), [(5, "all-unguarded")], "a local name is not the field"); + } + + #[test] + fn all_equality_guards_follow_methods_that_keep_items() { + for operand in [ + "xs.clone()", + "xs.iter().map(|l| l.0).collect()", + "xs.iter().copied().collect::>().into_iter().collect()", + "xs.iter().map(|l| l.0).collect::>()", + "&xs.iter().copied().rev().collect::>()", + ] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({operand}, vec![0, 7]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{operand}"); + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(5, "all-unguarded")], "{operand} then cleared"); + } + for (binding, compared) in [ + ("let ids: Vec<&str> = xs.iter().map(|l| l.id()).collect();", "assert_eq!(ids, [\"a\", \"b\"]);"), + ("let ids = xs.iter().cloned().collect::>();", "assert_eq!([\"a\"], ids);"), + ("let ids = xs.iter().copied().collect::>();", "assert_eq!(ids, [1]);"), + ("let ids: Vec<_> = xs.iter().copied().collect::>().into_iter().collect();", "assert_eq!(ids, [1]);"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n {compared}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + let filtered = src.replace(binding, &binding.replace(".iter()", ".iter().filter(|x| keep(x))")); + assert_eq!(hits(&filtered), [(5, "all-unguarded")], "{binding} through a filter"); + let rebound = src.replace(&format!(" {compared}\n"), &format!(" let ids = other();\n {compared}\n")); + assert_eq!(hits(&rebound), [(6, "all-unguarded")], "{binding} then bound again"); + for change in ["ids = vec![1];", "ids.clear();", "reset(&mut ids);", "ids.push(1);"] { + let reassigned = + src.replace("let ids", "let mut ids").replace(&format!(" {compared}\n"), &format!(" {change}\n {compared}\n")); + assert_eq!(hits(&reassigned), [(6, "all-unguarded")], "{binding} then {change}"); + } + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(6, "all-unguarded")], "{binding} then the source cleared"); + } + } + + #[test] + fn all_equality_guards_stop_at_other_collect_targets() { + for operand in [ + "xs.iter().copied().collect().into_iter().collect::>()", + "xs.iter().copied().collect().into_iter().collect()", + "xs.iter().copied().collect().clone()", + ] { + for compared in [format!("{operand}, [vec![]]"), format!("[vec![]], {operand}")] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({compared});\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{compared}"); + } + } + for binding in [ + "let ids: Option> = xs.iter().copied().collect();", + "let ids: Result, E> = xs.iter().copied().collect();", + "let ids: Items = xs.iter().copied().collect();", + "let ids = xs.iter().copied().collect();", + "let ids: Vec<_> = xs.iter().copied().collect().into_iter().collect();", + "let ids: Vec<_> = xs.iter().copied().collect().into_iter().collect::>();", + "let ids: Vec<_> = xs.iter().copied().collect().clone();", + ] { + let src = format!( + "#[test]\nfn t() {{\n {binding}\n assert_eq!(ids.into_iter().collect::>(), [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{binding}"); + } + for target in ["Option>", "Result, E>", "Items"] { + let operand = format!("xs.iter().copied().collect::<{target}>().iter().collect::>()"); + let direct = format!("#[test]\nfn t() {{\n assert_eq!({operand}, [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&direct), [(4, "all-unguarded")], "{target} compared directly"); + let derived = format!( + "#[test]\nfn t() {{\n let ids = {operand};\n assert_eq!(ids, [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&derived), [(5, "all-unguarded")], "{target} through a local"); + } + } + + #[test] + fn all_skips_const_and_static_arrays_of_the_file() { + let test = "#[test]\nfn t() {\n assert!(NAMES.iter().all(|n| valid(n)));\n}\n"; + for decl in [ + "const NAMES: [&str; 2] = [\"a\", \"b\"];\n", + "static NAMES: [u8; N] = [0; N];\nconst N: usize = 4;\n", + "pub(crate) static mut NAMES: [u8; 1] = [0];\n", + ] { + let src = format!("{decl}{test}"); + assert_eq!(hits(&src), [], "{decl}"); + } + for decl in ["const NAMES: [&str; 0] = [];\n", "const NAMES: &[&str] = &[\"a\"];\n", "fn my_const() {}\nlet NAMES: [u8; 2] = f();\n", ""] { + let src = format!("{decl}{test}"); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [(line, "all-unguarded")], "{decl}"); + } + let shadowed = "const NAMES: [&str; 2] = [\"a\", \"b\"];\n#[test]\nfn t() {\n let NAMES = items();\n assert!(NAMES.iter().all(|n| valid(n)));\n}\n"; + assert_eq!(hits(shadowed), [(5, "all-unguarded")], "a local of the same name"); + for (other_type, other_value, found) in [("[u8; 0]", "[]", true), ("&[u8]", "&[]", true), ("[u8; 3]", "[0; 3]", false)] { + for (first_type, first_value, second_type, second_value) in + [("[u8; 2]", "[0; 2]", other_type, other_value), (other_type, other_value, "[u8; 2]", "[0; 2]")] + { + let src = format!( + "mod a {{ const CASES: {first_type} = {first_value}; }}\nmod b {{\nconst CASES: {second_type} = {second_value};\n#[test]\nfn t() {{\n assert!(CASES.iter().all(|n| valid(n)));\n}}\n}}\n" + ); + let want: &[(usize, &str)] = if found { &[(6, "all-unguarded")] } else { &[] }; + assert_eq!(hits(&src), want, "{first_type} and {second_type}"); + } + } + } + + #[test] + fn all_windows_need_as_many_items_as_their_size() { + for (array, method, found) in [ + ("[a, b, c, d]", "windows(2)", false), + ("[a, b]", "windows(2)", false), + ("[a]", "windows(2)", true), + ("[a, b]", "windows(k)", true), + ("[a]", "chunks(3)", false), + ("[a, b]", "chunks_exact(3)", true), + ("[a, b, c]", "chunks_exact(3)", false), + ] { + let src = + format!("#[test]\nfn t() {{\n let xs = {array}.map(|s| node(s));\n assert!(xs.{method}.all(|w| w[0].y == w[1].y));\n}}\n"); + let want: &[(usize, &str)] = if found { &[(4, "all-unguarded")] } else { &[] }; + assert_eq!(hits(&src), want, "{array}.{method}"); + } + } + + #[test] + fn all_guards_accept_asserted_locals_that_count() { + let src = "#[test]\nfn t() {\n let row = cards.iter().filter(|c| first_row(c)).count();\n assert_eq!(row, 4, \"four cards\");\n assert!(cards.iter().all(|c| c.x < 10));\n}\n"; + assert_eq!(hits(src), []); + let summed = src.replace(".count()", ".map(|c| c.w).sum::()"); + assert_eq!(hits(&summed), [(5, "all-unguarded")], "a sum does not count items"); + let message = src.replace("assert_eq!(row, 4, \"four cards\")", "assert_eq!(a, b, \"{}\", row)"); + assert_eq!(hits(&message), [(5, "all-unguarded")], "a count in a failure message checks nothing"); + let unused = src.replace(" assert_eq!(row, 4, \"four cards\");\n", ""); + assert_eq!(hits(&unused), [(4, "all-unguarded")], "a count no assertion reads checks nothing"); + for change in ["let row = 4;", "row = 4;", "reset(&mut row);"] { + let changed = src.replace(" assert_eq!(row", &format!(" {change}\n assert_eq!(row")); + assert_eq!(hits(&changed), [(6, "all-unguarded")], "{change} before the assertion"); + } + let later = src.replace(" assert_eq!(row, 4, \"four cards\");\n", " assert_eq!(row, 4);\n let row = 4;\n"); + assert_eq!(hits(&later), [], "the count reaches the assertion before it is bound again"); + } + #[test] fn all_respects_condition_polarity() { for condition in [ @@ -2513,6 +3453,22 @@ mod tests { 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, ["only-weak", "self-compare", "ignore-without-reason", "sleep"]); + let weak = "#[test]\nfn weak() {\n assert!(f().is_ok());\n}\n"; + let unguarded = "#[test]\nfn all() {\n assert!(f().iter().all(|x| valid(x)));\n}\n"; + let 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"); + let both = hits_of(&format!("{weak}{unguarded}")); + assert_eq!(both.len(), 2); + let Err(message) = finish(&both, 0, 1, "base") else { panic!("only-weak fails the check") }; + assert!(message.starts_with("1 test-lint hit(s)"), "{message}"); + assert!(message.contains("[only-weak] `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()));