diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 449885209f..f6b8a6e2b1 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -16,8 +16,12 @@ //! be `const`s of the file) followed only by methods that keep an item (`map`, `iter`, `rev`, //! `collect` …), or filled by a `push` or `insert` on every pass of a loop over one, unless later //! code may shrink or replace them; and fields the file declares only as arrays of a positive -//! length. `.windows(k)` and `.chunks_exact(k)` need `k` items. Empty arrays still count. A change -//! anywhere in the test counts as a change to the hit; +//! length. `.windows(k)` and `.chunks_exact(k)` need `k` items. Empty arrays still count. Also +//! left out: a parenthesized range of literals or constants (`(0..3).all(…)`); a receiver whose +//! source an earlier equality assertion compares with a non-empty literal (a local bound from the +//! receiver, or the call the receiver is bound to), when nothing changes the source in between; +//! and a call to a function of the file that lists every row of a non-empty constant table +//! without filtering it. A change anywhere in the test counts as a change to the hit; //! * `only-weak`: every assertion is `is_ok()`, `is_some()`, `!is_empty()` or `len() > 0`, and the //! test calls no asserting helper; //! * `self-compare`: `assert_eq!(x, x)` or `assert_ne!(x, x)` on the same expression, when that @@ -26,7 +30,10 @@ //! * `exit-status-only`: a test that runs a process and checks only its exit status, reading no //! output, with a status check in any condition or compared operand of a standard assertion; //! * `no-assertion`: no assertion macro, `panic!`, `unwrap_err`, `expect_err` or asserting helper, -//! and no `#[should_panic]`; +//! and no `#[should_panic]`. An asserting helper passed by name as a value +//! (`keeping_settings(the_body)`) counts, unless a local binding or parameter shadows the name, +//! and so does an `#[ignore = "…"]` test that prints. A top-level test's call reaches the helper +//! of its own file when the file defines one of that name at its top level; //! * `early-return`: a silent bare `return` before the end of the test whose guard tests a value //! from the code under test. Left out: a return after an assertion in its block, one whose //! statement or line has a comment or a printed note saying why, and guards on files, fonts, @@ -1315,35 +1322,92 @@ fn in_regions(regions: &[(usize, usize)], pos: usize) -> bool { type Def = (String, bool, Vec); /// For each crate of `files` ([`crate_of`]), the names of the functions and macros in its test -/// code, or in `crates/testkit`'s, that assert, panic or call one that does. +/// code, or in `crates/testkit`'s, that assert, panic or call one that does. Each file of `files` +/// also gets an entry under its path ([`helpers_for`]): a call in a top-level test reaches the +/// function of that name the file defines only when all its definitions are at the file's top +/// level and the file does not call that name with a path. Other names keep the crate's verdict. pub fn asserting_helpers(files: &[(String, String)]) -> HashMap> { let mut defs: HashMap> = HashMap::new(); + // Each file's path, its definitions, and the names its own definitions decide. + let mut by_file: Vec<(&str, Vec, HashSet)> = vec![]; for (path, src) in files { let m = mask(src); let regions = test_regions(path, &m, &tests_in(&m)); - let crate_defs = defs.entry(crate_of(path)).or_default(); - for at in words(&m, b"fn", 0, m.len()).into_iter().chain(words(&m, b"macro_rules", 0, m.len())) { - if in_regions(®ions, at) { - crate_defs.extend(definition(&m, at)); - } - } + let depths = brace_depths(&m); + let mut nested = HashSet::new(); + let own: Vec = words(&m, b"fn", 0, m.len()) + .into_iter() + .chain(words(&m, b"macro_rules", 0, m.len())) + .filter(|&at| in_regions(®ions, at)) + .filter_map(|at| { + let def = definition(&m, at)?; + if depths[at] != 0 { + nested.insert(def.0.clone()); + } + Some(def) + }) + .collect(); + // A call with a path (`other::near(…)`) may reach another module's function, and calls + // keep only the last name, so a name the file also calls with a path keeps the crate's + // verdict. A definition below the file's top level also keeps the crate's verdict. + let names = own.iter().map(|d| d.0.clone()).filter(|n| !nested.contains(n) && !called_with_path(&m, n)).collect(); + defs.entry(crate_of(path)).or_default().extend(own.iter().cloned()); + by_file.push((path, own, names)); } let testkit = defs.get(TESTKIT).cloned().unwrap_or_default(); - defs.iter().map(|(krate, own)| (krate.clone(), checking(own.iter().chain(if krate == TESTKIT { &[][..] } else { &testkit[..] })))).collect() + let mut out: HashMap> = defs + .iter() + .map(|(krate, own)| (krate.clone(), checking(HashSet::new(), own.iter().chain(if krate == TESTKIT { &[][..] } else { &testkit[..] })))) + .collect(); + for (path, own, names) in by_file { + if names.is_empty() { + continue; + } + let base = out.get(&crate_of(path)).map(|set| set.difference(&names).cloned().collect()).unwrap_or_default(); + out.insert(path.to_owned(), checking(base, own.iter().filter(|d| names.contains(&d.0)))); + } + out +} + +/// Whether the masked file names `name` (a function, or `name!` for a macro) after a `::` path. +fn called_with_path(m: &[u8], name: &str) -> bool { + let name = name.trim_end_matches('!'); + words(m, name.as_bytes(), 0, m.len()).into_iter().any(|at| m[..at].trim_ascii_end().ends_with(b"::")) +} + +/// The asserting helpers a test in the file at `path` can reach: for a top-level test, the file's +/// own entry of [`asserting_helpers`] if present; otherwise, its crate's. +fn helpers_for<'a>(ctx: &'a Ctx, path: &str, top_level: bool) -> Option<&'a HashSet> { + if top_level { ctx.helpers.get(path).or_else(|| ctx.helpers.get(&crate_of(path))) } else { ctx.helpers.get(&crate_of(path)) } +} + +/// The brace depth before each byte of masked text. +fn brace_depths(m: &[u8]) -> Vec { + let mut depth = 0usize; + m.iter() + .map(|&c| { + let before = depth; + match c { + b'{' => depth += 1, + b'}' => depth = depth.saturating_sub(1), + _ => {} + } + before + }) + .collect() } /// The crate whose test helpers every crate can call. const TESTKIT: &str = "crates/testkit"; -/// The names among `defs` that check something, directly or through another of `defs`. Calls do -/// not say which of several functions with one name they reach, so a name counts only when every -/// definition with that name checks. -fn checking<'a>(defs: impl Iterator + Clone) -> HashSet { +/// `known` and the names among `defs` that check something, directly or through another of +/// `defs` or a name of `known`. Calls do not say which of several functions with one name they +/// reach, so a name counts only when every definition with that name checks. +fn checking<'a>(mut known: HashSet, defs: impl Iterator + Clone) -> HashSet { let mut by_name: HashMap<&str, Vec<&Def>> = HashMap::new(); for d in defs { by_name.entry(d.0.as_str()).or_default().push(d); } - let mut known: HashSet = HashSet::new(); loop { let checks = |d: &Def| d.1 || d.2.iter().any(|c| known.contains(c)); let more: Vec = by_name @@ -1380,7 +1444,14 @@ fn item_at(m: &[u8], at: usize) -> Option<(&[u8], bool, usize, usize)> { fn definition(m: &[u8], at: usize) -> Option { let (name, is_macro, open, close) = item_at(m, at)?; let name = String::from_utf8_lossy(name).into_owned(); - let called = calls(m, open, close).into_iter().filter(|(_, method)| !method).map(|(n, _)| n).collect(); + let called = calls(m, open, close) + .into_iter() + .filter(|(_, method)| !method) + .map(|(n, _)| n) + .chain( + passed_names(m, open, close).into_iter().filter(|(name, pos)| !shadows_helper(m, at, open, close, name.as_bytes(), *pos)).map(|(n, _)| n), + ) + .collect(); Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) } @@ -1391,6 +1462,8 @@ struct File<'a> { path: &'a str, src: &'a [u8], m: Vec, + /// The brace depth before each byte of [`File::m`] ([`brace_depths`]). + depths: Vec, /// [`File::m`] with the functions and macros declared inside each test blanked: declaring /// one does not run its body ([`executed`]). exec: Vec, @@ -1435,11 +1508,12 @@ impl File<'_> { /// Every hit in one file, exemptions applied. pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { let m = mask(src); + let depths = brace_depths(&m); let tests = tests_in(&m); let regions = test_regions(path, &m, &tests); let exec = executed(&m, &tests); let cfgs = cfg_spans(&m, src.as_bytes()); - let file = File { path, src: src.as_bytes(), m, exec, lines: Lines::new(src), tests, regions, cfgs }; + let file = File { path, src: src.as_bytes(), m, depths, exec, lines: Lines::new(src), tests, regions, cfgs }; let mut hits: Vec = file.tests.iter().flat_map(|t| test_hits(&file, t, ctx)).collect(); hits.extend(ignore_hits(&file)); hits.extend(sleep_hits(&file)); @@ -1493,19 +1567,24 @@ struct View<'a> { delegates: bool, checks: bool, should_panic: bool, + /// An ignored test with a reason that prints what it measures ([`ignored_with_reason`], + /// [`prints`]): a diagnostic run by hand, which has nothing to assert. + diagnostic: bool, } fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { let m = &file.exec; let asserts: Vec = macro_calls(m, t.open, t.close).into_iter().filter(|c| is_assert_macro(&c.name)).collect(); let none = HashSet::new(); - let helpers = ctx.helpers.get(&crate_of(file.path)).unwrap_or(&none); + let helpers = helpers_for(ctx, file.path, file.depths[t.attr] == 0).unwrap_or(&none); let delegates = calls(m, t.open, t.close) .iter() - .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)); + .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)) + || passes_helper(m, t, helpers); let checks = checks_itself(m, t.open, t.close); let should_panic = should_panic_attr(m, t.attr, t.fn_at); - let v = View { file, t, asserts, delegates, checks, should_panic }; + let diagnostic = ignored_with_reason(file, t.attr, t.fn_at) && prints(m, t.open, t.close); + let v = View { file, t, asserts, delegates, checks, should_panic, diagnostic }; let mut hits = all_unguarded(&v); hits.extend(self_compare(&v)); hits.extend(early_returns(&v)); @@ -1517,6 +1596,183 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { hits } +/// Whether a test's body passes an asserting helper by name as a value, an argument or a tuple +/// element (`keeping_settings(the_test_body)`, `[("case", case_body), …]`), excluding local bindings +/// and parameters that shadow helper names. +fn passes_helper(m: &[u8], t: &TestFn, helpers: &HashSet) -> bool { + passed_names(m, t.open, t.close).into_iter().any(|(name, pos)| { + name != t.name + && !COMMON.contains(&name.as_str()) + && helpers.contains(&name) + && !shadows_helper(m, t.fn_at, t.open, t.close, name.as_bytes(), pos) + }) +} + +/// Whether a parameter of the function at `at` (body `open..close`), or a local binding in scope at +/// `pos`, shadows the helper `name`. +fn shadows_helper(m: &[u8], at: usize, open: usize, close: usize, name: &[u8], pos: usize) -> bool { + binds_parameter(&m[at..=open], name) || bound_at(&m[open + 1..close], name, pos - (open + 1)) +} + +/// Whether a binding of `name` in `body` is in scope at `pos`: a `let` from the end of its statement +/// to the end of its block (an `if let` or `while let` in its block only), a `for` pattern in the +/// loop body, a match-arm pattern inside its arm, or a closure parameter inside the closure's body. +fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool { + let lets = words(body, b"let", 0, pos).into_iter().any(|at| { + let start = at + 3; + let mut end = start; + while end < body.len() { + if matches!(body[end], b'=' | b';') + || (body[end..].starts_with(b"else") && !is_ident(body[end - 1]) && !body.get(end + 4).copied().is_some_and(is_ident)) + { + break; + } + end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 }; + } + if words(body, name, start, end).is_empty() { + return false; + } + let head = body[..at].trim_ascii_end(); + let conditional = + [&b"if"[..], b"while"].into_iter().any(|k| head.ends_with(k) && !head[..head.len() - k.len()].last().copied().is_some_and(is_ident)); + if conditional { + return let_body(body, start).is_some_and(|(_, open, close)| open < pos && pos < close); + } + statement_end(body, at) < pos && pos < block_close(body, at) + }); + let loops = words(body, b"for", 0, pos).into_iter().any(|at| { + let Some((open, close)) = block_after(body, at + 3) else { return false }; + let Some(&in_at) = words(body, b"in", at + 3, open).first() else { return false }; + open < pos && pos < close && !words(body, name, at + 3, in_at).is_empty() + }); + let name = String::from_utf8_lossy(name); + lets || loops || arm_binding(body, &name, pos).is_some() || closure_binding(body, &name, pos).is_some() +} + +/// The innermost unclosed `(`, `[` or `{` before `at`. +fn enclosing_open(m: &[u8], at: usize) -> Option { + let mut depth = 0usize; + for i in (0..at).rev() { + match m[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth == 0 => return Some(i), + b'(' | b'[' | b'{' => depth -= 1, + _ => {} + } + } + None +} + +/// The bare identifiers, with their offsets, passed as arguments or as tuple or array elements in +/// the body between `open` and `close`. An element of a tuple, array or constructor counts only +/// where its value is kept: not in a statement of its own (`(body,);`), a `let _` or `let _name` +/// binding, or a `drop` or `forget` call. +fn passed_names(m: &[u8], open: usize, close: usize) -> Vec<(String, usize)> { + let mut names = Vec::new(); + let mut at = open + 1; + while at < close { + if !is_ident(m[at]) || (at > 0 && (is_ident(m[at - 1]) || m[at - 1] == b'.')) { + at += 1; + continue; + } + let end = at + m[at..close].iter().take_while(|&&c| is_ident(c)).count(); + let before = m[..at].trim_ascii_end().last().copied(); + let after = m.get(skip_ws(m, end)).copied(); + if matches!(before, Some(b'(' | b'[' | b',')) && matches!(after, Some(b')' | b']' | b',')) && value_kept(m, open, at) { + names.push((String::from_utf8_lossy(&m[at..end]).into_owned(), at)); + } + at = end; + } + names +} + +/// Whether the element at `at` is a call's argument, or sits in a tuple or array whose statement +/// keeps it ([`passed_names`]). +fn value_kept(m: &[u8], open: usize, at: usize) -> bool { + let Some(mut group) = enclosing_open(m, at).filter(|&g| g > open) else { return false }; + // A name in a `let` or `for` pattern (`let (body,) = …`) binds a value rather than passing one. + let from = m[open + 1..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(open + 1, |p| open + 2 + p); + if words(m, b"let", from, at).last().is_some_and(|&l| !m[l..at].contains(&b'=')) + || words(m, b"for", from, at).last().is_some_and(|&f| words(m, b"in", f, at).is_empty()) + { + return false; + } + loop { + let head = m[..group].trim_ascii_end(); + let call = m[group] != b'{' && head.last().is_some_and(|&c| is_ident(c) || c == b'!' || c == b'>'); + let mut start = group; + if call { + // A call runs even when its result is dropped; constructors only store the value. + let name = &head[head.len() - head.iter().rev().take_while(|&&c| is_ident(c)).count()..]; + let constructor = name.first().is_some_and(u8::is_ascii_uppercase) || head.ends_with(b"!") || head.ends_with(b"::new"); + if !constructor { + return !matches!(name, b"drop" | b"forget"); + } + start = head.len() - head.iter().rev().take_while(|&&c| is_ident(c) || matches!(c, b':' | b'!')).count(); + } + if let Some(outer) = enclosing_open(m, group).filter(|&g| g > open && m[g] != b'{') { + group = outer; + continue; + } + let statement = m[..start].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let statement = m[statement..start].trim_ascii(); + // `let _ = …` and `let _name = …` drop or ignore the value. + let discarded = statement + .strip_prefix(b"let") + .filter(|r| r.first().is_some_and(u8::is_ascii_whitespace)) + .is_some_and(|r| r.trim_ascii_start().starts_with(b"_")); + return !discarded && !statement.iter().all(|&c| c.is_ascii_whitespace() || c == b'&'); + } +} + +/// Whether a function or closure in `body` takes a parameter that binds `name`. +fn binds_parameter(body: &[u8], name: &[u8]) -> bool { + let binds = |from, to| { + split_args(body, from, to).into_iter().any(|(start, end)| { + let pattern = &body[start..end]; + let end = pattern.iter().position(|&c| c == b':').unwrap_or(pattern.len()); + !words(pattern, name, 0, end).is_empty() + }) + }; + if words(body, b"fn", 0, body.len()).into_iter().any(|at| { + let Some(open) = body[at + 2..].iter().position(|&c| c == b'(').map(|p| at + 2 + p) else { return false }; + matching(body, open).is_some_and(|close| binds(open + 1, close)) + }) { + return true; + } + let mut at = 0; + while at < body.len() { + let head = body[..at].trim_ascii_end(); + let opens = head.last().is_some_and(|c| matches!(c, b'=' | b'(' | b',' | b'{' | b';')) + || [b"move".as_slice(), b"return", b"=>"].iter().any(|word| head.ends_with(word)); + if body[at] == b'|' && opens { + let Some(close) = body[at + 1..].iter().position(|&c| c == b'|').map(|p| at + 1 + p) else { return false }; + if binds(at + 1, close) { + return true; + } + at = close; + } + at += 1; + } + false +} + +/// Whether the attributes in `file.m[from..to]` include `#[ignore = "…"]` with a non-blank reason. +fn ignored_with_reason(file: &File, from: usize, to: usize) -> bool { + let m = &file.m; + words(m, b"ignore", from, to).into_iter().any(|at| { + let j = skip_ws(m, at + "ignore".len()); + m[..at].ends_with(b"#[") + && m.get(j) == Some(&b'=') + && ignore_reason(&file.src[skip_ws(m, j + 1)..]).is_some_and(|body| body.iter().any(|c| !c.is_ascii_whitespace())) + }) +} + +/// Whether the masked text prints: `println!`, `eprintln!`, `print!` or `eprint!`. +fn prints(m: &[u8], from: usize, to: usize) -> bool { + macro_calls(m, from, to).iter().any(|c| matches!(c.name.as_str(), "println" | "eprintln" | "print" | "eprint")) +} + /// Whether the attributes in `m[from..to]` include an applied `should_panic`: `#[should_panic]`, /// `#[should_panic(…)]`, or one inside `#[cfg_attr(test, …)]`. Another `cfg_attr` predicate may /// not hold, so it does not count. @@ -2029,7 +2285,233 @@ fn positive_all(cond: &str, test_body: &[u8], sizes: &Sizes) -> bool { let body = arg.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(arg, |(_, body)| body); let none_match = not_equal_conjunction(body); let (receiver, need) = receiver_need(&cond[..i], sizes); - !none_match && least_items(receiver, test_body, sizes) < need + // A parenthesized range of literals or constants: `(0..3).all(…)`. + let range = if receiver.starts_with('(') { expr_len(receiver, sizes, "") } else { 0 }; + let known = least_items(receiver, test_body, sizes).max(range); + !none_match && known < need && !(need == 1 && (pinned_source(receiver, test_body, sizes) || fixed_table_call(receiver, test_body, sizes))) + }) +} + +/// Whether an earlier equality assertion compares what `receiver` is made from with a non-empty +/// literal: a plain local whose binding reads `receiver` (`let got = r.items()….collect(); +/// assert_eq!(got, [a, b])` before `r.items().iter().all(…)`, with `got` unchanged in between), or +/// the same call `receiver` is bound to (`let gaps = gaps(&word); assert_eq!(gaps(&word), [a, b])`). +fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { + let r = array_receiver(receiver); + let init = |name: &str, at: usize| let_init(body, name, at).and_then(|(init, _)| init); + // For a receiver bound to `f(&x)`: the call `f(&x)`, `x`, and where the binding of `x` it reads ends. + let source = if plain_local(r) { + let_init(body, r, body.len()).and_then(|(init, bound)| { + let (text, _) = init?; + let s = single_local_arg(&text)?.to_owned(); + if binds(&body[bound..], s.as_bytes()) { + return None; + } + let at = let_init(body, &s, bound).map_or(0, |(_, at)| statement_end(body, at)); + Some((norm(text.as_bytes()), s, at)) + }) + } else { + None + }; + macro_calls(body, 0, body.len()).into_iter().any(|a| { + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) || a.args.len() < 2 || !body_level_statement(body, a.at) { + return false; + } + let (left, right) = (norm(&body[a.args[0].0..a.args[0].1]), norm(&body[a.args[1].0..a.args[1].1])); + [(&left, &right), (&right, &left)].into_iter().any(|(pinned, literal)| { + if literal_len(literal, sizes) == 0 { + return false; + } + // The binding keeps the receiver's items (`r.items().iter().map(…).collect()`), nothing + // changes the binding before the assertion, and nothing changes the receiver's source + // from the binding on. + let read = !plain_local(r) + && plain_local(pinned) + && init(pinned, a.at).is_some_and(|(text, at)| { + let bound = statement_end(body, at); + keeping_base(&text, true) == r + && !touched_after(&body[..a.at], pinned, bound, pinned) + && !touched_after(body, root_local(r), bound, r) + }); + // The assertion compares the same call the receiver is bound to (`gaps(&word)`), so its + // literal is what the receiver holds. + read || source.as_ref().is_some_and(|(call, s, at)| pinned == call && !touched_after(body, s, *at, r)) + }) + }) +} + +/// Whether an expression starts a statement of the test body or a plain nested block. +fn body_level_statement(body: &[u8], mut at: usize) -> bool { + while body[..at].trim_ascii_end().ends_with(b"::") { + at = body[..at].trim_ascii_end().len() - 2; + at = body[..at].trim_ascii_end().len(); + while at > 0 && is_ident(body[at - 1]) { + at -= 1; + } + } + let mut statement = true; + let mut i = 0; + while i < at { + match body[i] { + b'{' if statement => {} + b'(' | b'[' | b'{' => { + let Some(close) = matching(body, i).filter(|&close| close < at) else { return false }; + statement = body[i] == b'{'; + i = close + 1; + continue; + } + b';' | b'}' => statement = true, + c if c.is_ascii_whitespace() => {} + _ => statement = false, + } + i += 1; + } + statement +} + +/// The local a receiver path starts from: `r` of `r.items()`. +fn root_local(expr: &str) -> &str { + let end = expr.bytes().take_while(|&c| is_ident(c)).count(); + &expr[..end] +} + +/// Whether code after `from` uses `name` other than through a read-only use of `receiver`, a shared +/// borrow `&name` read in an assertion, or a getter named `len`, `is_empty` or +/// ending in `_count`. Other uses, including assertion arguments, may change what it holds. +/// A read bound to another local or passed to a call outside an assertion may give out an alias. +fn touched_after(body: &[u8], name: &str, from: usize, receiver: &str) -> bool { + if !plain_local(name) { + return true; + } + words(body, name.as_bytes(), from, body.len()).into_iter().any(|at| { + let rest = norm(&body[at..statement_end(body, at)]); + let head = body[..at].trim_ascii_end(); + // A shared borrow reads the value in an assertion or in the receiver's own binding; passed to + // a call elsewhere (`reset(&r);`, `let old = reset(&r);`), it may change what an + // interior-mutable value holds. + let statement = body[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let raw = body[statement..at].trim_ascii_start(); + let macro_name = &raw[..raw.iter().take_while(|&&c| is_ident(c)).count()]; + let assertion = raw.get(macro_name.len()) == Some(&b'!') + && PLAIN_ASSERTS.iter().any(|p| macro_name.strip_prefix(p.as_bytes()).is_some_and(|r| r.is_empty() || r.starts_with(b"_"))); + // The `let` that binds the receiver itself (`let gaps = gaps(&plain);`) reads its source. + let binds_receiver = raw + .strip_prefix(b"let") + .map(<[u8]>::trim_ascii_start) + .is_some_and(|r| r.starts_with(receiver.as_bytes()) && !r.get(receiver.len()).copied().is_some_and(is_ident)); + let shared = head.ends_with(b"&") && !head.ends_with(b"&&") && (assertion || binds_receiver); + let getter = rest + .strip_prefix(name) + .and_then(|r| r.strip_prefix('.')) + .and_then(|r| r.split_once('(')) + .is_some_and(|(method, _)| plain_local(method) && (matches!(method, "len" | "is_empty") || method.ends_with("_count"))); + let read = rest.strip_prefix(receiver).is_some_and(|tail| { + tail.is_empty() + || tail.starts_with([')', ']', '}', ',']) + || [".iter()", ".len()", ".is_empty()", ".first()", ".last()", ".get(", ".contains("].iter().any(|method| tail.starts_with(method)) + }); + let read_only = assertion || binds_receiver || body_level_statement(body, at); + !((read || getter) && read_only || shared) + }) +} + +/// The plain local of a call with one argument, `f(&x)` or `f(x)`. +fn single_local_arg(call: &str) -> Option<&str> { + let open = call.find('(')?; + let head = &call[..open]; + if head.is_empty() || !head.bytes().all(|c| is_ident(c) || c == b':') || matching(call.as_bytes(), open) != Some(call.len() - 1) { + return None; + } + let arg = &call[open + 1..call.len() - 1]; + let arg = arg.strip_prefix('&').unwrap_or(arg); + plain_local(arg).then_some(arg) +} + +/// Whether `receiver` calls a function of the file whose body lists every row of a non-empty +/// constant table of the file (`const TABLE: [T; 3]`, `TABLE.iter()…`) without filtering it: the +/// call gives at least one row whatever state the test builds. A filter, even one on plain values, +/// may drop every row, so it leaves the function out. +fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { + let r = array_receiver(receiver); + let Some(open) = r.find('(') else { return false }; + let name = &r[..open]; + if !plain_local(name) + || matching(r.as_bytes(), open) != Some(r.len() - 1) + || let_binds(test_body, name.as_bytes()) + || binds_parameter(test_body, name.as_bytes()) + { + return false; + } + let file = sizes.file; + let defs: Vec = words(file, name.as_bytes(), 0, file.len()) + .into_iter() + .filter(|&at| { + let head = file[..at].trim_ascii_end(); + head.ends_with(b"fn") && !(head.len() > 2 && is_ident(head[head.len() - 3])) + }) + .collect(); + // Functions of one name in several modules: the call may reach any of them, so every one has + // to list the table. + if defs.is_empty() { + return false; + } + defs.into_iter().all(|at| { + let head = file[..at].trim_ascii_end(); + let Some((_, _, body_open, body_close)) = item_at(file, head.len() - 2) else { return false }; + let params_open = skip_ws(file, at + name.len()); + let Some(params_close) = (file.get(params_open) == Some(&b'(')).then(|| matching(file, params_open)).flatten() else { return false }; + let signature = norm(&file[params_close + 1..body_open]); + let return_type = signature.strip_prefix("->").unwrap_or(""); + let body = norm(&file[body_open + 1..body_close]); + let table_end = body.bytes().take_while(|&c| is_ident(c) || c == b':').count(); + let table = &body[..table_end]; + let screaming = !table.is_empty() && table.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_'); + if !screaming || item_len(table, sizes) == 0 || !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()")) { + return false; + } + // The body is the chain alone, of steps that keep every row. + let mut at = table_end; + while at < body.len() { + let Some(rest) = body[at..].strip_prefix('.') else { return false }; + let method_len = rest.bytes().take_while(|&c| is_ident(c)).count(); + let method = &rest[..method_len]; + let mut open = at + 1 + method_len; + let mut target = None; + if method == "collect" && body[open..].starts_with("::<") { + let Some(close) = body[open..].find(">(") else { return false }; + target = Some(&body[open + 3..open + close]); + open += close + 1; + } + let Some(close) = (body.as_bytes().get(open) == Some(&b'(')).then(|| matching(body.as_bytes(), open)).flatten() else { return false }; + match method { + "iter" | "into_iter" | "map" | "copied" | "cloned" | "enumerate" | "rev" => {} + "collect" => { + if !known_collection(target.unwrap_or(if close + 1 == body.len() { return_type } else { "" })) { + return false; + } + } + _ => return false, + } + at = close + 1; + } + true + }) +} + +/// Whether a `let` pattern in masked `body` contains `name` as a whole word. +fn let_binds(body: &[u8], name: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let start = at + 3; + let mut end = start; + while end < body.len() { + if matches!(body[end], b'=' | b';') + || (body[end..].starts_with(b"else") && !is_ident(body[end - 1]) && !body.get(end + 4).copied().is_some_and(is_ident)) + { + break; + } + end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 }; + } + !words(body, name, start, end).is_empty() }) } @@ -2907,7 +3389,7 @@ fn strip_stream_configuration(body: &mut [u8]) { } fn no_assertion(v: &View) -> Option { - if v.checks || v.delegates || v.should_panic { + if v.checks || v.delegates || v.should_panic || v.diagnostic { return None; } Some(v.whole(Rule::NoAssertion, "no assertion and no asserting helper".into())) @@ -7307,4 +7789,264 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } + + #[test] + fn a_files_own_helper_decides_over_one_of_the_same_name_in_another_file() { + let own = "fn near(a: f64) { assert!(a < 1.0); }\n#[test]\nfn t() {\n near(f());\n}\n"; + let other = "fn near(a: f64) -> bool { a < 1.0 }\n#[test]\nfn u() {\n assert!(near(f()));\n}\n"; + let caller = "#[test]\nfn v() {\n near(f());\n}\n"; + let files = [ + ("crates/x/tests/it/own.rs".to_owned(), own.to_owned()), + ("crates/x/tests/it/other.rs".to_owned(), other.to_owned()), + ("crates/x/tests/it/caller.rs".to_owned(), caller.to_owned()), + ]; + let ctx = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/tests/it/own.rs", own, &ctx), [], "the file's own near asserts"); + let qualified = own.replace(" near(f());", " other::near(f());"); + let files = [files[0].clone(), files[1].clone(), ("crates/x/tests/it/q.rs".to_owned(), qualified.clone())]; + let ctx_q = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/q.rs", &qualified, &ctx_q), + [(3, "no-assertion")], + "a call with a path may reach the other file's near" + ); + assert_eq!( + hits_in("crates/x/tests/it/caller.rs", caller, &ctx), + [(2, "no-assertion")], + "a file that defines none cannot tell which it reaches" + ); + let nested = "mod a {\n fn near(a: f64) { assert!(a < 1.0); }\n}\nuse other::*;\n#[test]\nfn t() {\n near(f());\n}\n"; + let files = [("crates/x/tests/it/nested.rs".to_owned(), nested.to_owned()), files[1].clone()]; + let ctx_nested = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/nested.rs", nested, &ctx_nested), + [(6, "no-assertion")], + "a helper inside an inline module does not decide for the file's top-level call" + ); + let inner = + "fn near(a: f64) { assert!(a < 1.0); }\nmod inner {\n use super::other::*;\n #[test]\n fn t() {\n near(f());\n }\n}\n"; + let files = [("crates/x/tests/it/inner.rs".to_owned(), inner.to_owned()), files[1].clone()]; + let ctx_inner = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/inner.rs", inner, &ctx_inner), + [(5, "no-assertion")], + "a test inside an inline module may import the other file's near" + ); + let local = "#[test]\nfn t() {\n fn near(a: f64) { assert!(a < 1.0); }\n assert!(f());\n}\n#[test]\nfn u() {\n near(f());\n}\n"; + let files = [("crates/x/tests/it/local.rs".to_owned(), local.to_owned()), files[1].clone()]; + let ctx_local = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/local.rs", local, &ctx_local), + [(7, "no-assertion")], + "a helper inside a test does not decide for another test's call" + ); + } + + #[test] + fn a_test_body_passed_to_a_wrapper_counts_as_its_check() { + let src = "fn keeping(test: fn()) {\n test();\n}\nfn body() {\n assert_eq!(f(), 1);\n}\n#[test]\nfn t() {\n keeping(body);\n}\n"; + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), src.to_owned())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), []); + let wrapper = src.replace(" keeping(body);", " wrapper();") + "fn wrapper() {\n keeping(body);\n}\n"; + let wrapper_ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), wrapper.clone())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &wrapper, &wrapper_ctx), []); + let shadowed_wrapper = wrapper.replace(" keeping(body);", " let body = || {};\n keeping(body);"); + let shadowed_wrapper_ctx = + Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), shadowed_wrapper.clone())]), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/src/tests.rs", &shadowed_wrapper, &shadowed_wrapper_ctx), + [(8, "no-assertion")], + "a local binding in a wrapper shadows the asserting helper" + ); + let shadowed = src.replace(" keeping(body);", " let body = || {};\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &shadowed, &ctx), [(8, "no-assertion")], "a local binding shadows the asserting helper"); + let destructured = src.replace(" keeping(body);", " let (body,) = (|| {},);\n keeping(body);"); + assert_eq!( + hits_in("crates/x/src/tests.rs", &destructured, &ctx), + [(8, "no-assertion")], + "a destructured binding shadows the asserting helper" + ); + let closure = src.replace(" keeping(body);", " keeping(|body| keeping(body));"); + assert_eq!(hits_in("crates/x/src/tests.rs", &closure, &ctx), [(8, "no-assertion")], "a closure parameter shadows the asserting helper"); + let block_closure = src.replace(" keeping(body);", " let _cb = |body: fn()| { drop(body); };\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &block_closure, &ctx), [], "a closure parameter's scope ends with the closure"); + let expr_closure = src.replace(" keeping(body);", " let _cb = |body: fn()| drop(body);\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &expr_closure, &ctx), [], "an expression closure's scope ends at its semicolon"); + let inner = src.replace(" keeping(body);", " let _cb = |body: fn()| { keeping(body); };"); + assert_eq!(hits_in("crates/x/src/tests.rs", &inner, &ctx), [(8, "no-assertion")], "the parameter inside its closure"); + let parameter = src.replace("fn t()", "fn t(body: fn())"); + assert_eq!(hits_in("crates/x/src/tests.rs", ¶meter, &ctx), [(8, "no-assertion")], "a function parameter shadows the asserting helper"); + let later = src.replace(" keeping(body);", " keeping(body);\n {\n let body = || {};\n let _ = body;\n }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &later, &ctx), [], "a binding in a later block does not reach the call"); + let after = src.replace(" keeping(body);", " keeping(body);\n let body = || {};\n let _ = body;"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after, &ctx), [], "a binding after the call"); + let looped = src.replace(" keeping(body);", " for body in [|| {}] {\n keeping(body);\n }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &looped, &ctx), [(8, "no-assertion")], "a loop pattern shadows the helper in the loop body"); + let after_loop = src.replace(" keeping(body);", " for body in [|| {}] {\n let _ = body;\n }\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after_loop, &ctx), [], "the helper after the loop"); + let unused = src.replace(" keeping(body);", " let _unused = (body,);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &unused, &ctx), [(8, "no-assertion")], "a tuple that is never called"); + let dropped = src.replace(" keeping(body);", " (body,);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &dropped, &ctx), [(8, "no-assertion")], "a tuple in a statement of its own"); + let table = src.replace(" keeping(body);", " let cases = [(\"case\", body)];\n run(&cases);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &table, &ctx), [], "a table of named cases"); + let idle = src.replace("assert_eq!(f(), 1);", "f();"); + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), idle.clone())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &idle, &ctx), [(8, "no-assertion")], "a passed body that checks nothing"); + } + + #[test] + fn a_match_arm_binding_shadows_a_helper_only_in_its_arm() { + let src = "fn body() { assert_eq!(f(), 1); }\n#[test]\nfn t() {\n match Some(|| {}) { Some(body) => keeping(body), None => () }\n}\n"; + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), src.to_owned())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [(3, "no-assertion")], "a match-arm pattern shadows the helper"); + let after = src.replace("None => () }", "None => () }\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after, &ctx), [], "the helper after the match"); + } + + #[test] + fn a_dropped_helper_value_is_not_a_check() { + let src = "fn keeping(test: fn()) {\n test();\n}\nfn body() {\n assert_eq!(f(), 1);\n}\n#[test]\nfn t() {\n keeping(body);\n}\n"; + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), src.to_owned())]), ..Ctx::default() }; + let stored = src.replace(" keeping(body);", " let _unused = Some(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &stored, &ctx), [(8, "no-assertion")], "a constructor only stores the helper"); + let boxed = src.replace(" keeping(body);", " let _ = Box::new(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &boxed, &ctx), [(8, "no-assertion")], "a boxed helper that is dropped"); + let called = src.replace(" keeping(body);", " let _ = keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &called, &ctx), [], "a call runs even when its result is dropped"); + let dropped = src.replace(" keeping(body);", " drop(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &dropped, &ctx), [(8, "no-assertion")], "a dropped callback"); + for call in ["std::mem::drop", "mem::drop", "forget", "std::mem::forget", "mem::forget"] { + let forgotten = src.replace(" keeping(body);", &format!(" {call}(body);")); + assert_eq!(hits_in("crates/x/src/tests.rs", &forgotten, &ctx), [(8, "no-assertion")], "a discarded callback: {call}"); + } + for value in ["[body]", "Some(body)"] { + let dropped = src.replace(" keeping(body);", &format!(" drop({value});")); + assert_eq!(hits_in("crates/x/src/tests.rs", &dropped, &ctx), [(8, "no-assertion")], "a discarded stored callback: {value}"); + } + let constructed = src.replace(" keeping(body);", " run(Some(body));"); + assert_eq!(hits_in("crates/x/src/tests.rs", &constructed, &ctx), [], "a stored callback passed to a call"); + let passed = src.replace(" keeping(body);", " run(&[body]);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &passed, &ctx), [], "an array passed to a call"); + let array = src.replace(" keeping(body);", " [body];"); + assert_eq!(hits_in("crates/x/src/tests.rs", &array, &ctx), [(8, "no-assertion")], "a discarded array"); + for value in ["[body]", "[body, other]", "&[body]", "vec![body]"] { + let passed = src.replace(" keeping(body);", &format!(" run({value});")); + assert_eq!(hits_in("crates/x/src/tests.rs", &passed, &ctx), [], "an array argument: {value}"); + let kept = src.replace(" keeping(body);", &format!(" let cases = {value};\n run(cases);")); + assert_eq!(hits_in("crates/x/src/tests.rs", &kept, &ctx), [], "a kept array: {value}"); + let unused = src.replace(" keeping(body);", &format!(" let _ = {value};")); + assert_eq!(hits_in("crates/x/src/tests.rs", &unused, &ctx), [(8, "no-assertion")], "an unused array: {value}"); + } + } + + #[test] + fn a_pin_counts_only_when_its_assertion_runs_and_no_alias_changes_the_source() { + let pinned = "#[test]\nfn t() {\n let got: Vec = r.items().iter().map(|j| j.n).collect();\n assert_eq!(got, vec![1, 2]);\n assert!(r.items().iter().all(|j| j.ok));\n}\n"; + for assertion in ["std::assert_eq!(got, vec![1, 2]);", "core::assert_eq!(got, vec![1, 2]);"] { + let qualified = pinned.replace("assert_eq!(got, vec![1, 2]);", assertion); + assert_eq!(hits(&qualified), [], "{assertion}"); + } + for assertion in [ + "let _check = || assert_eq!(got, vec![1]);", + "if ready { assert_eq!(got, vec![1]); }", + "match ready { true => assert_eq!(got, vec![1]), false => () }", + "while ready { assert_eq!(got, vec![1]); }", + "for _ in rounds { assert_eq!(got, vec![1]); }", + ] { + let conditional = pinned.replace("assert_eq!(got, vec![1, 2]);", assertion); + assert_eq!(only("all-unguarded", &conditional), [(5, "all-unguarded")], "{assertion}"); + } + let block = pinned.replace("assert_eq!(got, vec![1, 2]);", "{ { assert_eq!(got, vec![1]); } }"); + assert_eq!(hits(&block), [], "a plain nested block runs its assertion"); + let after_branch = pinned.replace(" assert_eq!(got", " if ready {} else {}\n assert_eq!(got"); + assert_eq!(hits(&after_branch), [], "an earlier branch does not contain the pinning assertion"); + for change in ["let items = r.items(); items.clear();", "let (items,) = (r.items(),); items.clear();", "clear(r.items());"] { + let aliased = pinned.replace(" assert!(r.items()", &format!(" {change}\n assert!(r.items()")); + assert_eq!(only("all-unguarded", &aliased), [(6, "all-unguarded")], "{change}"); + } + let read = pinned.replace(" assert!(r.items()", " r.items();\n assert!(r.items()"); + assert_eq!(hits(&read), [], "a standalone getter read preserves the pinned source"); + } + + #[test] + fn all_over_a_literal_range_or_a_pinned_source_is_guarded() { + let range = "#[test]\nfn t() {\n assert!((0..3).all(|i| a[i] == b[i]));\n}\n"; + assert_eq!(hits(range), []); + assert_eq!(hits(&range.replace("(0..3)", "(0..n)")), [(3, "all-unguarded")], "a range whose end the test does not show"); + let pinned = "#[test]\nfn t() {\n let got: Vec = r.items().iter().map(|j| j.n).collect();\n assert_eq!(got, vec![1, 2]);\n assert!(r.items().iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(pinned), []); + assert_eq!(hits(&pinned.replace("vec![1, 2]", "vec![]")), [(5, "all-unguarded")], "pinned to an empty list"); + assert_eq!(hits(&pinned.replace("= r.items()", "= other.items()")), [(5, "all-unguarded")], "a list made from another receiver"); + let shadowed = "#[test]\nfn t() {\n let got = f();\n assert_eq!(got, vec![1]);\n let got: Vec = r.items().iter().map(|j| j.n).collect();\n assert!(r.items().iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(shadowed), [(6, "all-unguarded")], "the pinned binding is not the one made from the receiver"); + let cleared = pinned.replace(" assert!(r.items()", " r.clear();\n assert!(r.items()"); + assert_eq!(hits(&cleared), [(6, "all-unguarded")], "the receiver changed after the assertion"); + let cleared_items = pinned.replace(" assert!(r.items()", " r.items().clear();\n assert!(r.items()"); + assert_eq!(hits(&cleared_items), [(6, "all-unguarded")], "the receiver's items changed after the assertion"); + let early = pinned.replace(" assert_eq!(got", " r.clear();\n assert_eq!(got"); + assert_eq!(hits(&early), [(6, "all-unguarded")], "the receiver changed between the binding and the assertion"); + let taken = pinned.replace(" assert!(r.items()", " assert!(r.take_items().is_some());\n assert!(r.items()"); + assert_eq!(hits(&taken), [(6, "all-unguarded")], "an assertion changes the receiver after the pinning assertion"); + let reset = pinned.replace(" assert!(r.items()", " reset(&r);\n assert!(r.items()"); + assert_eq!(hits(&reset), [(6, "all-unguarded")], "a shared borrow passed to a call may change interior-mutable items"); + let bound = pinned.replace(" assert!(r.items()", " let n = count(&r);\n assert!(r.items()"); + assert_eq!(hits(&bound), [(6, "all-unguarded")], "a call whose result is bound may still change interior-mutable items"); + let asserted = pinned.replace(" assert!(r.items()", " assert!(count(&r) > 0);\n assert!(r.items()"); + assert_eq!(hits(&asserted), [], "a shared borrow read in an assertion"); + let counted = pinned.replace(" assert!(r.items()", " assert_eq!(r.unhandled_rejection_count(), 2);\n assert!(r.items()"); + assert_eq!(hits(&counted), [], "a count getter preserves the pinned source"); + let chained = pinned.replace(".map(|j| j.n)", ".map(|j| j.n).chain([1])"); + assert_eq!(hits(&chained), [(5, "all-unguarded")], "a list that is not empty without the receiver's items"); + let reassigned = pinned.replace(" assert_eq!(got", " got = vec![1, 2];\n assert_eq!(got"); + assert_eq!(hits(&reassigned), [(6, "all-unguarded")], "the snapshot was replaced before the assertion"); + let pushed = pinned.replace(" assert_eq!(got", " got.push(1);\n assert_eq!(got"); + assert_eq!(hits(&pushed), [(6, "all-unguarded")], "the snapshot changed before the assertion"); + let read_first = pinned.replace(" assert_eq!(got", " assert!(got.len() < 9);\n assert_eq!(got"); + assert_eq!(hits(&read_first), [], "a read of the snapshot before the assertion"); + let word = "#[test]\nfn t() {\n let plain = word();\n assert_eq!(gaps(&plain), [0.0, 0.0]);\n let gaps = gaps(&plain);\n assert!(gaps.iter().all(|g| g.abs() < 1e-6));\n}\n"; + assert_eq!(hits(word), []); + assert_eq!(hits(&word.replace("gaps(&plain), [", "gaps(&other), [")), [(6, "all-unguarded")], "a literal about another value"); + assert_eq!(hits(&word.replace("gaps(&plain), [", "ids(&plain), [")), [(6, "all-unguarded")], "a literal about another call on the value"); + let emptied = word.replace(" let gaps = gaps(&plain);\n", " let mut gaps = gaps(&plain);\n gaps.clear();\n"); + assert_eq!(hits(&emptied), [(7, "all-unguarded")], "a receiver that may change after its binding"); + let rebound = word.replace(" assert_eq!(gaps(&plain), [0.0, 0.0]);\n", "").replace( + " let gaps = gaps(&plain);", + " let gaps = gaps(&plain);\n let plain = other();\n assert_eq!(gaps(&plain), [0.0, 0.0]);", + ); + assert_eq!(hits(&rebound), [(7, "all-unguarded")], "the assertion reads a later binding of the source"); + } + + #[test] + fn all_over_every_row_of_a_constant_table_is_guarded() { + let src = "const TABLE: [u8; 2] = [1, 2];\nfn reasons(app: &App, key: u8) -> Vec> {\n TABLE.iter().map(|r| app.reason(r, key)).collect()\n}\n#[test]\nfn t() {\n let app = App::new();\n assert!(reasons(&app, 2).iter().all(|r| r.is_none()));\n}\n"; + assert_eq!(hits(src), []); + let shadowed = src.replace(" assert!", " let reasons = |_: &App, _: u8| Vec::>::new();\n assert!"); + assert_eq!(hits(&shadowed), [(9, "all-unguarded")], "a local binding shadows the file's function"); + let twice = format!("{src}mod other {{\n fn reasons(_: &App, _: u8) -> Vec> {{\n Vec::new()\n }}\n}}\n"); + assert_eq!(hits(&twice), [(8, "all-unguarded")], "another module defines a function of the same name"); + let keyed = src.replace(".map(|r|", ".filter(|r| **r == key).map(|r|"); + assert_eq!(hits(&keyed), [(8, "all-unguarded")], "a filter on a plain value may drop every row"); + let state = src.replace(".map(|r|", ".filter(|r| app.has(r)).map(|r|"); + assert_eq!(hits(&state), [(8, "all-unguarded")], "a filter on the state the test builds"); + let empty = src.replace("[u8; 2] = [1, 2]", "[u8; 0] = []"); + assert_eq!(hits(&empty), [(8, "all-unguarded")], "an empty table"); + let elsewhere = src.replace("const TABLE: [u8; 2] = [1, 2];\n", ""); + assert_eq!(hits(&elsewhere), [(7, "all-unguarded")], "a table whose length the file does not show"); + let map_while = src.replace(".map(|r| app.reason(r, key))", ".map_while(|r| app.reason(r, key))"); + assert_eq!(hits(&map_while), [(8, "all-unguarded")], "another step that drops rows"); + let optional = src + .replace("-> Vec>", "-> Option>>") + .replace(".map(|r| app.reason(r, key))", ".map(|r| Some(app.reason(r, key)))") + .replace(".all(|r| r.is_none())", ".all(|r| r.len() == 1)"); + assert_eq!(hits(&optional), [(8, "all-unguarded")], "collecting into an option can discard every row"); + } + + #[test] + fn an_ignored_diagnostic_that_prints_needs_no_assertion() { + let diagnostic = "#[test]\n#[ignore = \"manual timing\"]\nfn t() {\n let n = f();\n eprintln!(\"{n:?}\");\n}\n"; + assert_eq!(hits(diagnostic), []); + assert_eq!(hits(&diagnostic.replace(" eprintln!(\"{n:?}\");\n", "")), [(3, "no-assertion")], "an ignored test that prints nothing"); + assert_eq!(hits(&diagnostic.replace("#[ignore = \"manual timing\"]\n", "")), [(2, "no-assertion")], "a test that runs and only prints"); + } }