diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 0e17e13a13..8aab64ef85 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -3,8 +3,11 @@ //! Rules, checked in `#[test]` functions (and `#[tokio::test]`, `#[test_case]`, //! `#[wasm_bindgen_test]`, and `#[test]` inside `proptest!`): //! * `all-unguarded`: `assert!(….all(…))` in a test that neither checks a length, emptiness, -//! count, first item or `any` in an assertion's condition or compared operands, nor takes a -//! first item by indexing, unwrapping or a panicking `let … else`: `.all()` is true for an empty +//! count, first item or `any` in an assertion's condition or compared operands (a check of a +//! plain local, such as `xs.len()`, counts for an `.all(…)` only when no code between them may +//! shrink or replace that local), nor takes an +//! item by a numeric index (not one it then iterates), or a first item by unwrapping or a +//! panicking `let … else`: `.all()` is true for an empty //! collection (negated `.all(…)`, including `== false`, and predicates saying that no item //! matches, with whole negations or `!=` comparisons joined only by `&&`, are left out). An earlier //! `assert_eq!`, `debug_assert_eq!` or `prop_assert_eq!` comparing a plain local receiver @@ -19,7 +22,8 @@ //! 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; +//! receiver, or the call the receiver is bound to), when nothing changes the source or a local +//! the receiver passes as a selector (`r.items(active)`) 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 @@ -66,9 +70,12 @@ //! arithmetic on both sides and two reads that differ only in the entry they name (a string or //! integer literal, a local or an indexed element); //! * `constant-echo`: every assertion of the test compares only constants, literals and enum -//! variants; +//! variants, without arithmetic or bitwise operators on user values; //! * `fixture-only`: every assertion reads only constants, literals and immutable locals of the //! test bound (in scope) to such values, so nothing the code under test returned is checked; +//! `into`, and a method such as `to_string` on a value of a type the test names (`Input { n: 5 }`), +//! run code of that type and do not count as reading a fixture. Arithmetic and bitwise operators +//! on user values or containers holding them also run code under test; //! * `never-run`: a test that the `cfg` attributes on it, on the items around it or on the `mod` //! declarations above its file leave out of every target CI runs tests on (Linux and FreeBSD on //! x86_64, and Windows for the app and the UI crate's print tests). A test that still builds on @@ -95,7 +102,7 @@ //! merge commit is checked out, and a shallow checkout fetches that parent); elsewhere the merge //! base of `HEAD` and `upstream/main` or `origin/main`. Uncommitted and untracked files count as //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the -//! workspace by crate and rule, and does not fail. +//! workspace by crate and rule, and the hits do not make it fail. use std::cell::{OnceCell, RefCell}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; @@ -248,7 +255,8 @@ pub struct Hit { pub note: String, /// The first and last line of what the hit covers: the test, from its attribute to its closing /// brace, for a rule about a whole test or `all-unguarded`, through the second operand for - /// `self-compare`, through the variable's name for `env-gate-unset`, through the attribute's + /// `self-compare` and `mirror`, through the compared operand or condition for `exact-pixel`, + /// through the variable's name for `env-gate-unset`, through the attribute's /// `]` for `ignore-without-reason`, through the call's `)` for `reads-source`, else `line`. This span /// controls changed-line detection; `all-unguarded` and `self-compare` exemptions still apply /// only near `line`. @@ -374,7 +382,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; // The gates the parent declarations gave at the base: a parent edit counts against a child's - // test only when the test ran in CI before it. + // test when it becomes newly off or moves from report-only to failing. let base_gates = module_gates(&gated, &read_base, &base_overrides); let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; @@ -415,12 +423,13 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } /// Whether `base`, the hits of `base_src` under the base's gates, has a `never-run` hit for the test -/// of `hit` in `src`. A test is matched by its name, the inline modules around it and its place -/// among the tests of that name in those modules, so lines that moved still match and tests of one -/// name in different inline modules stay apart, even when a change removes one of the modules. +/// of `hit` in `src` that was failing too, unless `hit` is report-only. A test is matched by its name, +/// the inline modules around it and its place among the tests of that name in those modules, so +/// lines that moved still match and tests of one name in different inline modules stay apart, even +/// when a change removes one of the modules. fn already_off(base: &[Hit], base_src: &str, src: &str, hit: &Hit) -> bool { let place = test_place(src, &hit.test, hit.line); - base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test).any(|h| match &place { + base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test && (h.fails() || hit.report_only)).any(|h| match &place { Some(place) => test_place(base_src, &h.test, h.line).as_ref() == Some(place), None => h.line == hit.line, }) @@ -662,6 +671,15 @@ fn read_git_blob(root: &Path, rev: &str, path: &str, limit: u64) -> Option Option { + let size = |spec: &str| git(root, &["cat-file", "-s", spec]).ok()?.parse().ok(); + read_blob(rev, path, limit, size, |spec| { + let out = Command::new("git").current_dir(root).args(["cat-file", "blob", spec]).output().ok()?; + out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned()) + }) +} + fn read_base_blob(root: &Path, rev: &str, path: &str, limit: u64, sizes: Option<&HashMap>) -> Option { match sizes.and_then(|sizes| sizes.get(path)).copied() { Some(size) => read_blob(rev, path, limit, |_| Some(size), |spec| git(root, &["show", spec]).ok()), @@ -749,6 +767,9 @@ fn changed_lines(root: &Path, base: &str) -> Result Result>>> = RefCell::default(); + let can_change_test = |path: &str, line: usize| { + let mut cache = test_lines.borrow_mut(); + let lines = + cache.entry(path.to_owned()).or_insert_with(|| read_git_blob_verbatim(root, base, path, MAX_FILE).map(|src| lines_affecting_tests(&src))); + lines.as_ref().is_none_or(|l| l.contains(&line)) + }; + let mut out = parse_diff(&diff, &can_change_test); for path in git(root, &["ls-files", "-z", "--others", "--exclude-standard", "--", "*.rs"])?.split('\0').filter(|p| !p.is_empty()) { out.insert(path.to_owned(), None); } @@ -766,14 +796,34 @@ fn changed_lines(root: &Path, base: &str) -> Result BTreeMap>> { +/// line, or just line 1 when the anchor is 0, unless it deletes only blank lines and line comments +/// ([`inert_deleted_line`]) that `can_change_test(path, old line)` places outside literals and tests. +fn parse_diff(diff: &str, can_change_test: &dyn Fn(&str, usize) -> bool) -> BTreeMap>> { let mut out: BTreeMap>> = BTreeMap::new(); let mut current: Option = None; // Inside a file's header (from `diff --git` to its first hunk), where `+++ ` names the file. let (mut header, mut new_file) = (false, false); let mut old: Option = None; + // The pure deletion being read: its anchor, whether a deleted line so far can change code, and + // the old line number of the next deleted line. + let mut deletion: Option<(usize, bool, usize)> = None; + let flush = |deletion: &mut Option<(usize, bool, usize)>, current: &Option, out: &mut BTreeMap>>| { + if let (Some((start, true, _)), Some(Some(lines))) = (deletion.take(), current.as_ref().and_then(|p| out.get_mut(p))) { + lines.extend(start.max(1)..=start.saturating_add(1)); + } + }; for line in diff.lines() { + if let (Some((_, significant, old_line)), false, Some(path)) = (deletion.as_mut(), header, current.as_deref()) { + if let Some(deleted) = line.strip_prefix('-') { + *significant |= !inert_deleted_line(deleted) || can_change_test(path, *old_line); + *old_line += 1; + continue; + } + if line.starts_with('\\') { + continue; + } + } + flush(&mut deletion, ¤t, &mut out); if line.starts_with("diff --git ") { (header, new_file, old) = (true, false, None); } else if header && line.starts_with("new file mode") { @@ -792,16 +842,58 @@ fn parse_diff(diff: &str) -> BTreeMap>> { header = false; if let (Some((start, count)), Some(Some(lines))) = (hunk_range(hunk), out.get_mut(path)) { if count == 0 { - lines.extend(start.max(1)..=start.saturating_add(1)); + deletion = Some((start, false, hunk_old_start(hunk).unwrap_or(0))); } else { lines.extend(start..start + count); } } } } + flush(&mut deletion, ¤t, &mut out); out } +/// The first old line of a hunk header's `-a,b +c,d @@`. +fn hunk_old_start(hunk: &str) -> Option { + let old = hunk.split_whitespace().find(|w| w.starts_with('-'))?.trim_start_matches('-'); + old.split(',').next()?.parse().ok() +} + +/// Base lines where deleting a blank line or comment can change a test finding. +fn lines_affecting_tests(src: &str) -> BTreeSet { + let mut out = lines_in_literals(src); + let lines = Lines::new(src); + for test in tests_in(&mask(src)) { + out.extend(lines.of(test.attr)..=lines.of(test.close)); + } + out +} + +/// The 1-based lines of `src` that start inside a string or character literal, where a blank line +/// or a `//` line is part of the literal's value. +fn lines_in_literals(src: &str) -> BTreeSet { + // A marker byte at the start of each line stays in the masked text outside literals and is + // blanked inside one. + let marked: String = src.split('\n').map(|l| format!("\u{1}{l}")).collect::>().join("\n"); + let m = mask_parts(&marked, false, true); + let mut out = BTreeSet::new(); + let mut at = 0; + for (n, l) in marked.split('\n').enumerate() { + if m.get(at) == Some(&b' ') { + out.insert(n + 1); + } + at += l.len() + 1; + } + out +} + +/// Whether a deleted line outside tests and literals can be ignored: a blank line, or a line +/// comment that is not a `test-lint: allow` marker and does not open or close a block comment. +fn inert_deleted_line(line: &str) -> bool { + let t = line.trim(); + t.is_empty() || (t.starts_with("//") && !t.contains(ALLOW.trim_end()) && !t.contains("/*") && !t.contains("*/")) +} + /// The path in a `+++ ` label: git ends a label that contains a space with a tab, and writes a /// path with a quote, a backslash or a control character as a C-style quoted string. fn patch_path(label: &str) -> Option { @@ -870,20 +962,87 @@ fn upper_words(text: &str) -> impl Iterator + '_ { let start = line.trim_start().strip_prefix("- ").unwrap_or(line.trim_start()).trim_start(); let mapping = start.split_once(':').filter(|(name, rest)| env_assignment_name(name) && (rest.is_empty() || rest.starts_with(char::is_whitespace))); + let shell = workflow_scalar(start).unwrap_or_else(|| line.to_owned()); + let code = shell_code(&shell); + let line = code.as_str(); let assignments = line.match_indices('=').filter_map(move |(at, _)| { let name = line[..at].rsplit(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')).next().unwrap_or_default(); let from = at - name.len(); - let boundary = from == 0 || line.as_bytes().get(from - 1).is_some_and(|c| c.is_ascii_whitespace() || matches!(c, b'\'' | b'"' | b';')); + let word_start = |p: usize| p == 0 || line.as_bytes().get(p - 1).is_some_and(|c| c.is_ascii_whitespace() || *c == b';'); + // Inside quotes, only a quote that opens a whole word right before the name starts + // an assignment, not one inside a value (`m="NAME=x"`). + let boundary = match open_quote(line, from) { + None => word_start(from), + Some(q) => q + 1 == from && word_start(q), + }; (boundary && env_assignment_name(name) && !line[at + 1..].starts_with(['=', '>']) && !printed(line, from)).then(|| name.to_owned()) }); - mapping.map(|(name, _)| name.to_owned()).into_iter().chain(assignments) + mapping.map(|(name, _)| name.to_owned()).into_iter().chain(assignments).collect::>() }) } +/// Decodes a quoted YAML `run` value so shell quote checks see the command itself. +fn workflow_scalar(line: &str) -> Option { + let (key, value) = line.split_once(':')?; + if key != "run" || !value.starts_with(char::is_whitespace) { + return None; + } + let value = value.trim(); + if let Some(value) = value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')) { + return Some(value.replace("''", "'")); + } + let value = value.strip_prefix('"')?.strip_suffix('"')?; + let mut out = String::new(); + let mut chars = value.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + out.push(match chars.next()? { + '0' => '\0', + 'a' => '\u{7}', + 'b' => '\u{8}', + 't' | '\t' => '\t', + 'n' => '\n', + 'v' => '\u{b}', + 'f' => '\u{c}', + 'r' => '\r', + 'e' => '\u{1b}', + 'N' => '\u{85}', + '_' => '\u{a0}', + 'L' => '\u{2028}', + 'P' => '\u{2029}', + c @ (' ' | '"' | '/' | '\\') => c, + c @ ('x' | 'u' | 'U') => { + let width = match c { + 'x' => 2, + 'u' => 4, + _ => 8, + }; + let hex: String = chars.by_ref().take(width).collect(); + if hex.len() != width { + return None; + } + char::from_u32(u32::from_str_radix(&hex, 16).ok()?)? + } + _ => return None, + }); + } + Some(out) +} + /// Whether the text at `from` is an argument of `echo` or `printf` in its shell command, on a line /// that does not write to `$GITHUB_ENV`. fn printed(line: &str, from: usize) -> bool { - let command = line[..from].rsplit([';', '&', '|']).next().unwrap_or_default().as_bytes(); + // A line break ends the command unless a backslash continues it. + let head = &line[..from]; + let cut = head + .char_indices() + .rev() + .find(|&(i, c)| matches!(c, ';' | '&' | '|') || (c == '\n' && !head[..i].ends_with('\\'))) + .map_or(0, |(i, c)| i + c.len_utf8()); + let command = &head.as_bytes()[cut..]; let prints = ["echo", "printf"].iter().any(|w| !words(command, w.as_bytes(), 0, command.len()).is_empty()); prints && !line.contains("GITHUB_ENV") } @@ -892,6 +1051,24 @@ fn env_assignment_name(name: &str) -> bool { name.starts_with(|c: char| c.is_ascii_uppercase()) && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_') } +/// The offset of the quote that is still open at `at` in a workflow line, read as +/// [`workflow_code`] reads quotes. +fn open_quote(line: &str, at: usize) -> Option { + let (mut quote, mut escaped) = (None, false); + for (i, c) in line[..at].char_indices() { + if escaped { + escaped = false; + } else if c == '\\' && quote.is_none_or(|(q, _)| q != '\'') { + escaped = true; + } else if quote.is_some_and(|(q, _)| q == c) { + quote = None; + } else if quote.is_none() && matches!(c, '\'' | '"') { + quote = Some((c, i)); + } + } + quote.map(|(_, i)| i) +} + /// Removes comment text outside quotes from a workflow line. fn workflow_code(line: &str) -> &str { let (mut quote, mut escaped) = (None, false); @@ -913,6 +1090,33 @@ fn workflow_code(line: &str) -> &str { line } +/// Removes comment text outside quotes from a shell script that can hold several lines (a decoded +/// `run` value): each comment ends at its line break, and quotes stay open across line breaks. +fn shell_code(script: &str) -> String { + let (mut out, mut quote, mut escaped, mut comment) = (String::with_capacity(script.len()), None, false, false); + for c in script.chars() { + if comment { + comment = c != '\n'; + } else if escaped { + escaped = false; + } else if c == '\\' && quote != Some('\'') { + escaped = true; + } else if quote == Some(c) { + quote = None; + } else if quote.is_none() { + match c { + '\'' | '"' => quote = Some(c), + '#' => comment = true, + _ => {} + } + } + if !comment { + out.push(c); + } + } + out +} + fn set_by_system(name: &str) -> bool { SYSTEM_ENV.contains(&name) || SYSTEM_ENV_PREFIXES.iter().any(|p| name.starts_with(p)) } @@ -1120,7 +1324,7 @@ fn split_args(m: &[u8], from: usize, to: usize) -> Vec<(usize, usize)> { match ch { b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' => depth -= 1, - b'<' if angles > 0 || m[from..j].trim_ascii_end().ends_with(b"::") => angles += 1, + b'<' if angles > 0 || opens_angle(&m[from..j]) => angles += 1, b'>' if angles > 0 => angles -= 1, b',' if depth == 0 && angles == 0 => { out.push((start, j)); @@ -1135,6 +1339,14 @@ fn split_args(m: &[u8], from: usize, to: usize) -> Vec<(usize, usize)> { out } +/// Whether a `<` after `before` opens generic arguments: a turbofish (`f::`) or a qualified +/// path at the start of an operand (`>::VALUE`). A `<` after an operand is a +/// comparison, and one after another `<` is a shift. +fn opens_angle(before: &[u8]) -> bool { + let before = before.trim_ascii_end(); + before.ends_with(b"::") || matches!(before.last(), None | Some(b'(' | b'[' | b'{' | b',' | b'&' | b'*' | b'!' | b'=' | b';')) +} + /// `b` without whitespace. fn norm(b: &[u8]) -> String { String::from_utf8_lossy(&b.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect::>()).into_owned() @@ -1228,9 +1440,21 @@ fn fn_after(m: &[u8], attr: usize, from: usize) -> Option { if name_end == name_start { return None; } - let open = name_end + m[name_end..].iter().position(|&c| c == b'{' || c == b';')?; - if m[open] != b'{' { - return None; + // The body's `{` comes after the signature, whose parameters, array types (`[u8; 2]`) and + // braced const arguments (`Foo<{ N + 1 }>`) can hold `;` and braces. + let mut open = name_end; + let mut angles = 0usize; + loop { + match m.get(open)? { + b'(' | b'[' => open = matching(m, open)?, + b'<' => angles += 1, + b'>' if m[open - 1] != b'-' => angles = angles.saturating_sub(1), + b'{' if angles > 0 => open = matching(m, open)?, + b'{' => break, + b';' if angles == 0 => return None, + _ => {} + } + open += 1; } let close = matching(m, open)?; // The item starts after the previous item or block opening; comments before it are masked. @@ -1291,11 +1515,12 @@ fn calls_at(m: &[u8], from: usize, to: usize) -> Vec<(usize, String, bool)> { let mut out = vec![]; let mut i = from; while i < to { - if !(m[i].is_ascii_alphabetic() || m[i] == b'_') || (i > 0 && is_ident(m[i - 1])) { + // Non-ASCII letters (`vérifier`) are part of a name, as in a test's own name. + if !(m[i].is_ascii_alphabetic() || m[i] == b'_' || m[i] >= 0x80) || (i > 0 && (is_ident(m[i - 1]) || m[i - 1] >= 0x80)) { i += 1; continue; } - let end = i + m[i..to].iter().take_while(|&&c| is_ident(c)).count(); + let end = i + m[i..to].iter().take_while(|&&c| is_ident(c) || c >= 0x80).count(); let bang = m.get(end) == Some(&b'!'); let after = skip_ws(m, end + usize::from(bang)); let after = if bang { after } else { skip_turbofish(m, after) }; @@ -1576,7 +1801,7 @@ fn item_at(m: &[u8], at: usize) -> Option<(&[u8], bool, usize, usize)> { if is_macro { start = skip_ws(m, start + usize::from(m.get(start) == Some(&b'!'))); } - let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c) || c >= 0x80).count(); if end == start { return None; } @@ -1676,6 +1901,8 @@ pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { /// `m` with each `fn` and `macro_rules!` declared inside a test's body replaced by spaces, from /// its keyword to its closing brace. A call to one stays, so it can still count as a helper call. +/// A closure or async block bound to `_` (`let _ = async { … };`) is dropped unrun, so its +/// statement is replaced too. fn executed(m: &[u8], tests: &[TestFn]) -> Vec { let mut out = m.to_vec(); for t in tests { @@ -1684,6 +1911,39 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec { blank(&mut out, at, close + 1); } } + // Only a `let` statement, not the pattern of an `if let` or `while let`. + let statements = words(m, b"let", t.open, t.close) + .into_iter() + .filter(|&at| m[..at].trim_ascii_end().last().is_some_and(|c| matches!(c, b'{' | b';' | b'}'))); + for at in statements { + let wild = skip_ws(m, at + 3); + let eq = skip_ws(m, wild + 1); + if m.get(wild) != Some(&b'_') + || m.get(wild + 1).copied().is_some_and(is_ident) + || m.get(eq) != Some(&b'=') + || m.get(eq + 1) == Some(&b'=') + { + continue; + } + let mut value = skip_ws(m, eq + 1); + let is_async = m[value..].starts_with(b"async") && !m.get(value + 5).copied().is_some_and(is_ident); + if is_async { + value = skip_ws(m, value + 5); + } + if m[value..].starts_with(b"move") && !m.get(value + 4).copied().is_some_and(is_ident) { + value = skip_ws(m, value + 4); + } + let end = statement_end(m, at); + // The block alone is the value; `async { … }.await` runs it. + let unrun = if is_async { + m.get(value) == Some(&b'{') && matching(m, value).is_some_and(|close| skip_ws(m, close + 1) == end) + } else { + m.get(value) == Some(&b'|') + }; + if unrun && end < t.close { + blank(&mut out, at, end + 1); + } + } } out } @@ -1987,6 +2247,15 @@ impl View<'_> { self.file.hit(at, rule, &self.t.name, note) } + /// A hit at `at` whose span runs through the last line of the operand `through`, so a change to + /// any compared operand of a multiline assertion counts; a failure message after it does not. + fn hit_through(&self, at: usize, through: (usize, usize), rule: Rule, note: String) -> Hit { + let mut h = self.hit(at, rule, note); + let end = through.0 + self.file.m[through.0..through.1].trim_ascii_end().len(); + h.last = h.last.max(self.file.lines.of(end.saturating_sub(1))); + h + } + /// A hit for the whole test, on its `fn` line. fn whole(&self, rule: Rule, note: String) -> Hit { let mut h = self.hit(self.t.fn_at, rule, note); @@ -2025,10 +2294,34 @@ fn all_unguarded(v: &View) -> Vec { let mut body = v.body_without_messages(); strip_all_predicates(&mut body); let locals = bindings(&body); + // Size checks of a plain local (`xs.len()`), each with where its operand ends: one guards an + // `.all(…)` assertion only when no code between them may shrink or replace that local. + let mut direct: Vec<(String, usize)> = vec![]; let checked = v.asserts.iter().any(|a| { a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { let (from, to) = (from - v.t.open, to - v.t.open); - SIZE_CHECKS.iter().any(|g| norm(&body[from..to]).contains(g)) || reads_counted_local(&body, &locals, from, to) + let text = norm(&body[from..to]); + let other = SIZE_CHECKS.iter().any(|g| { + text.match_indices(g).any(|(i, _)| { + let head = &text[..i]; + let start = head.bytes().rposition(|c| !is_ident(c)).map_or(0, |p| p + 1); + let receiver = &head[start..]; + let plain = plain_local(receiver) && !head[..start].ends_with(['.', ':']); + // An operand that may shrink the local after reading its size + // (`{ let n = xs.len(); xs.clear(); n }`) guards nothing; a change before the + // read (`{ xs = fetch(); xs.len() }`) is measured by it. + let read = format!("{receiver}{g}"); + let kept = words(&body, receiver.as_bytes(), from, to) + .into_iter() + .filter(|&p| norm(&body[p..to]).starts_with(&read)) + .any(|p| !may_shrink(&body[..to], receiver.as_bytes(), p + receiver.len())); + if plain && kept { + direct.push((receiver.to_owned(), to)); + } + !plain + }) + }); + other || reads_counted_local(&body, &locals, from, to) }) }); let sizes = Sizes { file: &v.file.m, consts: OnceCell::new(), src: v.file.src, open: v.t.open, cond: RefCell::default() }; @@ -2038,6 +2331,10 @@ fn all_unguarded(v: &View) -> Vec { v.asserts .iter() .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())) + .filter(|a| { + let at = a.at - v.t.open; + !direct.iter().any(|(name, to)| *to >= at || !may_shrink(&body[..at], name.as_bytes(), *to)) + }) .filter(|a| { let cond = v.first_arg(a); let lits = a.args.first().map(|&(from, to)| literals_in(v.file.src, &v.file.m, from, to)).unwrap_or_default(); @@ -2917,7 +3214,7 @@ fn strip_closure_keywords(head: &str) -> (&str, bool) { } /// Where `b[after..to]` calls the closure that the `let` at `bound` binds to `name`: `name(…)`, not -/// a method (`other.run()`), and not after a later `let` of the same name that is still in scope. +/// a method (`other.run()`) or a path (`other::run()`), and not under a later binding of the same name. /// Calling an async closure only makes a future, so its call counts only when the future is /// awaited (`run().await`) or passed to `block_on`. fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, asynchronous: bool) -> Vec { @@ -2937,7 +3234,8 @@ fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, as if before.last() == Some(&b'.') || before.ends_with(b"::") || b.get(open) != Some(&b'(') { return false; } - if words(b, b"let", bound + 3, at).into_iter().any(|l| rebinds(l, at)) { + let pattern = for_binding(b, name, at).max(closure_binding(b, name, at)).max(arm_binding(b, name, at)); + if pattern.is_some_and(|p| p > bound) || words(b, b"let", bound + 3, at).into_iter().any(|l| rebinds(l, at)) { return false; } if !asynchronous { @@ -3469,11 +3767,37 @@ fn strip_all_predicates(body: &mut [u8]) { } } -/// Whether test code accesses a first item in a way that fails on an empty collection. +/// Whether test code accesses an item in a way that fails on an empty collection: a first item, or +/// an index written as a number. fn first_item_guard(body: &[u8], sizes: &Sizes) -> bool { let compact = norm(body); let unwrapped = [".first().unwrap()", ".first().expect(", ".next().unwrap()", ".next().expect("]; - let indexed = compact.match_indices("[0]").any(|(at, _)| array_literal_len(&compact[..at + 3], sizes).is_none_or(|n| n == 0)); + let indexed = compact.match_indices('[').any(|(at, _)| { + let digits = compact[at + 1..].bytes().take_while(u8::is_ascii_digit).count(); + let end = at + 1 + digits; + if digits == 0 || compact.as_bytes().get(end) != Some(&b']') { + return false; + } + // `rows()[2].iter().all(…)` runs `.all` over the item: the access checks `rows()`, not what + // `.all` reads. An item iterated for another call (`rows[0].iter().sum()`) still shows that + // `rows` has items. [`strip_all_predicates`] has blanked each `.all(…)` call, so its chain + // ends at the `.` before it. + let b = compact.as_bytes(); + let mut chain = end + 1; + while let Some(&c) = b.get(chain) { + chain = match c { + b'(' | b'[' => match matching(b, chain) { + Some(close) => close + 1, + None => break, + }, + c if is_ident(c) || c >= 0x80 || matches!(c, b'.' | b':') => chain + 1, + _ => break, + }; + } + let calls = &compact[end + 1..chain]; + let all_over_item = [".iter()", ".into_iter()"].iter().any(|m| calls.starts_with(m)) && calls.ends_with('.'); + !all_over_item && array_literal_len(&compact[..=end], sizes).is_none_or(|n| n == 0) + }); indexed || unwrapped.iter().any(|g| compact.contains(g)) || panicking_first_binding(body) } @@ -3575,7 +3899,7 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { } // 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. + // or a local it passes as a selector (`r.items(active)`) from the binding on. let read = !plain_local(r) && plain_local(pinned) && init(pinned, a.at).is_some_and(|(text, at)| { @@ -3586,6 +3910,7 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { && sizes.receiver_literals(r).is_some_and(|want| sizes.literals(let_value(body, at, bound), bound).starts_with(&want)) && !touched_after(&body[..a.at], pinned, bound, pinned) && !touched_after(body, root, bound, r) + && selector_locals(r).into_iter().all(|s| s == root || !selector_touched(body, s, bound)) && !gives_alias(&body[..at], root, root_from) }); // The assertion compares the same call the receiver is bound to (`gaps(&word)`), so its @@ -3598,7 +3923,9 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { }) } -/// Whether an expression starts a statement of the test body or a plain nested block. +/// Whether an expression starts a statement of the test body or a plain nested block. A block +/// still open at the end of `body` also holds the code that follows `body` (the assertion a caller +/// passes `body` up to), so a statement in it runs whenever that code runs. 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; @@ -3612,12 +3939,15 @@ fn body_level_statement(body: &[u8], mut at: usize) -> bool { 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'[' | b'{' => match matching(body, i) { + Some(close) if close < at => { + statement = body[i] == b'{'; + i = close + 1; + continue; + } + None => statement = body[i] == b'{', + Some(_) => return false, + }, b';' | b'}' => statement = true, c if c.is_ascii_whitespace() => {} _ => statement = false, @@ -3693,6 +4023,52 @@ fn root_local(expr: &str) -> &str { &expr[..end] } +/// Whether a prefix ends in field access or a path separator, rather than a range operator. +fn field_or_path(prefix: &[u8]) -> bool { + let prefix = prefix.trim_ascii_end(); + prefix.ends_with(b"::") || (prefix.ends_with(b".") && !prefix.ends_with(b"..")) +} + +/// Whether code after `from` may change the selector local `name` ([`touched_after`]). A field +/// or a path segment of the same name (`settings.active`, `mode::active`) is another value. +fn selector_touched(body: &[u8], name: &str, from: usize) -> bool { + let mut own = body.to_vec(); + for at in words(body, name.as_bytes(), from, body.len()) { + let before = body[..at].trim_ascii_end(); + if field_or_path(before) { + blank(&mut own, at, at + name.len()); + } + } + touched_after(&own, name, from, name) +} + +/// The plain locals an expression passes as call arguments or indexes after its root +/// (`active` in `r.items(active)`, `i` in `rows[i]`): not method or field names, path segments, +/// called names, closure parameters or `true` and `false`. +fn selector_locals(expr: &str) -> Vec<&str> { + let b = expr.as_bytes(); + let mut out = vec![]; + let mut at = b.iter().take_while(|&&c| is_ident(c)).count(); + while at < b.len() { + if !is_ident(b[at]) { + at += 1; + continue; + } + let start = at; + while at < b.len() && is_ident(b[at]) { + at += 1; + } + let word = &expr[start..at]; + let before = expr[..start].trim_end(); + let after = expr[at..].trim_start(); + let named = field_or_path(before.as_bytes()) || before.ends_with([':', '|']) || after.starts_with(['(', '!', ':', '|']); + if plain_local(word) && !named && !matches!(word, "true" | "false" | "as" | "mut") && !out.contains(&word) { + out.push(word); + } + } + out +} + /// 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. @@ -4055,15 +4431,17 @@ fn receiver_need<'a>(receiver: &'a str, sizes: &Sizes) -> (&'a str, usize) { (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. +/// The length of the non-empty literal an equality assertion at the level of the test body 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()) { + // Only an assertion that always runs, not one under an `if` or in a closure, pins the length. + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) || !body_level_statement(body, a.at) { return None; } let &(lf, lt) = a.args.first()?; @@ -4423,7 +4801,8 @@ fn may_shrink(body: &[u8], name: &[u8], from: usize) -> bool { } /// 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. +/// an assignment, a `&mut` borrow, or passing it to a call when it holds a `&mut` reference. +/// 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", @@ -4446,6 +4825,8 @@ fn may_change(body: &[u8], name: &[u8], from: usize, allow_growth: bool) -> bool "windows", "chunks", "chunks_exact", + "as_chunks", + "as_rchunks", "sort", "sort_by", "sort_by_key", @@ -4465,24 +4846,84 @@ fn may_change(body: &[u8], name: &[u8], from: usize, allow_growth: bool) -> bool "values", ]; const ADDING: &[&str] = &["push", "push_back", "push_front", "insert", "extend"]; + let local = std::str::from_utf8(name).is_ok_and(plain_local); + let mut_ref = binds_mut_ref(body, name); words(body, name, from, body.len()).into_iter().any(|p| { + let prefix = body[..p].trim_ascii_end(); + if local && field_or_path(prefix) { + return false; + } 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]; + let mut start = p; + let mut end = skip_ws(body, p + name.len()); + while let Some(open) = enclosing_open(body, start) { + let callee = body[..open].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'}' | b'>')); + if body[open] != b'(' || callee || skip_ws(body, open + 1) != start || matching(body, open) != Some(end) { + break; + } + start = open; + end = skip_ws(body, end + 1); + } + let method_call = &body[end..]; + let plain_assign = |rest: &[u8]| rest.starts_with(b"=") && !rest.starts_with(b"==") && !rest.starts_with(b"=>"); + // A destructuring assignment (`(xs, _) = …`) replaces each local named as an element of + // the tuple or array to the left of its `=`. + let destructured = after.first().is_some_and(|c| matches!(c, b',' | b')' | b']')) && { + let mut at = p; + let mut target = false; + while let Some(open) = enclosing_open(body, at) { + let callee = body[..open].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'}' | b'>' | b'!')); + let Some(close) = matching(body, open).filter(|_| matches!(body[open], b'(' | b'[') && !callee) else { break }; + if plain_assign(&body[skip_ws(body, close + 1)..]) { + target = true; + break; + } + at = open; + } + target + }; + let assigned = plain_assign(method_call) + || destructured + || ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="].iter().any(|op| method_call.starts_with(op.as_bytes())); + let called = if method_call.first() == Some(&b'.') { + let start = skip_ws(method_call, 1); + let end = start + method_call[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + let rest = &method_call[skip_ws(method_call, end)..]; + let method = &method_call[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 + // A local that already holds a `&mut` reborrows it when passed to a function or method + // (`std::mem::take(xs)`), which can change it; a macro such as `assert_eq!` only reads it. + let passed = mut_ref + && (before.ends_with(b"(") || before.ends_with(b",")) + && matches!(after.first(), Some(b')' | b',')) + && enclosing_open(body, p).is_some_and(|open| { + body[open] == b'(' && body[..open].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'}' | b'>')) + }); + assigned || borrowed || called || passed + }) +} + +/// Whether `body` has a `let` that binds `name` to a mutable reference (`let xs = &mut v;`, +/// `let xs: &mut Vec = …;`). +fn binds_mut_ref(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 end = start + name.len(); + if !body[start..].starts_with(name) || body.get(end).copied().is_some_and(is_ident) { + return false; + } + let rest = norm(&body[end..statement_end(body, end)]); + rest.starts_with("=&mut") || rest.starts_with(":&mut") }) } @@ -4654,6 +5095,10 @@ fn bindings(body: &[u8]) -> Vec { 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 prefix = body[..p].trim_ascii_end(); + if field_or_path(prefix) { + return false; + } let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p); reaching .is_some_and(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end) && r.source.as_ref().is_none_or(|s| !may_shrink(body, s, r.end))) @@ -4729,7 +5174,26 @@ fn exit_status_only(v: &View) -> Option { let status_only = |a: &MacroCall| { a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { let c = norm(&v.file.m[from..to]); - c.contains(".success()") || c.contains(".code()") + let c = unparenthesized(&c); + let mut start = 0; + top_level_at(c, "||").into_iter().chain([c.len()]).any(|end| { + if end < start { + return false; + } + let alternative = c.get(start..end); + start = end.saturating_add(2); + alternative.is_some_and(|alternative| { + let mut start = 0; + top_level_at(alternative, "&&").into_iter().chain([alternative.len()]).all(|end| { + if end < start { + return true; + } + let operand = alternative.get(start..end); + start = end.saturating_add(2); + operand.is_some_and(|operand| operand.contains(".success()") || operand.contains(".code()")) + }) + }) + }) }) }; if !runs || reads || v.asserts.is_empty() || !v.asserts.iter().all(status_only) || v.delegates { @@ -5301,7 +5765,7 @@ fn counted_while(m: &[u8], head: &[u8], open: usize, close: usize) -> bool { /// body calls a function or method other than [`TIME_CALLS`] and [`PASS_THROUGH_CALLS`] (a /// flag's `load`, a `poll`, a progress read). A macro such as `println!`, a call inside the /// arguments of `stringify!`, of a [`LOG_MACROS`] macro or of the sleep itself, a nested `fn` name -/// and `Duration::new` do not count. A closure passed directly to a `thread::spawn` call whose +/// and the calls in its body, and `Duration::new` do not count. A closure passed directly to a `thread::spawn` call whose /// handle is dropped runs beside the test, which does not wait for it. In `while n < bound` with /// `n += 1`, `n -= 1`, `n = n + 1` or `n = n - 1` in the body, the loop counts its own passes, so /// only calls in the body count. @@ -5343,16 +5807,60 @@ fn polls_or_releases(m: &[u8], at: usize, imports: Imports) -> bool { let b = before(p); b.ends_with(b"fn") && !b.len().checked_sub(3).is_some_and(|j| is_ident(b[j])) }; + // A nested `fn` item runs only where something calls it, so its signature and body do not poll. + let items: Vec<(usize, usize)> = words(m, b"fn", from, close).into_iter().filter_map(|kw| fn_item_span(m, kw, close)).collect(); found.iter().any(|&(p, ref name, method)| { !name.ends_with('!') && !TIME_CALLS.contains(&name.as_str()) && !PASS_THROUGH_CALLS.contains(&name.as_str()) && !skipped.iter().any(|&(o, c)| o < p && p < c) + && !items.iter().any(|&(o, c)| o < p && p < c) && !(name == "new" && !method && duration_new(p)) && !(!method && declared(p)) }) } +/// The span of the `fn` item whose keyword is at `kw`, from the keyword to the brace that closes +/// its body, when that brace comes before `to`: the name, any generic parameters (``), +/// the parameter list, the return type and the body. `None` for a `fn` pointer type (`fn(u8)`) or a +/// declaration without a body. +fn fn_item_span(m: &[u8], kw: usize, to: usize) -> Option<(usize, usize)> { + let name = skip_ws(m, kw + 2); + let name_end = name + m[name..to].iter().take_while(|&&c| is_ident(c)).count(); + if name_end == name { + return None; + } + let mut i = skip_ws(m, name_end); + if m.get(i) == Some(&b'<') { + let mut depth = 0usize; + while i < to { + match m[i] { + b'<' => depth += 1, + b'>' if m[i - 1] != b'-' => { + depth -= 1; + if depth == 0 { + break; + } + } + b'(' | b'[' | b'{' => i = matching(m, i)?, + _ => {} + } + i += 1; + } + i = skip_ws(m, i + 1); + } + if m.get(i) != Some(&b'(') { + return None; + } + let params_close = matching(m, i)?; + let open = params_close + m.get(params_close..to)?.iter().position(|&c| matches!(c, b'{' | b';'))?; + if m[open] != b'{' { + return None; + } + let close = matching(m, open)?; + (close < to).then_some((kw, close)) +} + /// The start of the name of the `spawn(…)` call that takes the closure whose head is `m[start..open]` /// as its argument directly (`spawn(|| {`, `spawn(move || {`), not through another call such as /// `spawn(prepare(|| {`. @@ -5907,13 +6415,21 @@ fn mirrors(v: &View) -> Vec { let (la, ra) = (head_args(v.file, code, lr)?, head_args(v.file, code, rr)?); let mut differing = la.iter().zip(&ra).filter(|(x, y)| x != y).peekable(); let entries = la.len() == ra.len() && differing.peek().is_some() && differing.all(|(x, y)| key_like(x) && key_like(y)); - (!entries).then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) + (!entries).then(|| v.hit_through(a.at, rr, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) }) .collect() } -/// Methods that only read a value the test built itself. -const FIXTURE_READS: &[&str] = &["len", "is_empty", "clone", "to_string", "to_owned", "as_str", "as_ref", "as_slice", "to_vec", "into"]; +/// Methods that inspect a fixture container without running its elements' code. +const FIXTURE_READS: &[&str] = &["len", "is_empty", "as_str", "as_ref", "as_slice"]; + +/// Methods that can run element code and are inert only when the fixture holds no user values. +/// `into` is not one: its target can be any type with a `From` impl. +const FIXTURE_CONVERSIONS: &[&str] = &["clone", "to_string", "to_owned", "to_vec"]; + +/// Capitalized names from the standard library that an operand may build or read without reaching +/// code under test. +const STD_TYPES: &[&str] = &["Some", "None", "Ok", "Err", "Box", "String", "Vec", "Option", "Result"]; /// Lowercase names that are types or keywords, not locals. const PLAIN_NAMES: &[&str] = &[ @@ -5925,31 +6441,57 @@ fn screaming_or_camel(name: &str) -> bool { name.as_bytes().first().is_some_and(u8::is_ascii_uppercase) } +/// Whether a name is a capitalized type, struct or enum of the code under test: `Input`, `Kind`, not +/// an all-capitals constant (`MAX_ZOOM`) or one of [`STD_TYPES`]. +fn user_type(name: &str) -> bool { + screaming_or_camel(name) && name.bytes().any(|c| c.is_ascii_lowercase()) && !STD_TYPES.contains(&name) +} + +/// Looks up a local at a position: for a local whose reaching binding is inert there, whether its +/// value is a [`user_value`], its initializer and the position of its binding. +type LocalAt<'a> = dyn Fn(&str, usize) -> Option<(bool, String, usize)> + 'a; + /// Whether a (whitespace-free, masked) operand reads only literals, constants, enum variants and the -/// test's own locals bound to such values: `Some(true)` when it reads such a local, `Some(false)` -/// when it reads none, `None` when it calls or reads anything else. -fn inert(op: &str, local: &dyn Fn(&str) -> Option) -> Option { +/// test's own locals bound to such values: `Some((reads_local, user))`, where `reads_local` says +/// whether it reads such a local and `user` whether its value is one of a [`user_type`] +/// ([`user_value`]); `None` when it calls or reads anything else. A method on a user value can run +/// its own implementation. A [`FIXTURE_READS`] method on a container of user values is inert, but +/// a [`FIXTURE_CONVERSIONS`] method on that container can run element code. +/// Arithmetic and bitwise operators on user values can also run their implementations. +/// `local` gives, for a local whose reaching binding is inert at a position, its `user`, initializer +/// and binding position. +fn inert(op: &str, pos: usize, local: &LocalAt) -> Option<(bool, bool)> { let b = op.as_bytes(); + // Non-ASCII letters (`数`) are part of a name; their UTF-8 bytes are all 0x80 or above. + let ident = |c: u8| is_ident(c) || c >= 0x80; let mut reads_local = false; let mut i = 0; while i < b.len() { - if !is_ident(b[i]) || b[i].is_ascii_digit() || (i > 0 && is_ident(b[i - 1])) { + if fixture_operator_runs(op, i, pos, local) { + return None; + } + if !ident(b[i]) || b[i].is_ascii_digit() || (i > 0 && ident(b[i - 1])) { // Number suffixes (`1.0f32`, `2_u8`) are part of the literal. if b[i].is_ascii_digit() { - i += b[i..].iter().take_while(|&&c| is_ident(c)).count(); + i += b[i..].iter().take_while(|&&c| ident(c)).count(); continue; } i += 1; continue; } - let end = i + b[i..].iter().take_while(|&&c| is_ident(c)).count(); + let end = i + b[i..].iter().take_while(|&&c| ident(c)).count(); let name = &op[i..end]; let after = &op[end..]; let method = op[..i].ends_with('.') && !op[..i].ends_with(".."); let path_tail = op[..i].ends_with("::"); if method { - if after.starts_with('(') && !FIXTURE_READS.contains(&name) { - return None; + if after.starts_with('(') { + let receiver = &op[receiver_start(b, i - 1)..i - 1]; + let inert_read = FIXTURE_READS.contains(&name) && !user_value(receiver, pos, local); + let inert_conversion = FIXTURE_CONVERSIONS.contains(&name) && !holds_user_value(receiver, pos, local); + if !inert_read && !inert_conversion { + return None; + } } } else if after.starts_with("::") || PLAIN_NAMES.contains(&name) { } else if after.starts_with('!') && !after.starts_with("!=") { @@ -5960,7 +6502,7 @@ fn inert(op: &str, local: &dyn Fn(&str) -> Option) -> Option { } else if after.starts_with('(') { let builder = ["Some", "Ok", "Err"].contains(&name) || (path_tail && ["Box::new", "String::from", "Vec::new"].iter().any(|p| op[..end].ends_with(p))) - || (!path_tail && screaming_or_camel(name)); + || screaming_or_camel(name); if !builder { return None; } @@ -5969,14 +6511,215 @@ fn inert(op: &str, local: &dyn Fn(&str) -> Option) -> Option { } else if path_tail { return None; } else { - match local(name) { - Some(true) => reads_local = true, - _ => return None, - } + reads_local = true; + local(name, pos)?; } i = end; } - Some(reads_local) + Some((reads_local, user_value(op, pos, local))) +} + +/// Whether the operator at `at` can call an implementation on a user value. Comparisons, logical +/// operators, borrows and ranges do not count. Operands stop at other operators or separators, so +/// an unrelated user value in the assertion does not make literal arithmetic behavioral. +fn fixture_operator_runs(op: &str, at: usize, pos: usize, local: &LocalAt) -> bool { + let b = op.as_bytes(); + let c = b[at]; + if !matches!(c, b'+' | b'-' | b'*' | b'/' | b'%' | b'&' | b'|' | b'^' | b'<' | b'>' | b'!') { + return false; + } + let previous = at.checked_sub(1).and_then(|i| b.get(i)).copied(); + let next = b.get(at + 1).copied(); + if next == Some(b'=') || (matches!(c, b'&' | b'|') && (next == Some(c) || previous == Some(c))) { + return false; + } + let width = if matches!(c, b'<' | b'>') { + if next != Some(c) || previous == Some(c) || b.get(at + 2) == Some(&b'=') { + return false; + } + 2 + } else { + 1 + }; + let binary = previous.is_some_and(|p| is_ident(p) || p >= 0x80 || matches!(p, b')' | b']' | b'}' | b'"' | b'\'')); + if (!binary && !matches!(c, b'-' | b'!')) || (binary && c == b'!') { + return false; + } + if binary && holds_user_value(&op[receiver_start(b, at)..at], pos, local) { + return true; + } + let from = at + width; + let mut end = from; + // Prefix borrows and dereferences belong to the right operand, not another binary operator. + while matches!(b.get(end), Some(b'&' | b'*')) { + end += 1; + } + while end < b.len() { + match b[end] { + b'(' | b'[' | b'{' => { + let Some(close) = matching(b, end) else { return false }; + end = close + 1; + } + b'.' if b.get(end + 1) == Some(&b'.') => break, + b'!' if matches!(b.get(end + 1), Some(b'(' | b'[' | b'{')) => end += 1, + c if is_ident(c) || c >= 0x80 || matches!(c, b'.' | b':') => end += 1, + _ => break, + } + } + holds_user_value(&op[from..end], pos, local) +} + +/// Where the receiver of the method call whose `.` is at `dot` starts in a whitespace-free operand: +/// back over names, paths, field and method accesses, bracketed groups, macro names and string +/// literals. +fn receiver_start(op: &[u8], dot: usize) -> usize { + let ident = |c: u8| is_ident(c) || c >= 0x80; + let mut j = dot; + while j > 0 { + let c = op[j - 1]; + if matches!(c, b')' | b']' | b'}') { + let mut depth = 0usize; + let mut k = j; + while k > 0 { + k -= 1; + match op[k] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' => { + depth -= 1; + if depth == 0 { + break; + } + } + _ => {} + } + } + j = k; + } else if ident(c) { + while j > 0 && ident(op[j - 1]) { + j -= 1; + } + } else if c == b'"' { + j = op[..j - 1].iter().rposition(|&q| q == b'"').unwrap_or(0); + } else if (c == b'.' && !(j >= 2 && op[j - 2] == b'.')) || (c == b'!' && j >= 2 && ident(op[j - 2])) { + j -= 1; + } else if c == b':' && j >= 2 && op[j - 2] == b':' { + j -= 2; + } else { + break; + } + } + j +} + +/// Whether a whitespace-free expression is a value of a [`user_type`]: it starts with such a name +/// (`Input { n: 5 }`, `model::Input(5)`, `Kind::A`), or with a local whose reaching binding is one (`local`). +/// A literal, a macro such as `vec!` and a standard builder such as `Some(…)` are not. A field read +/// (`input.n`, `pair.0`) is the value the struct literal or constructor it reads gives that field, +/// and not a user value when the test does not show it. +fn user_value(expr: &str, pos: usize, local: &LocalAt) -> bool { + let expr = expr.trim_start_matches(['&', '*']); + if let Some((base, field)) = last_field(expr) { + return field_value(base, field, pos, local).is_some_and(|(v, at)| user_value(&v, at, local)); + } + if expr.starts_with('(') { + return matching(expr.as_bytes(), 0) == Some(expr.len() - 1) && user_value(&expr[1..expr.len() - 1], pos, local); + } + let mut expr = expr; + loop { + let n = expr.bytes().take_while(|&c| is_ident(c) || c >= 0x80).count(); + if n == 0 || !expr.as_bytes()[0].is_ascii_lowercase() || !expr[n..].starts_with("::") { + break; + } + expr = &expr[n + 2..]; + } + let n = expr.bytes().take_while(|&c| is_ident(c) || c >= 0x80).count(); + if n == 0 || expr.as_bytes()[0].is_ascii_digit() { + return false; + } + let (name, after) = expr.split_at(n); + if user_type(name) { + return true; + } + if after.starts_with(['(', '!', ':']) || screaming_or_camel(name) || PLAIN_NAMES.contains(&name) { + return false; + } + local(name, pos).is_some_and(|(user, _, _)| user) +} + +/// Whether a fixture value contains a user value, including nested containers and local aliases. +fn holds_user_value(expr: &str, pos: usize, local: &LocalAt) -> bool { + let expr = expr.trim_start_matches(['&', '*']); + if let Some(receiver) = [".as_slice()", ".as_ref()", ".clone()", ".to_vec()", ".to_owned()"].iter().find_map(|suffix| expr.strip_suffix(suffix)) { + return holds_user_value(receiver, pos, local); + } + if let Some((base, field)) = last_field(expr) { + return field_value(base, field, pos, local).is_some_and(|(v, at)| holds_user_value(&v, at, local)); + } + if plain_local(expr) { + return user_value(expr, pos, local) || local(expr, pos).is_some_and(|(_, init, at)| holds_user_value(&init, at, local)); + } + let b = expr.as_bytes(); + let Some(open) = b.iter().position(|c| matches!(c, b'(' | b'[' | b'{')) else { return user_value(expr, pos, local) }; + let Some(close) = matching(b, open) else { return false }; + // An element indexed out of a local (`xs[0]`) is a user value when the local's value holds one. + if b[open] == b'[' && close + 1 == b.len() && plain_local(&expr[..open]) && b[0].is_ascii_lowercase() { + return holds_user_value(&expr[..open], pos, local); + } + // Only a whole container exposes its elements, not the result of a method such as `len`. + if close + 1 != b.len() || expr[..open].bytes().any(|c| !is_ident(c) && !matches!(c, b':' | b'!')) { + return false; + } + if user_value(expr, pos, local) { + return true; + } + split_args(b, open + 1, close).into_iter().any(|(from, to)| { + let arg = &expr[from..to]; + // A repeated array or vector contains the value before its top-level semicolon. + let end = top_level_at(arg, ";").first().copied().unwrap_or(arg.len()); + holds_user_value(&arg[..end], pos, local) + }) +} + +/// The base and the field of a whitespace-free expression that ends with a field read: `input` and +/// `n` of `input.n`, `pair` and `0` of `pair.0`. Not a range (`0..n`). +fn last_field(expr: &str) -> Option<(&str, &str)> { + let n = expr.bytes().rev().take_while(|&c| is_ident(c) || c >= 0x80).count(); + let dot = expr.len().checked_sub(n + 1)?; + (n > 0 && expr.as_bytes()[dot] == b'.' && dot > 0 && expr.as_bytes()[dot - 1] != b'.').then(|| (&expr[..dot], &expr[dot + 1..])) +} + +/// The expression a struct literal or tuple constructor gives `field` when `base` (a local, a field +/// read or the literal itself) is one: `5` for `input.n` after `let input = Input { n: 5 };`. +/// Local aliases resolve at their own binding positions. The expression comes with the position +/// where its names are resolved. +fn field_value(base: &str, field: &str, pos: usize, local: &LocalAt) -> Option<(String, usize)> { + let base = base.trim_start_matches(['&', '*']); + let (value, at) = if let Some((b, f)) = last_field(base) { + field_value(b, f, pos, local)? + } else if plain_local(base) && base.as_bytes()[0].is_ascii_lowercase() { + let (_, init, at) = local(base, pos)?; + return field_value(&init, field, at, local); + } else { + (base.to_owned(), pos) + }; + let v = value.as_bytes(); + let open = v.iter().take_while(|&&c| is_ident(c) || c == b':').count(); + if open == 0 || !matches!(v.get(open), Some(b'{' | b'(')) || matching(v, open) != Some(v.len() - 1) { + return None; + } + let args = split_args(v, open + 1, v.len() - 1); + let text = |&(a, b): &(usize, usize)| value[a..b].to_owned(); + if v[open] == b'(' { + return args.get(field.parse::().ok()?).map(|arg| (text(arg), at)); + } + args.iter() + .map(text) + .find_map(|arg| match arg.split_once(':') { + Some((name, rest)) if name == field && !rest.starts_with(':') => Some(rest.to_owned()), + None if arg == field => Some(arg), + _ => None, + }) + .map(|value| (value, at)) } /// The initializer of the last immutable `let = …;` in `body[..before]`: `None` when there is @@ -5985,15 +6728,7 @@ fn inert(op: &str, local: &dyn Fn(&str) -> Option) -> Option { fn reaching_init(body: &[u8], name: &str, before: usize) -> Option> { let found = let_init(body, name, before); // A `for` pattern binds its names inside the loop body only, to values the loop produces. - let loop_at = words(body, b"for", 0, before).into_iter().rev().find(|&at| { - // `in` is found as a word outside the pattern's brackets, so a line break around it still - // ends the pattern, and the braces of `for Row { n } in …` are not the loop body. - let Some(kw) = words(body, b"in", at + 3, before).into_iter().find(|&kw| bracket_depth(&body[at + 3..kw]) == 0) else { return false }; - let Some((open, close)) = block_after(body, kw + 2) else { return false }; - // Words stay apart, so `mut n` binds `n`. - let pattern = norm_words(&body[at + 3..kw]); - open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() - }); + let loop_at = for_binding(body, name, before); // A match arm's pattern binds its names inside that arm only, and a closure's parameters // inside its body only. let inner = loop_at.max(arm_binding(body, name, before)).max(closure_binding(body, name, before)); @@ -6004,6 +6739,20 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option Option { + words(body, b"for", 0, before).into_iter().rev().find(|&at| { + // `in` is found as a word outside the pattern's brackets, so a line break around it still + // ends the pattern, and the braces of `for Row { n } in …` are not the loop body. + let Some(kw) = words(body, b"in", at + 3, before).into_iter().find(|&kw| bracket_depth(&body[at + 3..kw]) == 0) else { return false }; + // A block expression as the iterator (`for n in { … } { … }`) comes before the loop body. + let iter = skip_ws(body, kw + 2); + let iter = if body.get(iter) == Some(&b'{') { matching(body, iter).map_or(iter, |close| close + 1) } else { iter }; + let Some((open, close)) = block_after(body, iter) else { return false }; + open < before && before < close && pattern_binds(body, name.as_bytes(), at + 3, kw) + }) +} + /// The offset of the parameter list of the innermost closure whose parameters bind `name` and whose /// body holds `before`: `for_each(|n| assert_eq!(n, 1))` binds `n`. fn closure_binding(body: &[u8], name: &str, before: usize) -> Option { @@ -6095,14 +6844,7 @@ fn arm_binding(body: &[u8], name: &str, before: usize) -> Option { if guard >= before { continue; } - let pattern = norm_words(&body[start..guard]); - let p = pattern.as_bytes(); - // A field label (`Row { body: _ }`) names a field; it binds nothing. - let label = |at: usize| { - let after = skip_ws(p, at + name.len()); - p.get(after) == Some(&b':') && p.get(after + 1) != Some(&b':') - }; - if !words(p, name.as_bytes(), 0, p.len()).into_iter().any(|at| !label(at)) { + if !pattern_binds(body, name.as_bytes(), start, guard) { continue; } // The arm's body: a block, or an expression up to the `,` or brace that ends the arm. @@ -6141,7 +6883,7 @@ fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, u let start = skip_ws(body, at + 3); let is_mut = body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace); let n0 = if is_mut { skip_ws(body, start + 3) } else { start }; - let n1 = n0 + body[n0..].iter().take_while(|&&c| is_ident(c)).count(); + let n1 = n0 + body[n0..].iter().take_while(|&&c| is_ident(c) || c >= 0x80).count(); let head = body[..at].trim_ascii_end(); let keyword = [&b"if"[..], b"while"].into_iter().find(|k| head.ends_with(k) && !head[..head.len() - k.len()].last().copied().is_some_and(is_ident)); @@ -6242,15 +6984,15 @@ fn block_close(body: &[u8], at: usize) -> usize { } /// `inert` for an operand of the test at `pos`, resolving locals through their initializers. -fn inert_at(body: &[u8], op: &str, pos: usize, depth: usize) -> Option { - let local = |name: &str| -> Option { +fn inert_at(body: &[u8], op: &str, pos: usize, depth: usize) -> Option<(bool, bool)> { + let local = |name: &str, before: usize| -> Option<(bool, String, usize)> { if depth > 8 { return None; } - let (init, at) = reaching_init(body, name, pos)??; - inert_at(body, &init, at, depth + 1).map(|_| true) + let (init, at) = reaching_init(body, name, before)??; + inert_at(body, &init, at, depth + 1).map(|(_, user)| (user, init, at)) }; - inert(op, &local) + inert(op, pos, &local) } /// `constant-echo` and `fixture-only`: every assertion of the test reads only constants and @@ -6271,7 +7013,7 @@ fn echoes(v: &View) -> Option { } for &(from, to) in a.args.iter().take(n) { let op = norm(&body[from - v.t.open..to - v.t.open]); - reads_local |= inert_at(&body, &op, from - v.t.open, 0)?; + reads_local |= inert_at(&body, &op, from - v.t.open, 0)?.0; } } Some(if reads_local { @@ -6824,7 +7566,8 @@ fn path_arg(arg: &str) -> Option { } /// The `#[cfg_attr(, path = "…")]` overrides in `m[from..to]`, each as its condition and -/// path. +/// path. A nested `cfg_attr` adds its condition to the enclosing ones: +/// `cfg_attr(test, cfg_attr(unix, path = "p.rs"))` gives `all(test,unix)`. fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, String)> { let mut out = vec![]; for at in words(m, b"cfg_attr", from, to) { @@ -6834,16 +7577,30 @@ fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, let open = skip_ws(m, at + "cfg_attr".len()); let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; let text = norm_outside_literals(&mask_parts(&String::from_utf8_lossy(&src[open + 1..close]), true, false)); - let cuts = attr_commas(&text); - let Some(&first) = cuts.first() else { continue }; - let mut start = first + 1; - for cut in cuts[1..].iter().copied().chain([text.len()]) { - let arg = text.get(start..cut).unwrap_or(""); - if let Some(rel) = path_arg(arg) { - out.push((text[..first].to_owned(), rel)); - } - start = cut + 1; + out.extend(cfg_attr_path_args(&text, None)); + } + out +} + +/// The `path = "…"` arguments of the whitespace-free arguments `text` of a `cfg_attr(…)`, each with +/// its condition joined to the enclosing ones (`outer`). +fn cfg_attr_path_args(text: &str, outer: Option<&str>) -> Vec<(String, String)> { + let cuts = attr_commas(text); + let Some(&first) = cuts.first() else { return vec![] }; + let cond = match outer { + Some(o) => format!("all({o},{})", &text[..first]), + None => text[..first].to_owned(), + }; + let mut out = vec![]; + let mut start = first + 1; + for cut in cuts[1..].iter().copied().chain([text.len()]) { + let arg = text.get(start..cut).unwrap_or(""); + if let Some(rel) = path_arg(arg) { + out.push((cond.clone(), rel)); + } else if let Some(n) = arg.strip_prefix("cfg_attr(").and_then(|p| p.strip_suffix(')')) { + out.extend(cfg_attr_path_args(n, Some(&cond))); } + start = cut + 1; } out } @@ -7175,17 +7932,17 @@ fn exact_pixels(v: &View) -> Vec { .iter() .filter_map(|a| { let arg = |i: usize| a.args.get(i).map(|&(f, t)| norm(&v.file.m[f..t])); - let (l, r) = if a.name.ends_with("_eq") { - (arg(0)?, arg(1)?) + let ((l, r), last) = if a.name.ends_with("_eq") { + ((arg(0)?, arg(1)?), *a.args.get(1)?) } else if PLAIN_ASSERTS.contains(&a.name.as_str()) { let cond = arg(0)?; let at = *top_level_at(&cond, "==").first()?; - (cond[..at].to_owned(), cond[at + 2..].to_owned()) + ((cond[..at].to_owned(), cond[at + 2..].to_owned()), *a.args.first()?) } else { return None; }; let pixel = (names_rect(&l) && only_numbers(&r)) || (names_rect(&r) && only_numbers(&l)); - pixel.then(|| v.hit(a.at, Rule::ExactPixel, format!("{}! compares a rect with numbers written out", a.name))) + pixel.then(|| v.hit_through(a.at, last, Rule::ExactPixel, format!("{}! compares a rect with numbers written out", a.name))) }) .collect() } @@ -7207,12 +7964,81 @@ mod tests { lint_file(path, src, ctx).into_iter().map(|h| (h.line, h.rule.id())).collect() } + /// A new directory under the system temporary directory, removed when the guard is dropped, + /// including when an assertion fails. + struct TempRepo(std::path::PathBuf); + + impl TempRepo { + fn new(name: &str) -> Self { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("test-lint-{name}-{}-{unique}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + } + + impl std::ops::Deref for TempRepo { + type Target = Path; + + fn deref(&self) -> &Path { + &self.0 + } + } + + impl Drop for TempRepo { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + #[test] fn all_needs_a_non_empty_guard() { let bad = "#[test]\nfn t() {\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; assert_eq!(hits(bad), [(4, "all-unguarded")]); let good = "#[test]\nfn t() {\n let xs = f();\n assert_eq!(xs.len(), 3);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; assert_eq!(hits(good), []); + let cleared = good.replace(" assert!(xs", " xs.clear();\n assert!(xs"); + assert_eq!(hits(&cleared), [(6, "all-unguarded")], "a length check of a collection cleared after it"); + let field = good.replace(" assert!(xs", " other.xs.clear();\n assert!(xs"); + assert_eq!(hits(&field), [], "a field cleared after checking the local's length"); + let path = good.replace(" assert!(xs", " other:: xs.clear();\n assert!(xs"); + assert_eq!(hits(&path), [], "a path cleared after checking the local's length"); + let saved = good.replace("assert_eq!(xs.len(), 3);", "let n = xs.len(); assert_eq!(n, 3); other.xs.clear();"); + assert_eq!(hits(&saved), [], "a field cleared after checking the local's saved length"); + let count = good.replace("assert_eq!(xs.len(), 3);", "let n = xs.len(); assert_eq!(n, 3);"); + assert_eq!(hits(&count), [], "an assertion on the saved length"); + let range = count.replace("assert_eq!(n, 3)", "assert_eq!(0..n, 0..3)"); + assert_eq!(hits(&range), [], "a range equality reads the saved length"); + let inclusive = range.replace("0..", "0..="); + assert_eq!(hits(&inclusive), [], "an inclusive range equality reads the saved length"); + let drained = good.replace(" assert!(xs", " let _ = 0..xs.drain(..).count();\n assert!(xs"); + assert_eq!(hits(&drained), [(6, "all-unguarded")], "a range operand drains the collection after its length check"); + let count_field = count.replace("assert_eq!(n, 3)", "assert_eq!(other.n, 3)"); + assert_eq!(hits(&count_field), [(5, "all-unguarded")], "a field is not the saved length"); + let spaced_count_field = count_field.replace("other.n", "other. n"); + assert_eq!(hits(&spaced_count_field), [(5, "all-unguarded")], "whitespace before the field name"); + let count_path = count.replace("assert_eq!(n, 3)", "assert_eq!(other::n, 3)"); + assert_eq!(hits(&count_path), [(5, "all-unguarded")], "a path is not the saved length"); + let spaced_count_path = count_path.replace("other::n", "other:: n"); + assert_eq!(hits(&spaced_count_path), [(5, "all-unguarded")], "whitespace before the path segment"); + let replaced = good.replace(" assert!(xs", " xs = g();\n assert!(xs"); + assert_eq!(hits(&replaced), [(6, "all-unguarded")], "a length check of a collection replaced after it"); + let sorted = good.replace(" assert!(xs", " xs.sort();\n assert!(xs"); + assert_eq!(hits(&sorted), [], "a call that keeps every item"); + let cleaned = good.replace("> 0));\n", "> 0));\n xs.clear();\n"); + assert_eq!(hits(&cleaned), [], "a collection cleared after the assertion it guards"); + let between = good.replace("> 0));\n", "> 0));\n xs.clear();\n assert!(xs.iter().all(|x| *x > 1));\n"); + assert_eq!(hits(&between), [(7, "all-unguarded")], "only the assertion after the clear"); + let inside = good.replace("assert_eq!(xs.len(), 3);", "assert_eq!({ let n = xs.len(); xs.clear(); n }, 3);"); + assert_eq!(hits(&inside), [(5, "all-unguarded")], "an operand that clears the collection after reading its length"); + let field_inside = good.replace("assert_eq!(xs.len(), 3);", "assert_eq!({ let n = xs.len(); other.xs.clear(); n }, 3);"); + assert_eq!(hits(&field_inside), [], "an operand that clears a field after reading the local's length"); + let spaced_field = field_inside.replace("other.xs", "other. xs"); + assert_eq!(hits(&spaced_field), [], "whitespace before the field name"); + let refreshed = good.replace("assert_eq!(xs.len(), 3);", "assert_eq!({ xs = g(); xs.len() }, 3);"); + assert_eq!(hits(&refreshed), [], "an operand that replaces the collection before reading its length"); + let chunked = good.replace("xs.iter().all(|x| *x > 0)", "xs.as_chunks::<2>().0.iter().all(|[a, b]| a == b)"); + assert_eq!(hits(&chunked), [], "a turbofish view in the assertion itself"); let inner = "#[test]\nfn t() {\n assert!(rows().iter().all(|r| r.len() == 3));\n}\n"; assert_eq!(hits(inner), [(3, "all-unguarded")], "a length inside the predicate is about each item"); let none = "#[test]\nfn t() {\n assert!(warnings().iter().all(|w| !w.contains(\"lost\")), \"no warning\");\n}\n"; @@ -7225,6 +8051,20 @@ mod tests { assert_eq!(hits(mixed), [(3, "all-unguarded")]); } + #[test] + fn mutation_checks_distinguish_locals_from_fields() { + assert!(!may_change(b"other. xs = next();", b"xs", 0, false)); + assert!(!may_change(b"other:: xs = next();", b"xs", 0, false)); + assert!(may_change(b"xs = next();", b"xs", 0, false)); + assert!(!may_change(b"use_it(&mut other.xs);", b"xs", 0, false)); + assert!(may_change(b"use_it(&mut xs);", b"xs", 0, false)); + assert!(!may_change(b"other.xs.push(1);", b"xs", 0, false)); + assert!(may_change(b"xs.push(1);", b"xs", 0, false)); + assert!(may_change(b"let _ = 0..xs.drain(..);", b"xs", 0, false)); + assert!(may_change(b"let _ = 0..=xs.drain(..).count();", b"xs", 0, false)); + assert!(may_shrink(b"holder.other.xs.clear();", b"other.xs", 0)); + } + #[test] fn census_round_trips_look_up_the_entry() { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); @@ -8019,8 +8859,15 @@ mod tests { #[test] fn all_guards_accept_first_item_access_that_fails_when_empty() { - for expr in ["xs[0]", "xs.first().unwrap()", "xs.first().expect(\"item\")", "xs.iter().next().unwrap()", "xs.iter().next().expect(\"item\")"] - { + for expr in [ + "xs[0]", + "xs[1]", + "xs[12]", + "xs.first().unwrap()", + "xs.first().expect(\"item\")", + "xs.iter().next().unwrap()", + "xs.iter().next().expect(\"item\")", + ] { let good = format!("#[test]\nfn t() {{\n let _ = {expr};\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); assert_eq!(hits(&good), [], "{expr} fails when empty"); let inner = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| {expr} > 0));\n}}\n"); @@ -8030,6 +8877,14 @@ mod tests { } let literal = "#[test]\nfn t() {\n let _ = [0];\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; assert_eq!(hits(literal), [(4, "all-unguarded")], "an array literal does not access an item"); + let other = literal.replace("[0]", "[3]"); + assert_eq!(hits(&other), [(4, "all-unguarded")], "an array literal of another number does not access an item"); + let range = "#[test]\nfn t() {\n let _ = &xs[1..];\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(range), [(4, "all-unguarded")], "a slice range is not an item access"); + let item = "#[test]\nfn t() {\n assert!(rows()[0].iter().all(|r| r.ok));\n}\n"; + assert_eq!(hits(item), [(3, "all-unguarded")], "indexing the collection `.all` reads checks only the outer one"); + let summed = "#[test]\nfn t() {\n let sum: u8 = rows[0].iter().sum();\n assert_eq!(sum, 6);\n assert!(rows.iter().all(|r| r.len() == 3));\n}\n"; + assert_eq!(hits(summed), [], "an item iterated for another call still shows that the outer collection has items"); } #[test] @@ -8040,6 +8895,12 @@ mod tests { assert_eq!(hits(bad), [(4, "all-unguarded")]); } + #[test] + fn a_first_callback_call_guards_the_callback_collection() { + let src = "#[test]\nfn t() {\n let callbacks = callbacks();\n callbacks[0]();\n assert!(callbacks.iter().all(|f| f() > 0));\n}\n"; + assert_eq!(only("all-unguarded", src), []); + } + #[test] fn all_hits_count_changes_anywhere_in_their_test() { let src = "#[should_panic]\n#[test]\nfn t() {\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\nfn other() {}\n"; @@ -8053,7 +8914,7 @@ mod tests { } assert!(!touches(&found[0], Some(&[7].into_iter().collect())), "another function is outside the test"); let diff = "diff --git a/crates/x/src/tests.rs b/crates/x/src/tests.rs\n--- a/crates/x/src/tests.rs\n+++ b/crates/x/src/tests.rs\n@@ -5 +4,0 @@\n- assert!(!xs.is_empty());\n"; - let changed = parse_diff(diff); + let changed = parse_diff(diff, &|_, _| false); assert!(touches(&found[0], changed["crates/x/src/tests.rs"].as_ref()), "removing a guard changes the test"); } @@ -8091,6 +8952,21 @@ mod tests { assert_eq!(hits(unused), [(2, "only-weak")], "a declared function's assertion does not run"); let macro_only = "#[test]\nfn t() {\n macro_rules! check {\n () => { assert_eq!(1, 1) };\n }\n f();\n}\n"; assert_eq!(hits(macro_only), [(2, "no-assertion")], "a declared macro's assertion does not run"); + for dropped in [ + "let _ = async { assert_eq!(f(), 1); };", + "let _ = async move { assert_eq!(f(), 1); };", + "let _ = || assert_eq!(f(), 1);", + "let _ = move |x| assert_eq!(x, 1);", + ] { + let src = format!("#[test]\nfn t() {{\n {dropped}\n}}\n"); + assert_eq!(hits(&src), [(2, "no-assertion")], "{dropped}"); + } + let kept = "#[test]\nfn t() {\n let check = || assert_eq!(f(), 1);\n check();\n}\n"; + assert_eq!(hits(kept), [], "a named closure can be called"); + let awaited = "#[test]\nfn t() {\n let _ = async { assert_eq!(f(), 1); }.await;\n}\n"; + assert_eq!(hits(awaited), [], "an awaited block runs"); + let conditional = "#[test]\nfn t() {\n if let _ = || () {\n assert_eq!(f(), 1);\n };\n}\n"; + assert_eq!(hits(conditional), [], "an `if let` pattern is not a statement"); let called = unused.replace(" assert!(parse", " unused();\n assert!(parse"); let files = [("crates/x/src/tests.rs".to_owned(), called.clone())]; let with_helpers = Ctx { helpers: asserting_helpers(&files), ..ctx() }; @@ -8156,6 +9032,18 @@ mod tests { assert_eq!(hits(good), []); } + #[test] + fn process_status_checks_require_every_boolean_operand_to_check_status() { + let good = "#[test]\nfn t() {\n let status = Command::new(\"cp\").arg(src).arg(&destination).status().unwrap();\n assert!(status.success() && destination.exists());\n}\n"; + assert_eq!(hits(good), []); + let borrowed = good.replace("status.success() && destination.exists()", "status.success() && &actual == &expected"); + assert_eq!(hits(&borrowed), []); + for condition in ["status.success() && status.code() == Some(0)", "status.success()", "status.success() || destination.exists()"] { + let bad = good.replace("status.success() && destination.exists()", condition); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{condition}"); + } + } + #[test] fn process_status_checks_accept_every_comparison_assertion() { for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { @@ -8263,7 +9151,7 @@ mod tests { #[test] fn assertion_arguments_keep_turbofish_groups_and_split_comparisons() { - for operand in ["f::()", "f::>()", "f :: ()"] { + for operand in ["f::()", "f::>()", "f :: ()", "

>::VALUE", "&

>::get()"] { let src = format!("{operand}, expected, message"); let m = mask(&src); let args: Vec<&str> = split_args(&m, 0, m.len()).into_iter().map(|(from, to)| src[from..to].trim()).collect(); @@ -8273,6 +9161,11 @@ mod tests { let args: Vec<&str> = split_args(&m, 0, m.len()).into_iter().map(|(from, to)| comparison[from..to].trim()).collect(); assert_eq!(args, ["a < b", &format!("{operand} > c"), "message"], "comparisons around {operand}"); } + let shift = "a << b, c"; + let m = mask(shift); + assert_eq!(split_args(&m, 0, m.len()).len(), 2, "a shift opens no generic arguments"); + let qualified = "#[test]\nfn t() {\n assert_eq!(>::VALUE, read_value());\n}\n"; + assert_eq!(only("constant-echo", qualified), [], "the second operand is a computed value, not a message"); } #[test] @@ -8497,7 +9390,7 @@ mod tests { #[test] fn changed_lines_come_from_the_new_side_of_each_hunk() { let diff = "diff --git a/crates/x/src/a.rs b/crates/x/src/a.rs\nindex 1..2 100644\n--- a/crates/x/src/a.rs\n+++ b/crates/x/src/a.rs\n@@ -3,0 +4,2 @@ fn f() {\n+a\n+b\n@@ -10 +12 @@\n-c\n+d\n@@ -20,2 +21,0 @@\n-e\ndiff --git a/crates/x/src/n.rs b/crates/x/src/n.rs\nnew file mode 100644\n--- /dev/null\n+++ b/crates/x/src/n.rs\n@@ -0,0 +1,3 @@\n"; - let got = parse_diff(diff); + let got = parse_diff(diff, &|_, _| false); assert_eq!(got.len(), 2); assert_eq!(got["crates/x/src/a.rs"], Some([4, 5, 12, 21, 22].into_iter().collect())); assert_eq!(got["crates/x/src/n.rs"], None); @@ -8514,7 +9407,7 @@ mod tests { assert_eq!(found.len(), 2); let old = anchor + 1; let diff = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -{old} +{anchor},0 @@\n-#[should_panic]\n"); - let changed = parse_diff(&diff); + let changed = parse_diff(&diff, &|_, _| false); let expected = if anchor == 0 { vec![1] } else { vec![anchor, anchor + 1] }; assert_eq!(changed[path], Some(expected.into_iter().collect())); assert_eq!(found[0].rule, Rule::NoAssertion); @@ -8593,6 +9486,7 @@ mod tests { " run: MY_SAMPLES=value cargo test", " echo \"MY_SAMPLES=value\" >> \"$GITHUB_ENV\"", " echo 'MY_SAMPLES=value' >> \"$GITHUB_ENV\"", + " echo \"MY_SAMPLES=fixtures\" | tee -a \"$GITHUB_ENV\"", " MY_SAMPLES=value # OTHER_SAMPLES=value", " MY_SAMPLES=\"#value\"", " MY_SAMPLES=", @@ -8606,6 +9500,61 @@ mod tests { assert_eq!(upper_words(reads).collect::>(), Vec::::new()); } + #[test] + fn powershell_environment_file_writes_set_workflow_variables() { + for line in [ + " echo \"MY_SAMPLES=fixtures\" >> $env:GITHUB_ENV", + " echo \"MY_SAMPLES=fixtures\" >> \"$env:GITHUB_ENV\"", + " echo \"MY_SAMPLES=fixtures\" >> ${env:GITHUB_ENV}", + " echo \"MY_SAMPLES=fixtures\" >> \"${env:GITHUB_ENV}\"", + " \"MY_SAMPLES=fixtures\" | Out-File -FilePath $env:GITHUB_ENV -Append", + " echo \"MY_SAMPLES=fixtures\" | Out-File -Append -FilePath \"$env:GITHUB_ENV\"", + " Add-Content -Path $env:GITHUB_ENV -Value \"MY_SAMPLES=fixtures\"", + " \"MY_SAMPLES=fixtures\" | Add-Content -Path ${env:GITHUB_ENV}", + " \"MY_SAMPLES=fixtures\" | out-file -filepath $env:GITHUB_ENV -append", + " \"MY_SAMPLES=fixtures\" | OUT-FILE -FILEPATH $env:GITHUB_ENV -APPEND", + " add-content -path $env:GITHUB_ENV -value \"MY_SAMPLES=fixtures\"", + " AdD-CoNtEnT -pAtH $env:GITHUB_ENV -vAlUe \"MY_SAMPLES=fixtures\"", + ] { + assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); + } + } + + #[test] + fn a_comment_in_a_decoded_run_script_ends_at_its_line_break() { + for line in + ["run: \"echo starting # setup\\nexport MY_SAMPLES=fixtures\\ncargo test\"", "run: \"echo starting\\nMY_SAMPLES=fixtures cargo test\""] + { + assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); + } + let quoted = "run: \"export msg=\\\"hello\\n# world\\\"\\nMY_SAMPLES=fixtures cargo test\""; + assert_eq!(upper_words(quoted).collect::>(), ["MY_SAMPLES"], "a `#` inside a quoted value that spans lines"); + let commented = "run: \"echo starting # MY_SAMPLES=fixtures\\ncargo test\""; + assert_eq!(upper_words(commented).collect::>(), Vec::::new()); + let continued = "run: \"echo \\\\\\nMY_SAMPLES=fixtures\""; + assert_eq!(upper_words(continued).collect::>(), Vec::::new(), "a continued `echo` prints the text"); + } + + #[test] + fn quoted_yaml_scalars_are_decoded_before_shell_assignments() { + for line in [ + "run: 'export MY_SAMPLES=fixtures; cargo test'", + "- run: \"export MY_SAMPLES=fixtures; cargo test\"", + "run: 'export MY_SAMPLES=fixtures; echo ''done'''", + "run: \"export MY_SAMPLES=fixtures; echo \\\"done\\\"\"", + ] { + assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); + } + for line in [ + "run: 'message=\"MY_SAMPLES=fixtures\"'", + "run: \"message=\\\"MY_SAMPLES=fixtures\\\"\"", + "name: 'Test with MY_SAMPLES=fixtures'", + "- name: \"Test with MY_SAMPLES=fixtures\"", + ] { + assert_eq!(upper_words(line).collect::>(), Vec::::new(), "{line}"); + } + } + #[test] fn workflow_mentions_do_not_suppress_unset_gates() { let src = "#[test]\nfn t() {\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; @@ -8631,13 +9580,38 @@ mod tests { } } + #[test] + fn quoted_assignment_command_arguments_set_workflow_variables() { + for line in [ + "run: export \"MY_SAMPLES=fixtures\"", + "run: export 'MY_SAMPLES=fixtures'", + "run: env \"MY_SAMPLES=fixtures\" cargo test", + "run: declare -x \"MY_SAMPLES=x\"", + "run: typeset -x \"MY_SAMPLES=x\"", + "run: local \"MY_SAMPLES=fixtures\"", + "run: readonly 'MY_SAMPLES=fixtures'", + "run: true; export \"MY_SAMPLES=fixtures\"", + "run: if true; then export \"MY_SAMPLES=fixtures\"; fi", + "run: while c; do env \"MY_SAMPLES=x\" cmd; done", + "run: ! command env \"MY_SAMPLES=x\" cmd", + "run: true && env \"MY_SAMPLES=fixtures\" cargo test", + "run: true | env \"MY_SAMPLES=fixtures\" cargo test", + "run: export OTHER='a;b&c|d' \"MY_SAMPLES=fixtures\"", + "run: 'export \"MY_SAMPLES=fixtures\"'", + "- run: \"export 'MY_SAMPLES=fixtures'\"", + ] { + assert!(upper_words(line).any(|name| name == "MY_SAMPLES"), "{line}"); + } + } + #[test] fn patch_labels_are_decoded_before_filtering() { let diff = "diff --git a/crates/x/tests/two words.rs b/crates/x/tests/two words.rs\n--- a/crates/x/tests/two words.rs\t\n+++ b/crates/x/tests/two words.rs\t\n@@ -1 +1 @@\n-a\n+b\ndiff --git \"a/crates/x/tests/q\\\"t.rs\" \"b/crates/x/tests/q\\\"t.rs\"\n--- \"a/crates/x/tests/q\\\"t.rs\"\n+++ \"b/crates/x/tests/q\\\"t.rs\"\n@@ -2 +2 @@\n-a\n+b\ndiff --git \"a/crates/x/tests/caf\\303\\251.rs\" \"b/crates/x/tests/caf\\303\\251.rs\"\n--- \"a/crates/x/tests/caf\\303\\251.rs\"\n+++ \"b/crates/x/tests/caf\\303\\251.rs\"\n@@ -3 +3 @@\n-a\n+b\n"; - let got = parse_diff(diff); + let got = parse_diff(diff, &|_, _| false); assert_eq!(got.get("crates/x/tests/two words.rs"), Some(&Some([1].into_iter().collect())), "{got:?}"); assert_eq!(got.get("crates/x/tests/q\"t.rs"), Some(&Some([2].into_iter().collect())), "{got:?}"); assert_eq!(got.get("crates/x/tests/caf\u{e9}.rs"), Some(&Some([3].into_iter().collect())), "{got:?}"); + assert_eq!(got.len(), 3, "{got:?}"); assert!(got.keys().all(|p| is_scanned(p)), "{got:?}"); } @@ -8651,6 +9625,20 @@ mod tests { assert_eq!(hits(inner), [(9, "no-assertion")], "#[should_panic] before #[test] still belongs to the test"); } + #[test] + fn signature_delimiters_do_not_hide_test_bodies() { + let array = "#[test_case([1, 2])]\nfn t(xs: [u8; 2]) {}\n"; + assert_eq!(hits(array), [(2, "no-assertion")], "array parameter"); + let result = "#[test]\nfn t() -> Result<[u8; 2], ()> {\n Ok([1, 2])\n}\n"; + assert_eq!(hits(result), [(2, "no-assertion")], "array type in generic arguments"); + let array_result = "#[test]\nfn t() -> [u8; 2] {\n [1, 2]\n}\n"; + assert_eq!(hits(array_result), [(2, "no-assertion")], "array return type"); + let braced = "#[test]\nfn t() -> Foo<{ assert!(true); 2 }> {}\n"; + assert_eq!(hits(braced), [(2, "no-assertion")], "braced const argument"); + let arrow = "#[test]\nfn t u8>() {}\n"; + assert_eq!(hits(arrow), [(2, "no-assertion")], "arrow inside generics"); + } + #[test] fn helpers_with_a_shared_name_count_only_when_each_asserts() { let src = "mod a {\n pub fn exercise() { assert_eq!(f(), 1); }\n}\nmod b {\n pub fn exercise() { f(); }\n}\n#[test]\nfn t() {\n b::exercise();\n}\n"; @@ -8833,6 +9821,15 @@ mod tests { assert_eq!(lint_file("crates/x/src/tests.rs", src, &ctx()).iter().map(|h| (h.line, h.test.as_str())).collect::>(), [(2, "échec")]); } + #[test] + fn helpers_with_non_ascii_names_count_as_checks() { + let src = "fn vérifier(a: u8) {\n assert_eq!(a, 1);\n}\n#[test]\nfn t() {\n vérifier(f());\n}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); + assert!(helpers["crates/x"].contains("vérifier"), "{helpers:?}"); + let ctx = Ctx { helpers, ..Ctx::default() }; + assert_eq!(hits_in("crates/x/tests/it.rs", src, &ctx), []); + } + #[test] fn block_comment_allows_need_a_reason_before_the_closing_delimiter() { let bare = "#[test]\nfn t() {\n thread::sleep(D); /* test-lint: allow sleep */\n assert_eq!(f(), 1);\n}\n"; @@ -8864,6 +9861,16 @@ mod tests { assert_eq!(hits(&cleared), [(7, "all-unguarded")]); } + #[test] + fn a_count_stops_guarding_when_its_grouped_collection_changes() { + let src = + "#[test]\nfn t() {\n let mut xs = f();\n let n = xs.len();\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + for call in ["(xs).clear();", "((xs)).clear();"] { + let changed = src.replace(" assert!(xs", &format!(" {call}\n assert!(xs")); + assert_eq!(only("all-unguarded", &changed), [(7, "all-unguarded")], "{call}"); + } + } + #[test] fn checks_in_failure_messages_do_not_end_only_weak() { let src = "#[test]\nfn t() {\n assert!(parse(input).is_ok(), \"{:?}\", probe().unwrap_err());\n}\n"; @@ -8939,6 +9946,15 @@ mod tests { assert_eq!(only("mirror", tails), [(3, "mirror")], "different arithmetic on each side still derives one from the other"); } + #[test] + fn echoes_recognize_non_ascii_identifiers() { + let src = "#[test]\nfn t() {\n let 数 = compute();\n assert_eq!(数, 42);\n}\n"; + assert_eq!(only("constant-echo", src), []); + assert_eq!(only("fixture-only", src), []); + let fixture = "#[test]\nfn t() {\n let 数 = 42;\n assert_eq!(数, 42);\n}\n"; + assert_eq!(only("fixture-only", fixture), [(2, "fixture-only")]); + } + #[test] fn echoes_check_only_constants_or_the_fixture() { let constant = "#[test]\nfn t() {\n assert_eq!(MAX_ZOOM, 64.0);\n assert!(Kind::A != Kind::B);\n}\n"; @@ -9200,6 +10216,19 @@ mod tests { } } + #[test] + fn a_report_only_base_hit_does_not_hide_a_newly_failing_gate() { + let path = "crates/x/src/child.rs"; + let src = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n#[cfg(target_os = \"netbsd\")]\n#[test]\nfn u() {\n assert_eq!(f(), 1);\n}\n"; + let gated = |pred: &str| Ctx { module_cfgs: [(path.to_owned(), vec![pred.to_owned()])].into_iter().collect(), ..ctx() }; + let base = lint_file(path, src, &gated("target_os=\"macos\"")); + let now = lint_file(path, src, &gated("target_os=\"netbsd\"")); + let base_off: Vec<(&str, bool)> = base.iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test.as_str(), h.report_only)).collect(); + assert_eq!(base_off, [("t", true), ("u", false)]); + let off: Vec<&str> = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, src, src, h)).map(|h| h.test.as_str()).collect(); + assert_eq!(off, ["t"], "the report-only hit becomes failing; the failing hit stays off"); + } + #[test] fn a_namesake_already_off_does_not_hide_a_newly_off_test() { let src = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; @@ -9381,8 +10410,7 @@ mod tests { #[test] fn path_override_discovery_accepts_attribute_whitespace_in_both_trees() { - let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); - let root = std::env::temp_dir().join(format!("test-lint-path-{}-{unique}", std::process::id())); + let root = TempRepo::new("path"); std::fs::create_dir_all(root.join("crates/x/src")).unwrap(); git(&root, &["init", "--quiet"]).unwrap(); let files = [ @@ -9408,13 +10436,28 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in(child, test, &ctx), [(2, "never-run")], "the discovered gates apply: {revision:?}"); } - std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn verbatim_base_blobs_preserve_literal_line_numbers_after_blank_lines() { + let root = TempRepo::new("verbatim"); + std::fs::create_dir_all(root.join("crates/x/src")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + let path = "crates/x/src/tests.rs"; + let src = "\n\n#[test]\nfn t() {\n let s = \"a\n// b\n\";\n}\n"; + std::fs::write(root.join(path), src).unwrap(); + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + let read = read_git_blob_verbatim(&root, &base, path, MAX_FILE).unwrap(); + assert_eq!(read, src); + assert_eq!(lines_in_literals(&read), [6, 7].into_iter().collect()); + assert_eq!(read_git_blob_verbatim(&root, &base, path, 8), None); + assert_eq!(read_git_blob_verbatim(&root, &base, "missing.rs", MAX_FILE), None); } #[test] fn base_blobs_over_the_limit_are_not_read() { - let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); - let root = std::env::temp_dir().join(format!("test-lint-blob-{}-{unique}", std::process::id())); + let root = TempRepo::new("blob"); std::fs::create_dir_all(root.join("crates/x/src")).unwrap(); git(&root, &["init", "--quiet"]).unwrap(); // 1 byte of text and 40 of trailing whitespace: the blob is 41 bytes. @@ -9445,13 +10488,11 @@ mod tests { assert_eq!(read_blob(&base, "crates/x/src/padded.rs", 8, |_| sizes.get("crates/x/src/padded.rs").copied(), show), None); assert_eq!(read_blob(&base, "crates/x/src/padded.rs", 41, |_| sizes.get("crates/x/src/padded.rs").copied(), show).as_deref(), Some("")); assert_eq!(*shown.borrow(), ["r:fits.rs".to_owned(), format!("{base}:crates/x/src/padded.rs")]); - std::fs::remove_dir_all(root).unwrap(); } #[test] fn base_root_routes_come_from_the_base_tree() { - let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); - let root = std::env::temp_dir().join(format!("test-lint-roots-{}-{unique}", std::process::id())); + let root = TempRepo::new("roots"); std::fs::create_dir_all(root.join("crates/x/tests/common")).unwrap(); git(&root, &["init", "--quiet"]).unwrap(); std::fs::write(root.join("crates/x/tests/smoke.rs"), "mod common;\n").unwrap(); @@ -9466,7 +10507,6 @@ mod tests { let routes = with_root_routes(Overrides::new(), &then); let parents: Vec<&str> = routes.get(shared).into_iter().flatten().map(|(p, _)| p.as_str()).collect(); assert_eq!(parents, ["crates/x/tests/smoke.rs"], "the deleted root loaded it at the base"); - std::fs::remove_dir_all(root).unwrap(); } #[test] @@ -9487,12 +10527,20 @@ mod tests { let platform = "crates/x/src/platform.rs".to_owned(); let gates = module_gates(std::slice::from_ref(&platform), &read, &overrides); assert_eq!(gates.get(&platform).map(|g| g.preds.clone()), Some(vec!["not(any(unix))".to_owned()]), "the default path elsewhere"); + let mut nested = files.clone(); + nested.insert( + "crates/x/src/lib.rs", + "#[cfg_attr(test, cfg_attr(unix, path = \"live.rs\"))]\nmod platform;\n#[cfg(target_os = \"macos\")]\nmod live;\n", + ); + let read = |p: &str| nested.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(nested.iter().map(|(p, s)| (*p, *s))); + let nested_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&live), &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(&live, test, &nested_ctx), [], "test builds on Linux load live.rs through a nested cfg_attr path"); } #[test] fn changed_lines_lists_both_paths_of_an_exact_rename() { - let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); - let root = std::env::temp_dir().join(format!("test-lint-rename-{}-{unique}", std::process::id())); + let root = TempRepo::new("rename"); std::fs::create_dir_all(root.join("crates/x/src/bin")).unwrap(); git(&root, &["init", "--quiet"]).unwrap(); let src = "#[path = \"../shared.rs\"]\nmod shared;\nfn main() {}\n"; @@ -9505,7 +10553,19 @@ mod tests { let changed = changed_lines(&root, &base).unwrap(); assert_eq!(changed.get("crates/x/src/bin/tool.rs"), Some(&None), "the old path counts as deleted"); assert_eq!(changed.get("crates/x/src/disabled/tool.rs"), Some(&None), "the new path counts as added"); - std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn changed_lines_reads_a_rust_file_git_takes_for_binary() { + let root = TempRepo::new("binary"); + std::fs::create_dir_all(root.join("crates/x/src")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + std::fs::write(root.join("crates/x/src/lib.rs"), "fn a() {}\nconst Z: &str = \"\0\";\nfn b() {}\n").unwrap(); + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + std::fs::write(root.join("crates/x/src/lib.rs"), "fn a() {}\nconst Z: &str = \"\0\";\nfn c() {}\n").unwrap(); + let changed = changed_lines(&root, &base).unwrap(); + assert_eq!(changed.get("crates/x/src/lib.rs"), Some(&Some([3].into_iter().collect())), "the changed third line"); } #[test] @@ -9706,7 +10766,7 @@ mod tests { #[test] fn deleted_files_are_kept_as_changed() { let diff = "diff --git a/crates/x/src/bin/tool.rs b/crates/x/src/bin/tool.rs\ndeleted file mode 100644\n--- a/crates/x/src/bin/tool.rs\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-#[path = \"../shared.rs\"]\n-mod shared;\n"; - let got = parse_diff(diff); + let got = parse_diff(diff, &|_, _| false); assert_eq!(got.get("crates/x/src/bin/tool.rs"), Some(&None), "{got:?}"); let base: Overrides = [("crates/x/src/shared.rs".to_owned(), vec![("crates/x/src/bin/tool.rs".to_owned(), vec![])])].into_iter().collect(); let seeds: Vec = got.keys().cloned().collect(); @@ -9808,6 +10868,36 @@ mod tests { assert_eq!(only("exact-pixel", engine), [], "document geometry outside UI code"); } + #[test] + fn exact_pixels_count_changes_through_the_second_operand() { + let src = "use egui::Rect;\n#[test]\nfn t() {\n assert_eq!(\n button_rect.width(),\n 120.0,\n \"width\"\n );\n}\n"; + let found: Vec = lint_file("crates/x/src/tests.rs", src, &ctx()).into_iter().filter(|h| h.rule == Rule::ExactPixel).collect(); + assert_eq!(found.len(), 1); + let hit = &found[0]; + assert_eq!((hit.line, hit.first, hit.last), (4, 4, 6)); + for line in [4, 5, 6] { + assert!(touches(hit, Some(&[line].into_iter().collect())), "changed line {line}"); + } + for line in [3, 7, 8] { + assert!(!touches(hit, Some(&[line].into_iter().collect())), "changed line {line}"); + } + let plain = + "use egui::Rect;\n#[test]\nfn t() {\n assert!(\n button_rect.width()\n == 120.0,\n \"width\"\n );\n}\n"; + let found: Vec = lint_file("crates/x/src/tests.rs", plain, &ctx()).into_iter().filter(|h| h.rule == Rule::ExactPixel).collect(); + assert_eq!(found.iter().map(|h| (h.line, h.last)).collect::>(), [(4, 6)], "a plain assertion's condition"); + } + + #[test] + fn mirrors_count_changes_through_the_second_operand() { + let src = "#[test]\nfn t() {\n assert_eq!(\n scale(p, 2.0),\n scale(p, 1.0) * 2.0,\n \"comparison\"\n );\n}\n"; + let found: Vec = lint_file("crates/x/src/tests.rs", src, &ctx()).into_iter().filter(|h| h.rule == Rule::Mirror).collect(); + assert_eq!(found.len(), 1); + let hit = &found[0]; + assert_eq!((hit.first, hit.last), (3, 5)); + assert!(touches(hit, Some(&[5].into_iter().collect())), "a change to the second operand"); + assert!(!touches(hit, Some(&[6].into_iter().collect())), "a change to the message"); + } + #[test] fn reads_source_covers_read_to_string_of_rust_files() { let read = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; @@ -9875,6 +10965,8 @@ mod tests { assert_eq!(only("fixture-only", looped), []); let broken = "#[test]\nfn t() {\n let n = 0;\n for n in\n results()\n {\n assert_eq!(n, 1);\n }\n}\n"; assert_eq!(only("fixture-only", broken), [], "a line break after `in`"); + let braced = "#[test]\nfn t() {\n let n = 0;\n for n in { [compute()] } {\n assert_eq!(n, 1);\n }\n}\n"; + assert_eq!(only("fixture-only", braced), [], "a block expression as the iterator"); let after = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); let mutable = "#[test]\nfn t() {\n let n = 0;\n for mut n in results() {\n n += 1;\n assert_eq!(n, 2);\n }\n}\n"; @@ -9913,6 +11005,12 @@ mod tests { assert_eq!(cfg_attr_paths(&mask(escaped), escaped.as_bytes(), 0, escaped.len()), [("unix".to_owned(), "a.rs".to_owned())]); let raw_escape = "#[cfg_attr(unix, path = r\"\\x61.rs\")]\nmod x;\n"; assert_eq!(cfg_attr_paths(&mask(raw_escape), raw_escape.as_bytes(), 0, raw_escape.len()), [("unix".to_owned(), "\\x61.rs".to_owned())]); + let nested_path = "#[cfg_attr(test, cfg_attr(unix, path = \"a.rs\"))]\nmod x;\n"; + assert_eq!( + cfg_attr_paths(&mask(nested_path), nested_path.as_bytes(), 0, nested_path.len()), + [("all(test,unix)".to_owned(), "a.rs".to_owned())], + "a path inside a nested cfg_attr" + ); } #[test] @@ -11081,6 +12179,18 @@ mod tests { let chars = pinned.replace("items(\"active\").iter().map", "items('a').iter().map").replace("items(\"active\").iter().all", "items('b').iter().all"); assert_eq!(hits(&chars), [(5, "all-unguarded")], "a character selector"); + let local = "#[test]\nfn t() {\n let mut active = true;\n let got: Vec = r.items(active).iter().map(|j| j.n).collect();\n assert_eq!(got, vec![1]);\n assert!(r.items(active).iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(local), [], "an unchanged local selector"); + let changed = local.replace(" assert!(r.items(active)", " active = false;\n assert!(r.items(active)"); + assert_eq!(hits(&changed), [(7, "all-unguarded")], "a local selector changed after the snapshot"); + let passed = local.replace(" assert!(r.items(active)", " toggle(&mut active);\n assert!(r.items(active)"); + assert_eq!(hits(&passed), [(7, "all-unguarded")], "a local selector lent mutably after the snapshot"); + let field = local.replace(" assert!(r.items(active)", " settings.active = false;\n assert!(r.items(active)"); + assert_eq!(hits(&field), [], "a field of the same name"); + let range = local.replace("let mut active = true;", "let mut n = 3;").replace("items(active)", "items(0..n)"); + assert_eq!(hits(&range), [], "an unchanged range selector"); + let changed_range = range.replace(" assert!(r.items", " n = 0;\n assert!(r.items"); + assert_eq!(hits(&changed_range), [(7, "all-unguarded")], "a range selector changed after the snapshot"); } #[test] @@ -11241,4 +12351,325 @@ mod tests { let ctx = Ctx { module_cfgs: [(child.to_owned(), vec!["any()".to_owned()])].into_iter().collect(), ..ctx() }; assert_eq!(hits_in(child, "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n", &ctx), [(2, "never-run")]); } + + #[test] + fn deleting_only_comments_or_blank_lines_changes_no_test() { + let path = "crates/x/src/tests.rs"; + let found = lint_file(path, "#[test]\nfn t() {}\n#[test]\nfn other() {}\n", &ctx()); + assert_eq!(found[0].test, "t"); + let diff = |deleted: &str| format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -3,2 +2,0 @@\n{deleted}"); + let changed = |deleted: &str| parse_diff(&diff(deleted), &|_, _| false); + for deleted in ["-// a note after the test\n", "-\n- // and a blank line\n"] { + assert!(!touches(&found[0], changed(deleted)[path].as_ref()), "{deleted:?}"); + } + for deleted in ["- assert_eq!(f(), 1);\n", "-// test-lint: allow no-assertion checked by hand\n", "-/* x\n", "-// note\n-x();\n"] { + assert!(touches(&found[0], changed(deleted)[path].as_ref()), "{deleted:?}"); + } + let base = "#[test]\nfn t() {\n let s = \"a\n// b\n\";\n let r = r#\"\n\n\"#;\n}\n// after\n"; + assert_eq!(lines_in_literals(base), [4, 5, 7, 8].into_iter().collect()); + let in_base = |p: &str, line: usize| p == path && lines_in_literals(base).contains(&line); + let in_string = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -4 +3,0 @@\n-// b\n"); + assert_eq!(parse_diff(&in_string, &in_base)[path], Some([3, 4].into_iter().collect()), "a line of a string literal"); + let after = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -10 +9,0 @@\n-// after\n"); + assert_eq!(parse_diff(&after, &in_base)[path], Some(BTreeSet::new()), "a comment outside every literal"); + } + + #[test] + fn deleting_a_skip_comment_inside_a_test_exposes_the_return() { + let path = "crates/x/src/tests.rs"; + let base = "#[test]\nfn t() {\n if unavailable() {\n // The fixture is optional.\n return;\n }\n assert_eq!(f(), 1);\n}\n// after\n"; + let src = base.replace(" // The fixture is optional.\n", ""); + assert_eq!(only("early-return", base), []); + assert_eq!(only("early-return", &src), [(4, "early-return")]); + let lines = lines_affecting_tests(base); + let can_change_test = |p: &str, line: usize| p == path && lines.contains(&line); + let diff = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -4 +3,0 @@\n- // The fixture is optional.\n"); + let changed = parse_diff(&diff, &can_change_test); + assert_eq!(changed[path], Some([3, 4].into_iter().collect())); + let found = lint_file(path, &src, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::EarlyReturn).unwrap(); + assert!(touches(hit, changed[path].as_ref())); + let blank = base.replace(" // The fixture is optional.", ""); + let blank_lines = lines_affecting_tests(&blank); + let diff = diff.replace("- // The fixture is optional.", "-"); + assert_eq!(parse_diff(&diff, &|_, line| blank_lines.contains(&line))[path], Some([3, 4].into_iter().collect())); + let after = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -9 +8,0 @@\n-// after\n"); + assert_eq!(parse_diff(&after, &can_change_test)[path], Some(BTreeSet::new())); + } + + #[test] + fn assignment_text_inside_a_quoted_value_sets_no_variable() { + for line in [" message=\"MY_SAMPLES=fixtures\"", " echo \"A=1 MY_SAMPLES=2\" >> \"$GITHUB_ENV\""] { + assert!(!upper_words(line).any(|n| n == "MY_SAMPLES"), "{line}"); + } + assert_eq!(upper_words(" message=\"x\" MY_SAMPLES=y cargo test").collect::>(), ["MY_SAMPLES"]); + } + + #[test] + fn a_path_call_of_the_same_name_does_not_call_the_closure() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!(census("let run = || app.run(c); other::run(); assert!(menu(c).is_some());"), [(2, "census")]); + assert_eq!(census("let run = || app.run(c); run(); assert!(menu(c).is_some());"), []); + } + + #[test] + fn pattern_bindings_shadow_calls_of_a_stored_closure() { + let source = |body: &str| format!("let run = || app.run(c); {body}"); + for body in ["for run in [|| ()] { run(); }", "consume(|run| { run(); });", "match value { Some(run) => { run(); } _ => {} }"] { + let code = mask(&source(body)); + assert_eq!(closure_calls(&code, "run", 0, 23, code.len(), false), Vec::::new(), "{body}"); + } + for body in ["for run in [|| ()] { run(); } run();", "for other in [|| ()] { run(); }"] { + let code = mask(&source(body)); + let calls = closure_calls(&code, "run", 0, 23, code.len(), false); + assert_eq!(calls.len(), 1, "{body}"); + assert_eq!(&code[calls[0]..calls[0] + 5], b"run()", "{body}"); + } + let src = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let run = || app.run(c);\n for run in [|| ()] { run(); }\n assert!(menu(c).is_some());\n }\n}\n"; + assert_eq!(only("census", src), [(2, "census")]); + } + + #[test] + fn struct_field_labels_preserve_outer_closure_calls_and_initializers() { + for body in [ + "for Row { run: other } in rows { run(); }", + "consume(|Row { run: other }| { run(); });", + "match value { Row { run: other } => { run(); } }", + ] { + let code = mask(&format!("let run = || app.run(c); {body}")); + let calls = closure_calls(&code, "run", 0, 23, code.len(), false); + assert_eq!(calls.len(), 1, "{body}"); + assert_eq!(&code[calls[0]..calls[0] + 5], b"run()", "{body}"); + assert!(reaching_init(&code, "run", calls[0]).flatten().is_some(), "{body}"); + } + for body in [ + "for Row { run } in rows { run(); }", + "for Row { x: run } in rows { run(); }", + "consume(|Row { run }| { run(); });", + "consume(|Row { x: run }| { run(); });", + "match value { Row { run } => { run(); } }", + "match value { Row { x: run } => { run(); } }", + ] { + let code = mask(&format!("let run = || app.run(c); {body}")); + assert_eq!(closure_calls(&code, "run", 0, 23, code.len(), false), Vec::::new(), "{body}"); + let at = code.windows(5).rposition(|word| word == b"run()").unwrap(); + assert_eq!(reaching_init(&code, "run", at), Some(None), "{body}"); + } + } + + #[test] + fn a_conditional_equality_does_not_guard_all() { + let src = "#[test]\nfn t() {\n assert_eq!(xs, [1]);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + let conditional = src.replace(" assert_eq!(xs, [1]);", " if check_first { assert_eq!(xs, [1]); }"); + assert_eq!(only("all-unguarded", &conditional), [(4, "all-unguarded")]); + let same_branch = + "#[test]\nfn t() {\n if check_first {\n assert_eq!(xs, [1]);\n assert!(xs.iter().all(|x| *x > 0));\n }\n}\n"; + assert_eq!(hits(same_branch), [], "the equality runs whenever the assertion in its branch does"); + } + + #[test] + fn a_count_stops_guarding_when_a_mutable_reference_is_passed_on() { + let src = + "#[test]\nfn t() {\n let xs = &mut f();\n let n = xs.len();\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + let taken = src.replace(" assert!(xs", " std::mem::take(xs);\n assert!(xs"); + assert_eq!(hits(&taken), [(7, "all-unguarded")]); + let printed = src.replace(" assert!(xs", " println!(\"{:?}\", xs);\n assert!(xs"); + assert_eq!(hits(&printed), [], "a macro only reads it"); + } + + #[test] + fn a_grouped_read_preserves_a_mutable_references_count_guard() { + let src = + "#[test]\nfn t() {\n let xs = &mut f();\n let n = xs.len();\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + for read in ["(xs).len();", "(a, xs);", "println!(\"{:?}\", xs);"] { + let grouped = src.replace(" assert!(xs", &format!(" {read}\n assert!(xs")); + assert_eq!(only("all-unguarded", &grouped), [], "{read}"); + } + for call in ["std::mem::take(xs);", "consume(a, xs);", "consumer.consume(xs);", "(consumer)(xs);"] { + let passed = src.replace(" assert!(xs", &format!(" {call}\n assert!(xs")); + assert_eq!(only("all-unguarded", &passed), [(7, "all-unguarded")], "{call}"); + } + } + + #[test] + fn assigning_a_grouped_collection_invalidates_its_count_guard() { + let src = + "#[test]\nfn t() {\n let mut xs = f();\n let n = xs.len();\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(only("all-unguarded", src), []); + for change in ["(xs) = vec![];", "((xs)) = vec![];", "(xs, _) = (vec![], 0);", "[_, (xs, _)] = [x, (vec![], 0)];"] { + let changed = src.replace(" assert!(xs", &format!(" {change}\n assert!(xs")); + assert_eq!(only("all-unguarded", &changed), [(7, "all-unguarded")], "{change}"); + } + for read in ["(xs).len();", "let pair = (&xs, 0);", "assert_eq!((&xs, 0), (&ys, 0));"] { + let read = src.replace(" assert!(xs", &format!(" {read}\n assert!(xs")); + assert_eq!(only("all-unguarded", &read), [], "{read}"); + } + } + + #[test] + fn calls_in_a_nested_fn_body_do_not_poll() { + for item in ["fn unused() {\n probe();\n }", "fn unused(f: F) -> u8 {\n probe()\n }"] { + let src = format!( + "fn wait() {{\n let t0 = Instant::now();\n while t0.elapsed() < D {{\n {item}\n thread::sleep(D);\n }}\n}}\n" + ); + assert_eq!(hits(&src).iter().filter(|h| h.1 == "sleep").count(), 1, "{src}"); + } + let direct = + "fn wait() {\n let t0 = Instant::now();\n while t0.elapsed() < D {\n probe();\n thread::sleep(D);\n }\n}\n"; + assert_eq!(hits(direct).iter().filter(|h| h.1 == "sleep").count(), 0); + } + + #[test] + fn conversions_of_types_the_test_names_are_not_fixture_reads() { + for src in [ + "#[test]\nfn t() {\n let result = Input { n: 5 }.to_string();\n assert_eq!(result, \"5\");\n}\n", + "#[test]\nfn t() {\n let input = Input { n: 5 };\n let shown = input.to_string();\n assert_eq!(shown, \"5\");\n}\n", + "#[test]\nfn t() {\n let shown = Kind::A.to_string();\n assert_eq!(shown, \"a\");\n}\n", + "#[test]\nfn t() {\n let c: u8 = 5.into();\n assert_eq!(c, 5);\n}\n", + "#[test]\nfn t() {\n let pair = Pair(5, Kind::A);\n assert_eq!(pair.1.to_string(), \"a\");\n}\n", + ] { + assert_eq!(only("fixture-only", src), [], "{src}"); + } + for src in [ + "#[test]\nfn t() {\n let name = \"x\".to_string();\n assert_eq!(name, \"x\");\n}\n", + "#[test]\nfn t() {\n let xs = vec![Input { n: 5 }];\n assert_eq!(xs.len(), 1);\n}\n", + "#[test]\nfn t() {\n let input = Input { n: 5 };\n assert_eq!(input.n.to_string(), \"5\");\n}\n", + "#[test]\nfn t() {\n let pair = Pair(5, Kind::A);\n assert_eq!(pair.0.to_string(), \"5\");\n}\n", + ] { + assert_eq!(only("fixture-only", src), [(2, "fixture-only")], "{src}"); + } + } + + #[test] + fn operators_on_user_values_are_not_fixture_reads() { + for expr in [ + "Amount(2) + Amount(3)", + "2 * Amount(3)", + "Amount(3) % 2", + "Amount(2) << 1", + "1 >> Amount(2)", + "Amount(2) & Amount(3)", + "Amount(2) | Amount(3)", + "Amount(2) ^ Amount(3)", + "-Amount(2)", + "!Amount(2)", + "Some(Amount(2) + Amount(3))", + "2 + vec![Amount(3)]", + ] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({expr}, Amount(5));\n}}\n"); + assert_eq!(only("constant-echo", &src), [], "{expr}"); + } + for expr in ["a + a", "a - a", "a / 2", "-a", "!a", "row.0 + a", "(a) + a", "&a + &a"] { + let src = format!("#[test]\nfn t() {{\n let a = Amount(2);\n let row = Row(a);\n assert_eq!({expr}, Amount(4));\n}}\n"); + assert_eq!(only("fixture-only", &src), [], "{expr}"); + } + let computed = "#[test]\nfn t() {\n let a = Amount(2);\n let actual = a + a;\n assert_eq!(actual, Amount(4));\n}\n"; + assert_eq!(only("fixture-only", computed), []); + let indexed = "#[test]\nfn t() {\n let xs = [Amount(2), Amount(3)];\n assert_eq!(xs[0] + xs[1], Amount(5));\n}\n"; + assert_eq!(only("fixture-only", indexed), [], "an indexed element of a user-value array"); + let primitive = indexed.replace("Amount(2), Amount(3)", "2, 3"); + assert_eq!(only("fixture-only", &primitive), [(2, "fixture-only")], "an indexed element of a primitive array"); + } + + #[test] + fn literal_operators_and_user_value_borrows_remain_inert() { + for expr in ["2 + 3", "MAX * 2", "!2", "-2", "Amount(2) == Amount(3)", "&Amount(2)", "Amount(2)..Amount(3)", "(Amount(2), 2 + 3)"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({expr}, EXPECTED);\n}}\n"); + assert_eq!(only("constant-echo", &src), [(2, "constant-echo")], "{expr}"); + } + for expr in ["&a", "a == a", "a != a", "a < a", "a >= a", "a..a", "row.0 + 2", "xs.len() + 2"] { + let src = format!( + "#[test]\nfn t() {{\n let a = Amount(2);\n let row = Row(2);\n let xs = vec![a];\n assert_eq!({expr}, EXPECTED);\n}}\n" + ); + assert_eq!(only("fixture-only", &src), [(2, "fixture-only")], "{expr}"); + } + } + + #[test] + fn container_conversions_can_test_element_implementations() { + for (init, field) in + [("vec![Input { n: 5 }]", "[0].n"), ("vec![Some(Input { n: 5 })]", "[0].as_ref().unwrap().n"), ("vec![vec![Input { n: 5 }]]", "[0][0].n")] + { + let src = format!("#[test]\nfn t() {{\n let xs = {init};\n let cloned = xs.clone();\n assert_eq!(cloned{field}, 6);\n}}\n"); + assert_eq!(only("fixture-only", &src), [], "{init}"); + } + let alias = "#[test]\nfn t() {\n let input = Input { n: 5 };\n let xs = vec![input; 2];\n let alias = xs;\n assert_eq!(alias.to_vec()[0].n, 6);\n}\n"; + assert_eq!(only("fixture-only", alias), []); + let view = alias.replace("alias.to_vec()", "alias.as_slice().to_vec()"); + assert_eq!(only("fixture-only", &view), []); + for expr in ["vec![Input { n: 5 }].len()", "vec![5].clone().len()"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({expr}, 1);\n}}\n"); + assert_eq!(only("constant-echo", &src), [(2, "constant-echo")], "{expr}"); + } + } + + #[test] + fn conversions_of_container_method_results_do_not_inspect_elements() { + let local = |name: &str, _: usize| match name { + "xs" => Some((false, "vec![Input{n:5}]".to_owned(), 0)), + "row" => Some((true, "Row{items:vec![Input{n:5}]}".to_owned(), 0)), + _ => None, + }; + for receiver in [ + "vec![Input{n:5}].len()", + "[Input{n:5}].is_empty()", + "(Input{n:5},).type_id()", + "Some(Input{n:5}).is_some()", + "xs.len()", + "row.items.is_empty()", + "vec![Input{n:5}].as_slice().len()", + ] { + assert!(!holds_user_value(receiver, 0, &local), "{receiver}"); + } + for expr in ["vec![Input { n: 5 }].len().to_string()", "vec![Input { n: 5 }].is_empty().to_string()"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({expr}, \"1\");\n}}\n"); + assert_eq!(only("constant-echo", &src), [(2, "constant-echo")], "{expr}"); + } + for receiver in [ + "vec![Input{n:5}]", + "[Input{n:5}]", + "(Input{n:5},)", + "Some(Input{n:5})", + "xs", + "row.items", + "vec![Input{n:5}].as_slice().as_ref().clone().to_vec().to_owned()", + ] { + assert!(holds_user_value(receiver, 0, &local), "{receiver}"); + } + } + + #[test] + fn qualified_user_types_and_their_fields_keep_their_value_kind() { + for init in ["Input { n: 5 }", "model::Input { n: 5 }", "outer::model::Input { n: 5 }", "model::Input(5)"] { + let src = format!("#[test]\nfn t() {{\n let input = {init};\n assert_eq!(input.to_string(), \"5\");\n}}\n"); + assert_eq!(only("fixture-only", &src), [], "{init}"); + } + for (init, field) in [("model::Input { n: 5 }", "n"), ("model::Input(5)", "0")] { + let src = format!("#[test]\nfn t() {{\n let input = {init};\n assert_eq!(input.{field}.to_string(), \"5\");\n}}\n"); + assert_eq!(only("fixture-only", &src), [(2, "fixture-only")], "{init}"); + let user = src.replacen('5', "model::Kind::A", 1); + assert_eq!(only("fixture-only", &user), [], "{init}"); + } + } + + #[test] + fn field_initializers_resolve_names_before_their_binding() { + let src = "#[test]\nfn t() {\n let input = Input { n: 5 };\n let input = Input { n: input.n };\n assert_eq!(input.n.to_string(), \"5\");\n}\n"; + assert_eq!(only("fixture-only", src), [(2, "fixture-only")]); + let user_field = src.replace("n: 5", "n: Kind::A"); + assert_eq!(only("fixture-only", &user_field), [], "the earlier field holds a user type"); + let aliased = src.replace( + " assert_eq!(input.n", + " let alias = input;\n let alias = alias;\n let input = Input { n: Kind::A };\n assert_eq!(alias.n", + ); + assert_eq!(only("fixture-only", &aliased), [(2, "fixture-only")], "the alias resolves before the later binding"); + let user_alias = user_field.replace( + " assert_eq!(input.n", + " let alias = input;\n let alias = alias;\n let input = Input { n: 5 };\n assert_eq!(alias.n", + ); + assert_eq!(only("fixture-only", &user_alias), [], "the aliased field holds a user type"); + } }