diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 3861915380..c27d4a7a44 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)) + }; + // The work tree is the new side of the diff. A file that cannot be read adds no blank lines. + let new_files: RefCell>> = RefCell::default(); + let code_after = |path: &str, line: usize| { + let mut cache = new_files.borrow_mut(); + let src = cache.entry(path.to_owned()).or_insert_with(|| read_small(root, path)); + src.as_deref().map_or(line, |s| next_code_line(s, line)) + }; + let mut out = parse_diff_in(&diff, &can_change_test, &code_after); for path in git(root, &["ls-files", "-z", "--others", "--exclude-standard", "--", "*.rs"])?.split('\0').filter(|p| !p.is_empty()) { out.insert(path.to_owned(), None); } Ok(out) } +/// [`parse_diff_in`] for a diff whose new side has no blank line after a deletion. +#[cfg(test)] +fn parse_diff(diff: &str, can_change_test: &dyn Fn(&str, usize) -> bool) -> BTreeMap>> { + parse_diff_in(diff, can_change_test, &|_, line| line) +} + +/// The first line of `src`, from 1-based `line` on, that holds code outside comments, or `line` +/// when none does. A line with only a block comment (`/* spacer */`) holds no code. +fn next_code_line(src: &str, line: usize) -> usize { + let code = mask_parts(src, true, false); + code.split(|&c| c == b'\n').enumerate().skip(line.saturating_sub(1)).find(|(_, l)| !l.trim_ascii().is_empty()).map_or(line, |(n, _)| n + 1) +} + /// The changed new-side lines in each file. A pure deletion includes its anchor and the following -/// line, or just line 1 when the anchor is 0. -fn parse_diff(diff: &str) -> BTreeMap>> { +/// 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. +/// When a hunk removes only blank lines and line comments and one of them can change a test, the +/// changed lines also run from the line after the hunk's new lines up to `code_after(path, line)`, +/// the next new-side line with code, so a `return` that a removed skip comment explained counts +/// as changed. +fn parse_diff_in( + diff: &str, + can_change_test: &dyn Fn(&str, usize) -> bool, + code_after: &dyn Fn(&str, usize) -> usize, +) -> 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 hunk whose removed lines are being read: its new-side start and line count, whether a + // removed line so far can change code, whether every removed line so far is blank or a line + // comment, and the old line number of the next removed line. + type Removed = Option<(usize, usize, bool, bool, usize)>; + let mut deletion: Removed = None; + let flush = |deletion: &mut Removed, current: &Option, out: &mut BTreeMap>>| { + if let (Some((start, count, true, inert, _)), Some(path)) = (deletion.take(), current.as_ref()) { + // Only removed comments reach past the next line, to the code that they explained. + let next = if count == 0 { start.saturating_add(1) } else { start.saturating_add(count) }; + let end = if inert { next.max(code_after(path, next)) } else { next }; + if let Some(Some(lines)) = out.get_mut(path) { + if count == 0 { + lines.extend(start.max(1)..=end); + } else if inert { + lines.extend(next..=end); + } + } + } + }; for line in diff.lines() { + if let (Some((_, _, significant, inert, old_line)), false, Some(path)) = (deletion.as_mut(), header, current.as_deref()) { + if let Some(deleted) = line.strip_prefix('-') { + let blank_or_comment = inert_deleted_line(deleted); + *inert &= blank_or_comment; + *significant |= !blank_or_comment || 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") { @@ -791,17 +882,58 @@ fn parse_diff(diff: &str) -> BTreeMap>> { } else if let (Some(hunk), Some(path)) = (line.strip_prefix("@@ "), ¤t) { header = false; if let (Some((start, count)), Some(Some(lines))) = (hunk_range(hunk), out.get_mut(path)) { - if count == 0 { - lines.extend(start.max(1)..=start.saturating_add(1)); - } else { + if count > 0 { lines.extend(start..start + count); } + deletion = Some((start, count, false, true, hunk_old_start(hunk).unwrap_or(0))); } } } + 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 { @@ -863,38 +995,380 @@ fn ci_env(root: &Path, files: &[String]) -> Result, String> { Ok(names) } -/// Workflow mapping keys and assignments with capitalized environment variable names. +/// Workflow mapping keys and assignments with capitalized environment variable names. A `run: |` +/// or `run: >` block is read as one script, so a `{ … }` group that spans lines keeps its +/// redirection. The block ends at the first line indented no deeper than the `run` key, and a +/// folded block joins its lines as YAML does ([`fold_block`]). fn upper_words(text: &str) -> impl Iterator + '_ { - text.lines().flat_map(|line| { - let line = workflow_code(line); - let start = line.trim_start().strip_prefix("- ").unwrap_or(line.trim_start()).trim_start(); - let mapping = - start.split_once(':').filter(|(name, rest)| env_assignment_name(name) && (rest.is_empty() || rest.starts_with(char::is_whitespace))); - let assignments = line.match_indices('=').filter_map(move |(at, _)| { + let mut units: Vec<(String, bool)> = vec![]; + let mut lines = text.lines().peekable(); + while let Some(line) = lines.next() { + let code = workflow_code(line); + let start = code.trim_start().strip_prefix("- ").unwrap_or(code.trim_start()).trim_start(); + // `start` is a suffix of `code`, which is a prefix of `line`, so this is the key's column. + let key = code.len() - start.len(); + let block = start.strip_prefix("run:").filter(|rest| rest.starts_with(char::is_whitespace)).and_then(|rest| { + let rest = rest.trim(); + let folded = rest.starts_with('>'); + let marks = rest.strip_prefix(['|', '>'])?; + // An indentation indicator gives the content's indentation past the `run` key's column. + let indent = marks.bytes().find(u8::is_ascii_digit).map(|d| key + usize::from(d - b'0')); + marks.bytes().all(|c| matches!(c, b'-' | b'+') || c.is_ascii_digit()).then_some((folded, indent)) + }); + let Some((folded, indent)) = block else { + units.push((line.to_owned(), false)); + continue; + }; + let mut body: Vec<&str> = vec![]; + while let Some(&next) = lines.peek().filter(|l| l.trim().is_empty() || l.len() - l.trim_start().len() > key) { + body.push(next); + lines.next(); + } + let script = if folded { fold_block(&body, indent) } else { body.iter().map(|l| format!("{}\n", l.trim_start())).collect() }; + units.push((script, true)); + } + units.into_iter().flat_map(|(unit, script)| { + let (mapping, shell) = if script { + (None, unit) + } else { + let line = workflow_code(&unit); + 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))) + .map(|(name, _)| name.to_owned()); + // The script of a `run:` line, or the line without its list marker, so the first shell + // word is the command's own. + let plain = start.strip_prefix("run:").filter(|rest| rest.starts_with(char::is_whitespace)).unwrap_or(start); + (mapping, workflow_scalar(start).unwrap_or_else(|| plain.to_owned())) + }; + let code = shell_code(&shell); + let line = code.as_str(); + let assignments = line.match_indices('=').filter_map(|(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';')); + // A command separator or a subshell opener ends the word before it (`true&&NAME=x`). + let word_start = + |p: usize| p == 0 || line.as_bytes().get(p - 1).is_some_and(|c| c.is_ascii_whitespace() || matches!(c, b';' | b'&' | b'|' | 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"`). + // A word is an assignment where the shell reads it as one: before the command name + // (`NAME=x cargo test`), or for a command that reads it as one (`export`, `env`) or + // that writes it to `$GITHUB_ENV`, not for one that searches for it (`grep`). + let boundary = match open_quote(line, from) { + None => word_start(from) && (command_name(line, from).is_none() || assigned_by_command(line, from)), + Some(q) => q + 1 == from && word_start(q) && assigned_by_command(line, 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.into_iter().chain(assignments).collect::>() }) } -/// 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`. +/// The text of a folded (`>`) YAML block scalar from its content lines. A line break between two +/// lines at the block's indentation becomes a space, a line break before blank lines is dropped and +/// each blank line becomes a line break, and lines indented deeper keep their line breaks and their +/// extra indentation (YAML 1.2.2, section 8.1.3). The block's indentation is `explicit`, from an +/// indentation indicator, or else that of its first line that is not blank. +fn fold_block(body: &[&str], explicit: Option) -> String { + let indent = |l: &str| l.len() - l.trim_start().len(); + let base = explicit.unwrap_or_else(|| body.iter().find(|l| !l.trim().is_empty()).map_or(0, |l| indent(l))); + let (mut out, mut prev, mut blanks) = (String::new(), None::, 0usize); + for line in body { + if line.trim().is_empty() { + blanks += 1; + continue; + } + let deeper = indent(line) > base; + let breaks = match prev { + None => blanks, + Some(was_deeper) if was_deeper || deeper => blanks + 1, + Some(_) => blanks, + }; + if breaks == 0 && prev.is_some() { + out.push(' '); + } + out.extend(std::iter::repeat_n('\n', breaks)); + out.push_str(if deeper { &line[base..] } else { line.trim_start() }); + (prev, blanks) = (Some(deeper), 0); + } + out.push('\n'); + out +} + +/// The shell words of `text`, split at whitespace outside quotes. A backslash before a line break +/// continues the line. +fn shell_words(text: &str) -> Vec<&str> { + let (mut out, mut quote, mut escaped, mut start) = (vec![], None, false, None); + for (i, c) in text.char_indices() { + if escaped { + escaped = false; + if c == '\n' + && let Some(s) = start.take().filter(|&s| s + 1 < i) + { + out.push(&text[s..i - 1]); + } + continue; + } + if c == '\\' && quote != Some('\'') { + escaped = true; + start.get_or_insert(i); + continue; + } + if let Some(q) = quote { + if q == c { + quote = None; + } + continue; + } + if c.is_whitespace() { + if let Some(s) = start.take() { + out.push(&text[s..i]); + } + continue; + } + if matches!(c, '\'' | '"') { + quote = Some(c); + } + start.get_or_insert(i); + } + if let Some(s) = start { + out.push(&text[s..]); + } + out +} + +/// Whether a shell word assigns a variable (`name=value`). +fn shell_assignment(word: &str) -> bool { + word.split_once('=').is_some_and(|(name, _)| { + name.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') && name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_') + }) +} + +/// The command name of the shell command that holds offset `at`, when it starts before `at`: +/// the first word that is not an assignment, a group opener or a keyword such as `then`. +fn command_name(line: &str, at: usize) -> Option<&str> { + let (start, _) = shell_command(line, at); + command_word(&line[start..at]) +} + +/// The first word of `text` that names a command. +fn command_word(text: &str) -> Option<&str> { + const PREFIXES: &[&str] = &["{", "(", "!", "then", "do", "else", "elif", "if", "while", "until", "time", "command", "builtin", "exec"]; + shell_words(text).into_iter().find(|w| !PREFIXES.contains(w) && !shell_assignment(w)) +} + +/// Whether a shell command writes to the environment file: a redirection to `$GITHUB_ENV`, or a +/// pipeline command that takes it as its output file (`tee`, `Out-File`, `Add-Content`, +/// `Set-Content`). An `echo` that only names the path prints it. A later redirection of standard +/// output in the same pipeline command (`>> "$GITHUB_ENV" > setup.log`) replaces the first one. +fn writes_env_file(command: &str) -> bool { + command.match_indices("GITHUB_ENV").any(|(at, name)| { + let before = command[..at].trim_end_matches(['"', '\'', '$', '{']); + let before = before.strip_suffix("env:").unwrap_or(before).trim_end_matches(['"', '\'', '$', '{']).trim_end(); + if let Some(op) = before.strip_suffix('>') { + // Only a redirection of standard output (`>>`, `1>>`, `&>>`) carries what is printed. + let op = op.strip_suffix('>').unwrap_or(op); + let digits = op.len() - op.trim_end_matches(|c: char| c.is_ascii_digit()).len(); + let word = op[..op.len() - digits].is_empty() || op[..op.len() - digits].ends_with(char::is_whitespace); + if digits > 0 && word && &op[op.len() - digits..] != "1" { + return false; + } + return !stdout_redirected(command[at + name.len()..].trim_start_matches(['"', '\'', '}'])); + } + let element = before.rfind('|').map_or(before, |p| &before[p + 1..]); + command_word(element).is_some_and(|w| ["tee", "out-file", "add-content", "set-content"].contains(&w.to_ascii_lowercase().as_str())) + }) +} + +/// Whether `rest`, the text after a redirection's target, redirects standard output again before +/// the pipeline's next command, a command separator (`;`, `&&`, `&`, a line break) or the end of +/// the group that holds it: a `>`, `>>`, `1>`, `&>` or +/// `>&2` outside quotes. A redirection of another descriptor (`2>`, `2>&1`) leaves standard output +/// where it was, and so does one of an enclosing `( … )` or `{ … }` group. +fn stdout_redirected(rest: &str) -> bool { + let b = rest.as_bytes(); + let (mut quote, mut escaped, mut depth) = (None, false, 0usize); + for (i, &c) in b.iter().enumerate() { + if escaped { + escaped = false; + continue; + } + if c == b'\\' && quote != Some(b'\'') { + escaped = true; + continue; + } + if let Some(q) = quote { + if q == c { + quote = None; + } + continue; + } + match c { + b'\'' | b'"' => quote = Some(c), + b'(' | b'{' => depth += 1, + b')' | b'}' if depth == 0 => return false, + b')' | b'}' => depth -= 1, + b'|' => return false, + // A redirection of a later command applies to that command only. + b';' | b'\n' if depth == 0 => return false, + b'&' if depth == 0 && b.get(i + 1) != Some(&b'>') && (i == 0 || !matches!(b[i - 1], b'>' | b'<')) => return false, + b'>' if i == 0 || b[i - 1] != b'>' => { + // A descriptor number counts only when it is a whole word (`2>`, not `a2>`). + let digits = b[..i].iter().rev().take_while(|d| d.is_ascii_digit()).count(); + let from = i - digits; + let fd = if from == 0 || b[from - 1].is_ascii_whitespace() { &rest[from..i] } else { "" }; + if fd.is_empty() || fd == "1" { + return true; + } + } + _ => {} + } + } + false +} + +/// 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 an `echo` or `printf` command, and that command's +/// pipeline does not write to `$GITHUB_ENV` ([`writes_env_file`]). fn printed(line: &str, from: usize) -> bool { - let command = line[..from].rsplit([';', '&', '|']).next().unwrap_or_default().as_bytes(); - let prints = ["echo", "printf"].iter().any(|w| !words(command, w.as_bytes(), 0, command.len()).is_empty()); - prints && !line.contains("GITHUB_ENV") + let (start, end) = shell_command(line, from); + command_word(&line[start..from]).is_some_and(|w| matches!(w, "echo" | "printf")) && !writes_env_file(&line[start..end]) +} + +/// Whether the shell command that holds the word at `word` reads it as an assignment: an `export`, +/// `env`, `declare`, `local`, `readonly` or `typeset` command, or a pipeline that writes to +/// `$GITHUB_ENV` ([`writes_env_file`]). +fn assigned_by_command(line: &str, word: usize) -> bool { + let (start, end) = shell_command(line, word); + command_word(&line[start..word]).is_some_and(|w| ["export", "env", "declare", "local", "readonly", "typeset"].contains(&w)) + || writes_env_file(&line[start..end]) +} + +/// The command of a shell line that holds offset `at`, as `(start, end)`. It starts after the last +/// `;`, `&`, `|` or line break before `at` outside quotes. Its pipeline ends at the next `;`, `&`, +/// `||` or line break outside quotes, since `|` passes its output on. A command inside a `{ … }` +/// or `( … )` group runs on to the group's redirection (`{ echo A=1; } >> "$GITHUB_ENV"`). A +/// backslash before a line break continues the command, and `&` in a redirection (`>&2`) does not +/// end it. +fn shell_command(line: &str, at: usize) -> (usize, usize) { + let b = line.as_bytes(); + let (mut quote, mut escaped) = (None, false); + let (mut start, mut depth, mut floor) = (0, 0i32, 0i32); + for (i, &c) in b.iter().enumerate() { + if escaped { + escaped = false; + continue; + } + if c == b'\\' && quote != Some(b'\'') { + escaped = true; + continue; + } + if let Some(q) = quote { + if q == c { + quote = None; + } + continue; + } + match c { + b'\'' | b'"' => quote = Some(c), + b'{' | b'(' => depth += 1, + b'}' | b')' => depth -= 1, + _ => {} + } + if i < at { + floor = floor.min(depth); + } + let redirect = c == b'&' && (i.checked_sub(1).is_some_and(|p| matches!(b[p], b'>' | b'<')) || b.get(i + 1) == Some(&b'>')); + let separator = (matches!(c, b';' | b'&' | b'\n') && !redirect) || (c == b'|' && (i < at || b.get(i + 1) == Some(&b'|'))); + if !separator { + continue; + } + if i < at { + start = i + 1; + } else if depth <= floor { + return (start, i); + } + } + (start, b.len()) } fn env_assignment_name(name: &str) -> bool { name.starts_with(|c: char| c.is_ascii_uppercase()) && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_') } -/// Removes comment text outside quotes from a workflow line. -fn workflow_code(line: &str) -> &str { +/// 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. A YAML comment starts at a `#` at the +/// start of the line or after whitespace; `one#two` is plain text. +fn workflow_code(line: &str) -> &str { + let (mut quote, mut escaped, mut prev) = (None, false, None); for (at, c) in line.char_indices() { if escaped { escaped = false; @@ -905,14 +1379,45 @@ fn workflow_code(line: &str) -> &str { } else if quote.is_none() { match c { '\'' | '"' => quote = Some(c), - '#' => return &line[..at], + '#' if prev.is_none_or(char::is_whitespace) => return &line[..at], _ => {} } } + prev = Some(c); } 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. A +/// comment starts at a `#` that starts a word, so `one#two` stays. +fn shell_code(script: &str) -> String { + let (mut out, mut quote, mut escaped, mut comment) = (String::with_capacity(script.len()), None, false, false); + let mut prev: Option = None; + 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), + '#' if prev.is_none_or(|p| p.is_whitespace() || matches!(p, ';' | '&' | '|' | '(' | ')' | '<' | '>')) => comment = true, + _ => {} + } + } + prev = Some(c); + 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 +1625,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 +1640,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() @@ -1210,6 +1723,26 @@ fn tests_in(m: &[u8]) -> Vec { out } +/// The `{` that opens the body of a `fn` whose signature continues at `from`. The body comes after +/// the signature, whose parameters, array types (`[u8; 2]`) and braced const arguments +/// (`Foo<{ N + 1 }>`) can hold `;` and braces. `None` for a declaration without a body. +fn body_open(m: &[u8], from: usize) -> Option { + let mut open = from; + 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'{' => return Some(open), + b';' if angles == 0 => return None, + _ => {} + } + open += 1; + } +} + /// The function an attribute at `attr` (ending at `from`) belongs to. fn fn_after(m: &[u8], attr: usize, from: usize) -> Option { // The attribute's arguments, and the attributes after it, can hold `;` (`#[test_case(1; "one")]`). @@ -1228,10 +1761,7 @@ 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; - } + let open = body_open(m, name_end)?; let close = matching(m, open)?; // The item starts after the previous item or block opening; comments before it are masked. // Inner attributes (`#![…]`) there belong to the enclosing module or crate. @@ -1291,11 +1821,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,14 +2107,16 @@ 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; } - let open = end + m[end..].iter().position(|&c| c == b'{' || c == b';')?; - if m[open] != b'{' { - return None; - } + let open = if is_macro { + let open = end + m[end..].iter().position(|&c| c == b'{' || c == b';')?; + (m[open] == b'{').then_some(open)? + } else { + body_open(m, end)? + }; Some((&m[start..end], is_macro, open, matching(m, open)?)) } @@ -1676,6 +2209,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 +2219,50 @@ 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 end = statement_end(m, at); + // Parentheses around the whole value (`(|| { … })`) do not call it; `(|| { … })()` does. + let mut limit = end; + // A tuple (`(|| (), { … })`) evaluates each element, so only one grouped expression is + // unwrapped. + while m.get(value) == Some(&b'(') { + match matching(m, value) { + Some(close) if skip_ws(m, close + 1) == limit && !tuple_parts(&m[value + 1..close]) => { + limit = close; + value = skip_ws(m, value + 1); + } + _ => break, + } + } + 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); + } + // A closure (`async || …` too) is never called. An async block is dropped when it is the + // whole value; `async { … }.await` runs it. + let unrun = m.get(value) == Some(&b'|') + || (is_async && m.get(value) == Some(&b'{') && matching(m, value).is_some_and(|close| skip_ws(m, close + 1) == limit)); + if unrun && end < t.close { + blank(&mut out, at, end + 1); + } + } } out } @@ -1987,6 +2566,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); @@ -2021,23 +2609,125 @@ const PLAIN_ASSERTS: &[&str] = &["assert", "debug_assert", "prop_assert"]; /// Calls whose result says how many items a collection has. const SIZE_CHECKS: &[&str] = &[".len()", ".is_empty()", ".count()", ".first()", ".any(", ".next()", ".last()"]; +/// A size check of a plain local: its name, where its operand ends, where the local is read, and +/// the count it is compared with ([`compared_count`]). +type SizeCheck = (String, usize, usize, Option<(String, bool)>); + 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()`, `xs.iter().count()`), each with where its operand + // ends and the count it compares with: one guards an `.all(…)` assertion only when no code + // between them may shrink or replace that local, and when that count gives the assertion's + // iterator an item (`.windows(2)` needs two). + // Each also keeps where the local is read, for a check in the assertion that holds `.all(…)`. + let mut direct: Vec = 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]; + // An iterator over the local (`xs.iter().count()`) has the local's items. + let mut source = head; + while let Some(s) = [".iter()", ".into_iter()", ".iter_mut()"].iter().find_map(|m| source.strip_suffix(m)) { + source = s; + } + let start = source.bytes().rposition(|c| !is_ident(c)).map_or(0, |p| p + 1); + let receiver = &source[start..]; + let plain = plain_local(receiver) && !source[..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!("{}{g}", &head[start..]); + let kept = words(&body, receiver.as_bytes(), from, to) + .into_iter() + .filter(|&p| norm(&body[p..to]).starts_with(&read)) + .find(|&p| !may_shrink(&body[..to], receiver.as_bytes(), p + receiver.len())); + if let (true, Some(read_at)) = (plain, kept) { + let count = compared_count(a, &body, v.t.open, (&text[..start], &text[i + g.len()..]), &read); + direct.push((receiver.to_owned(), to, read_at, count)); + } + !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() }; - if checked || first_item_guard(&body, &sizes) { + let (any_item, item_roots) = first_item_guard(&body, &sizes); + if checked || any_item { return vec![]; } v.asserts .iter() .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())) + .filter(|a| { + let at = a.at - v.t.open; + let end = a.args.last().map_or(at, |&(_, to)| to - v.t.open); + let cond = v.first_arg(a); + // The body offset of each byte of `cond`, which has no whitespace. + let offsets: Vec = a + .args + .first() + .map(|&(f, t)| (f..t).filter(|&k| !v.file.m[k].is_ascii_whitespace()).map(|k| k - v.t.open).collect()) + .unwrap_or_default(); + // Each `.all(…)` with the local its receiver starts from, the items it needs, and where + // it is called. An `.all(…)` inside another one's predicate reads an item, not a local. + let mut predicate_end = 0; + let alls: Vec<(Option<&str>, usize, usize)> = cond + .match_indices(".all(") + .filter(|&(i, _)| { + let outer = i >= predicate_end; + if outer { + predicate_end = matching(cond.as_bytes(), i + 4).unwrap_or(cond.len()); + } + outer + }) + .map(|(i, _)| { + let (receiver, need) = receiver_need(&cond[..i], &sizes); + (chain_root(receiver), need, offsets.get(i).copied().unwrap_or(at)) + }) + .collect(); + // A size check guards an `.all(…)` over the same local when it gives enough items. A check + // before the assertion holds while nothing between them shrinks or replaces the local; a + // check inside it, or after it, while nothing between the read and the `.all(…)` changes + // its item count at all (`xs.push(1)` included). + let guards = |root: Option<&str>, need: usize, call: usize| { + // An item read by a numeric index or a first-item unwrap shows that its own local has one. + if root.is_some_and(|r| item_roots.iter().any(|n| n == r)) { + return true; + } + direct.iter().any(|(name, to, read_at, count)| { + // A strict bound past `usize::MAX` (`xs.len() > usize::MAX`) cannot hold, so it + // guards nothing. + let least = match count.as_ref().map(|(c, strict)| (sizes.count(c), strict)) { + Some((Some(n), strict)) => match n.checked_add(usize::from(*strict)) { + Some(least) => least.max(1), + None => return false, + }, + _ => 1, + }; + let unchanged = if *to < at { + !may_shrink(&body[..at], name.as_bytes(), *to) + } else if *to <= end { + let (from, until) = if *read_at < call { (read_at + name.len(), call) } else { (call, *read_at) }; + // A check joined to the `.all(…)` by `||` need not hold for the assertion to + // pass (`xs.len() >= 2 || xs.windows(2).all(valid)`). + !may_change(&body[..until], name.as_bytes(), from, false) && !joined_by_or(&body[from.min(until)..until]) + } else { + !may_change(&body[..*to], name.as_bytes(), end, false) + }; + root.is_none_or(|r| r == name) && least >= need && unchanged + }) + }; + if alls.is_empty() { + return item_roots.is_empty() && !guards(None, 1, at); + } + !alls.iter().all(|&(root, need, call)| root.is_some() && guards(root, need, call)) + }) .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(); @@ -2053,6 +2743,89 @@ fn all_unguarded(v: &View) -> Vec { .collect() } +/// Whether `b` holds a `||` outside the brackets that open inside it, so the code before it and +/// the code after it are alternatives. +fn joined_by_or(b: &[u8]) -> bool { + let mut depth = 0i32; + for (i, &c) in b.iter().enumerate() { + match c { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + b'|' if depth <= 0 && b.get(i + 1) == Some(&b'|') => return true, + _ => {} + } + } + false +} + +/// The plain local a method chain at the end of `text` starts from: `xs` of `{let ok=xs.windows(2)`, +/// or `None` for a chain that starts from a call, a path or a field. +fn chain_root(text: &str) -> Option<&str> { + let b = text.as_bytes(); + let mut at = b.len(); + while at > 0 { + match b[at - 1] { + b')' | b']' => { + let mut depth = 0usize; + let mut k = at; + while k > 0 { + k -= 1; + match b[k] { + b')' | b']' => depth += 1, + b'(' | b'[' => { + depth -= 1; + if depth == 0 { + break; + } + } + _ => {} + } + } + if depth != 0 { + return None; + } + at = k; + } + c if name_byte(c) || c == b'.' => at -= 1, + _ => break, + } + } + let chain = &text[at..]; + let n = chain.bytes().take_while(|&c| name_byte(c)).count(); + let root = &chain[..n]; + let called = chain[n..].starts_with('('); + (plain_local(root) && !called && !text[..at].ends_with(':')).then_some(root) +} + +/// The count that the size check `read` (`xs.len()`) is compared with in a guard operand of `a`, +/// given the operand's text `around` the read: the other operand of an equality assertion whose +/// operand is the read alone, or the name or number right of `==`, `>=` or `>` (left of `==`, `<=` +/// or `<`). Only `.len()` and `.count()` give a count. The flag is true for a strict bound (`>`, +/// `<`), where the collection holds at least one item more than the count. +fn compared_count(a: &MacroCall, body: &[u8], open: usize, around: (&str, &str), read: &str) -> Option<(String, bool)> { + if !(read.ends_with(".len()") || read.ends_with(".count()")) { + return None; + } + let (before, after) = around; + if before.is_empty() && after.is_empty() { + return a + .name + .ends_with("_eq") + .then(|| a.args.iter().take(2).map(|&(from, to)| norm(&body[from - open..to - open])).find(|o| o != read))? + .map(|c| (c, false)); + } + let token = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == ':'; + let right = ["==", ">=", ">"] + .iter() + .find_map(|op| after.strip_prefix(op).map(|r| (r, *op == ">"))) + .map(|(r, strict)| (&r[..r.find(|c: char| !token(c)).unwrap_or(r.len())], strict)); + let left = ["==", "<=", "<"] + .iter() + .find_map(|op| before.strip_suffix(op).map(|l| (l, *op == "<"))) + .map(|(l, strict)| (&l[l.rfind(|c: char| !token(c)).map_or(0, |p| p + 1)..], strict)); + right.or(left).map(|(c, strict)| (c.to_owned(), strict)) +} + /// A loop over a whole table (`for x in TABLE`, `for c in Color::ALL`, `assert!(presets().iter().all(…))`) /// whose assertions only check presence, non-emptiness or a round trip. fn census(v: &View, helpers: &HashSet) -> Vec { @@ -2917,7 +3690,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 +3710,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,12 +4243,56 @@ fn strip_all_predicates(body: &mut [u8]) { } } -/// Whether test code accesses a first item in a way that fails on an empty collection. -fn first_item_guard(body: &[u8], sizes: &Sizes) -> bool { +/// Where test code accesses an item in a way that fails on an empty collection: a first item, or an +/// index written as a number. The flag is true for an access whose collection is not a plain local +/// (`rows()[0]`), which counts for every collection; the list names the plain locals that such +/// accesses read (`expected` of `expected[1]`), each of which then has an item. +fn first_item_guard(body: &[u8], sizes: &Sizes) -> (bool, Vec) { let compact = norm(body); + let (mut any, mut roots) = (false, vec![]); + let mut add = |head: &str| match chain_root(head) { + Some(root) => roots.push(root.to_owned()), + None => any = true, + }; let unwrapped = [".first().unwrap()", ".first().expect(", ".next().unwrap()", ".next().expect("]; - let indexed = compact.match_indices("[0]").any(|(at, _)| array_literal_len(&compact[..at + 3], sizes).is_none_or(|n| n == 0)); - indexed || unwrapped.iter().any(|g| compact.contains(g)) || panicking_first_binding(body) + let indexed = compact.match_indices('[').filter(|&(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, + }, + // Turbofish arguments (`.as_chunks::<2>()`) are part of the call. + b'<' if compact[..chain].ends_with("::") => match skip_turbofish(b, chain - 2) { + next if next > chain => next, + _ => 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_mut()", ".windows(", ".chunks(", ".chunks_exact(", ".as_chunks::<", ".as_rchunks::<"] + .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) + }); + for (at, _) in indexed.chain(unwrapped.iter().flat_map(|g| compact.match_indices(g))) { + add(&compact[..at]); + } + (any || panicking_first_binding(body), roots) } /// Whether a `let Some(…) = ….first() else { panic!(…) }` binding checks for an item. @@ -3575,7 +4393,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 +4404,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 +4417,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 +4433,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,12 +4517,58 @@ 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| name_byte(c)).count(); + while at < b.len() { + if !name_byte(b[at]) { + at += 1; + continue; + } + let start = at; + while at < b.len() && name_byte(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 local_name(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. /// A read bound to another local or passed to a call outside an assertion may give out an alias. fn touched_after(body: &[u8], name: &str, from: usize, receiver: &str) -> bool { - if !plain_local(name) { + if !local_name(name) { return true; } words(body, name.as_bytes(), from, body.len()).into_iter().any(|at| { @@ -4030,10 +4900,18 @@ fn item_len(receiver: &str, sizes: &Sizes) -> usize { } /// The receiver without its iterator method and the items it needs for `.all(…)` to see one: -/// `.windows(k)` and `.chunks_exact(k)` need `k`, anything else one. An unknown `k` needs more +/// `.windows(k)`, `.chunks_exact(k)` and the full chunks of `.as_chunks::()` need `k`, +/// anything else one. An unknown `k` needs more /// than any collection has. fn receiver_need<'a>(receiver: &'a str, sizes: &Sizes) -> (&'a str, usize) { let r = array_receiver(receiver); + // The full chunks of `.as_chunks::()` (`.0`) and `.as_rchunks::()` (`.1`) need `k`. + for (method, chunks) in [(".as_chunks::<", ">().0"), (".as_rchunks::<", ">().1")] { + let Some(head) = r.strip_suffix(chunks) else { continue }; + let Some(at) = head.rfind(method) else { continue }; + let need = sizes.count(&head[at + method.len()..]).filter(|&k| k > 0).unwrap_or(usize::MAX); + return (array_receiver(&r[..at]), need); + } for (method, exact) in [(".windows(", true), (".chunks_exact(", true), (".chunks(", false)] { let Some(at) = r.rfind(method) else { continue }; let open = at + method.len() - 1; @@ -4055,15 +4933,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()?; @@ -4092,6 +4972,17 @@ fn plain_local(name: &str) -> bool { !name.is_empty() && !name.as_bytes()[0].is_ascii_digit() && name.bytes().all(is_ident) } +/// Whether `c` is a byte of a name, non-ASCII letters (`数`) included: their UTF-8 bytes are all +/// 0x80 or above. +fn name_byte(c: u8) -> bool { + is_ident(c) || c >= 0x80 +} + +/// [`plain_local`], with non-ASCII letters allowed ([`name_byte`]). +fn local_name(name: &str) -> bool { + !name.is_empty() && !name.as_bytes()[0].is_ascii_digit() && name.bytes().all(name_byte) +} + /// Removes one borrow and a slice view from a compared operand. fn collection_operand(operand: &str) -> &str { let operand = operand.strip_prefix('&').unwrap_or(operand); @@ -4344,6 +5235,23 @@ fn repeat_count(contents: &[u8], sizes: &Sizes) -> Option { None } +/// Whether the text inside parentheses is a tuple: a comma outside brackets, after the parameter +/// list of a leading closure (`|a, b| …`). +fn tuple_parts(inner: &[u8]) -> bool { + let mut at = skip_ws(inner, 0); + for keyword in [&b"async"[..], b"move"] { + if inner[at..].starts_with(keyword) && !inner.get(at + keyword.len()).copied().is_some_and(is_ident) { + at = skip_ws(inner, at + keyword.len()); + } + } + if inner[at..].starts_with(b"||") { + at += 2; + } else if inner.get(at) == Some(&b'|') { + at = find(inner, b"|", at + 1).map_or(inner.len(), |p| p + 1); + } + has_top_level(&inner[at..], b',') +} + /// Whether `c` occurs in `b` outside brackets. fn has_top_level(b: &[u8], c: u8) -> bool { let mut at = 0; @@ -4423,7 +5331,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 +5355,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 +5376,86 @@ 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)`, `std::mem::take((xs))`), which can change it; a macro such as + // `assert_eq!` only reads it. The grouped argument's outer bounds find the call. + let outer_before = body[..start].trim_ascii_end(); + let passed = mut_ref + && (outer_before.ends_with(b"(") || outer_before.ends_with(b",")) + && matches!(body.get(end), Some(b')' | b',')) + && enclosing_open(body, start).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 +5627,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))) @@ -4726,18 +5703,47 @@ fn exit_status_only(v: &View) -> Option { strip_stream_configuration(&mut body); let reads = ["stdout", "stderr", "fs::read", "read_to_string", "from_slice", "from_str", "contains("].iter().any(|w| contains(&body, w.as_bytes())); - let status_only = |a: &MacroCall| { - a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { - let c = norm(&v.file.m[from..to]); - c.contains(".success()") || c.contains(".code()") - }) - }; + let status_only = + |a: &MacroCall| a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| status_only_condition(&norm(&v.file.m[from..to]))); if !runs || reads || v.asserts.is_empty() || !v.asserts.iter().all(status_only) || v.delegates { return None; } Some(v.whole(Rule::ExitStatusOnly, "runs a process and checks only its exit status".into())) } +/// Whether a whitespace-free condition can hold when only exit statuses are checked: one of its +/// `||` alternatives has only `&&` operands that check `.success()` or `.code()`. A parenthesized +/// operand is classified the same way, operand by operand. +fn status_only_condition(c: &str) -> bool { + 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| { + let inner = unparenthesized(operand); + if inner.len() < operand.len() { + status_only_condition(inner) + } else { + operand.contains(".success()") || operand.contains(".code()") + } + }) + }) + }) + }) +} + /// Blanks the names of builder calls that set a process's streams (`.stdout(…)`, whatever the /// argument) in whitespace-free text. Reads of the output fields (`out.stdout`) stay. fn strip_stream_configuration(body: &mut [u8]) { @@ -5301,7 +6307,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 +6349,56 @@ 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) || c >= 0x80).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 open = body_open(m, matching(m, i)? + 1).filter(|&open| open < to)?; + 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 +6953,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,26 +6979,47 @@ 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; // Where the path that ends at the current name starts: `Vec` in `Vec::::new`. let mut path_start = 0; 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]; // Turbofish arguments name types only, and the `(` after them makes a call of `name`. let rest = skip_turbofish(b, end); @@ -5955,8 +7030,15 @@ fn inert(op: &str, local: &dyn Fn(&str) -> Option) -> Option { path_start = i; } 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]; + // An element indexed out of a local (`xs[0].len()`) is a user value when the local holds one. + let user = indexed_local(receiver).map_or_else(|| user_value(receiver, pos, local), |base| holds_user_value(base, pos, local)); + let inert_read = FIXTURE_READS.contains(&name) && !user; + 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("!=") { @@ -5970,7 +7052,7 @@ fn inert(op: &str, local: &dyn Fn(&str) -> Option) -> Option { let path = without_turbofish(&op[path_start..end]); ["Box::new", "String::from", "Vec::new"].iter().any(|p| path.ends_with(p)) }) - || (!path_tail && screaming_or_camel(name)); + || screaming_or_camel(name); if !builder { return None; } @@ -5979,14 +7061,244 @@ 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 = rest; } - Some(reads_local) + Some((reads_local, user_value(op, pos, local))) +} + +/// The local an element is indexed out of (`xs` of `xs[0]` and `&rows[1][2]`), or `None`. +fn indexed_local(expr: &str) -> Option<&str> { + let expr = expr.trim_start_matches(['&', '*']); + let b = expr.as_bytes(); + // Names follow [`inert`]'s rules, so `数` of `数[0]` is a local. + let n = b.iter().take_while(|&&c| name_byte(c)).count(); + let mut at = n; + if at == b.len() { + return None; + } + while at < b.len() { + if b[at] != b'[' { + return None; + } + at = matching(b, at)? + 1; + } + local_name(&expr[..n]).then(|| &expr[..n]) +} + +/// 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)); + } + // Non-ASCII letters (`数`) are part of a name, as in [`inert`]. + if !expr.is_empty() && !expr.as_bytes()[0].is_ascii_digit() && expr.bytes().all(|c| is_ident(c) || c >= 0x80) { + 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]`, `数[0]`, `rows[1][2]`) is a user value when the + // local's value holds one. + if b[open] == b'[' + && let Some(name) = indexed_local(expr) + { + return holds_user_value(name, 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(); + // A tuple literal (`(5, Kind::A)`) has no name before its parenthesis. + let tuple = open == 0 && v.first() == Some(&b'('); + if (open == 0 && !tuple) || !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); + // Parentheses around one expression without a comma only group it. + if tuple && args.len() < 2 && !value[..v.len() - 1].trim_end().ends_with(',') { + return None; + } + 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)) } /// `s` with every `::<…>` turbofish removed: `Vec::::new` becomes `Vec::new`. @@ -6012,15 +7324,7 @@ fn without_turbofish(s: &str) -> String { 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)); @@ -6031,6 +7335,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 { @@ -6122,14 +7440,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. @@ -6168,7 +7479,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)); @@ -6269,15 +7580,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 @@ -6298,7 +7609,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 { @@ -6558,10 +7869,15 @@ fn cfg_spans(m: &[u8], src: &[u8]) -> Vec { let Some(close) = matching(m, skip_ws(m, after) + 1) else { break }; after = close + 1; } - let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; - match (m[open], matching(m, open)) { - (b'{', Some(close)) => (at, close), - _ => continue, + let Some(stop) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; + // A function's signature can hold `;` (`-> [u8; 2]`), so its body is found as `fn_after` finds it. + let open = match words(m, b"fn", after, stop).first() { + Some(&kw) => body_open(m, kw + 2), + None => (m[stop] == b'{').then_some(stop), + }; + match open.and_then(|open| matching(m, open)) { + Some(close) => (at, close), + None => continue, } }; out.push(CfgSpan { pred, at, end, span }); @@ -6851,7 +8167,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) { @@ -6861,16 +8178,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 } @@ -7202,17 +8533,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() } @@ -7234,12 +8565,113 @@ 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, created for this guard alone and + /// removed when the guard is dropped, including when an assertion fails. + struct TempRepo(tempfile::TempDir); + + impl TempRepo { + fn new(name: &str) -> Self { + Self(tempfile::Builder::new().prefix(&format!("test-lint-{name}-")).tempdir().unwrap()) + } + } + + impl std::ops::Deref for TempRepo { + type Target = Path; + + fn deref(&self) -> &Path { + self.0.path() + } + } + + #[test] + fn a_direct_length_guard_counts_the_items_each_view_needs() { + 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"; + let chunked = good.replace("xs.iter().all(|x| *x > 0)", "xs.as_chunks::<2>().0.iter().all(|[a, b]| a == b)"); + let short_chunks = chunked.replace("assert_eq!(xs.len(), 3);", "assert_eq!(xs.len(), 1);"); + assert_eq!(hits(&short_chunks), [(5, "all-unguarded")], "one item makes no chunk of two"); + for view in ["xs.windows(2).all(|w| w[0] < w[1])", "xs.chunks_exact(2).all(|c| c[0] < c[1])"] { + let short = good.replace("assert_eq!(xs.len(), 3);", "assert_eq!(xs.len(), 1);").replace("xs.iter().all(|x| *x > 0)", view); + assert_eq!(hits(&short), [(5, "all-unguarded")], "{view} after a length of one"); + let long = short.replace("assert_eq!(xs.len(), 1);", "assert!(xs.len() >= 2);"); + assert_eq!(hits(&long), [], "{view} after a length of at least two"); + let joined = format!("#[test]\nfn t() {{\n let xs = f();\n assert!(xs.len() >= 2 && {view});\n}}\n"); + assert_eq!(hits(&joined), [], "{view} in the same condition as a length of at least two"); + let reversed = joined.replace("xs.len() >= 2", "2 <= xs.len()"); + assert_eq!(hits(&reversed), [], "{view} after a reversed comparison"); + let strict = short.replace("assert_eq!(xs.len(), 1);", "assert!(xs.len() > 1);"); + assert_eq!(hits(&strict), [], "{view} after a length of more than one"); + let strict_reversed = short.replace("assert_eq!(xs.len(), 1);", "assert!(1 < xs.len());"); + assert_eq!(hits(&strict_reversed), [], "{view} after a reversed strict comparison"); + let strict_short = short.replace("assert_eq!(xs.len(), 1);", "assert!(xs.len() > 0);"); + assert_eq!(hits(&strict_short), [(5, "all-unguarded")], "{view} after a length of more than zero"); + let unbounded = joined.replace("xs.len() >= 2", "xs.len() > 0xffff_ffff_ffff_ffffusize"); + assert_eq!(hits(&unbounded), [(4, "all-unguarded")], "{view} after a strict bound past the largest length"); + } + let counted = good.replace("assert_eq!(xs.len(), 3);", "assert_eq!(xs.iter().count(), 3);"); + assert_eq!(hits(&counted), [], "a count of the local's iterator"); + let counted_cleared = counted.replace(" assert!(xs", " xs.clear();\n assert!(xs"); + assert_eq!(hits(&counted_cleared), [(6, "all-unguarded")], "a count of the local's iterator before a clear"); + } + #[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"); + } + + #[test] + fn a_later_or_inner_length_check_guards_all_while_the_collection_holds() { + 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"; + let later = "#[test]\nfn t() {\n let mut xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n assert_eq!(xs.len(), 3);\n}\n"; + assert_eq!(hits(later), [], "a later length check with nothing between"); + let later_pushed = later.replace(" assert_eq!(xs.len()", " xs.push(1);\n assert_eq!(xs.len()"); + assert_eq!(hits(&later_pushed), [(4, "all-unguarded")], "a later length check after a push"); + let later_replaced = later.replace(" assert_eq!(xs.len()", " xs = g();\n assert_eq!(xs.len()"); + assert_eq!(hits(&later_replaced), [(4, "all-unguarded")], "a later length check after a replacement"); + 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"; @@ -7252,6 +8684,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::>(); @@ -8046,8 +9492,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"); @@ -8057,6 +9510,18 @@ 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"); + for view in ["iter_mut()", "windows(2)", "chunks(2)"] { + let inner = item.replace("iter()", view); + assert_eq!(hits(&inner), [(3, "all-unguarded")], "an item read through {view}"); + } + 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] @@ -8067,6 +9532,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"; @@ -8080,7 +9551,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"); } @@ -8116,8 +9587,32 @@ mod tests { fn functions_declared_in_a_test_count_only_when_called() { let unused = "#[test]\nfn t() {\n fn unused() {\n assert_eq!(1, 1);\n }\n assert!(parse(\"x\").is_ok());\n}\n"; assert_eq!(hits(unused), [(2, "only-weak")], "a declared function's assertion does not run"); + let array_return = + unused.replace("fn unused() {\n assert_eq!(1, 1);", "fn unused() -> [u8; 1] {\n assert_eq!(1, 1);\n [1]"); + assert_eq!(hits(&array_return), [(2, "only-weak")], "a declared function with an array return type"); 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 _ = async || assert_eq!(f(), 1);", + "let _ = async move |x| assert_eq!(x, 1);", + "let _ = (|| { assert_eq!(f(), 1); });", + "let _ = ((async { assert_eq!(f(), 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 invoked = "#[test]\nfn t() {\n let _ = (|| { assert_eq!(f(), 1); })();\n}\n"; + assert_eq!(hits(invoked), [], "a grouped closure that is called 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() }; @@ -8183,6 +9678,26 @@ 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()", + "status.success() && (status.code() == Some(0) || destination.exists())", + ] { + let bad = good.replace("status.success() && destination.exists()", condition); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{condition}"); + } + let grouped = + good.replace("status.success() && destination.exists()", "status.success() && (destination.exists() && status.code() == Some(0))"); + assert_eq!(hits(&grouped), [], "a grouped conjunction that checks the destination"); + } + #[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"] { @@ -8290,7 +9805,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(); @@ -8300,6 +9815,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] @@ -8524,7 +10044,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); @@ -8541,7 +10061,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); @@ -8620,6 +10140,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=", @@ -8633,6 +10154,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"; @@ -8653,18 +10229,73 @@ mod tests { { assert_eq!(upper_words(line).collect::>(), Vec::::new(), "{line}"); } - for line in [" echo hi; MY_SAMPLES=x cargo test", " printf 'MY_SAMPLES=x\\n' >> \"$GITHUB_ENV\""] { + for line in [ + " echo hi; MY_SAMPLES=x cargo test", + " printf 'MY_SAMPLES=x\\n' >> \"$GITHUB_ENV\"", + " printf '%s; ' x; MY_SAMPLES=x cargo test", + " { echo MY_SAMPLES=x; echo OTHER=1; } >> \"$GITHUB_ENV\"", + ] { + assert!(upper_words(line).any(|name| name == "MY_SAMPLES"), "{line}"); + } + for line in [ + " printf '%s; ' MY_SAMPLES=fixtures", + " printf \"%s | \" MY_SAMPLES=fixtures", + "run: \"echo MY_SAMPLES=fixtures\\necho OTHER=1 >> \\\"$GITHUB_ENV\\\"\"", + " echo MY_SAMPLES=fixtures; echo OTHER=1 >> \"$GITHUB_ENV\"", + ] { + assert!(!upper_words(line).any(|name| name == "MY_SAMPLES"), "{line}"); + } + } + + #[test] + fn quoted_search_patterns_set_no_workflow_variable() { + for line in [" grep \"MY_SAMPLES=fixtures\" settings.txt", "run: grep 'MY_SAMPLES=fixtures' settings.txt; export OTHER=1"] { + assert!(!upper_words(line).any(|name| name == "MY_SAMPLES"), "{line}"); + } + } + + #[test] + fn a_hash_inside_a_shell_word_starts_no_comment() { + for line in ["run: \"export note=one#two; MY_SAMPLES=fixtures cargo test\"", "run: export note=one#two; MY_SAMPLES=fixtures cargo test"] { assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); } + for line in ["run: \"export note=one #MY_SAMPLES=fixtures\"", "run: export note=one;#MY_SAMPLES=fixtures"] { + assert_eq!(upper_words(line).collect::>(), Vec::::new(), "{line}"); + } + } + + #[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:?}"); } @@ -8678,6 +10309,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"; @@ -8860,6 +10505,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"; @@ -8891,6 +10545,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"; @@ -8966,6 +10630,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"; @@ -9038,6 +10711,8 @@ mod tests { fn never_run_tests_are_compiled_out_on_every_ci_target() { let mac = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(only("never-run", mac), [(3, "never-run")]); + let array_return = mac.replace("fn t() {", "fn t() -> Result<(), [u8; 2]> {"); + assert_eq!(only("never-run", &array_return), [(3, "never-run")], "a return type that holds `;`"); let module = "#[cfg(all(test, windows))]\nmod tests {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; assert_eq!(hits_in("crates/x/src/lib.rs", module, &ctx()).into_iter().filter(|h| h.1 == "never-run").count(), 1); let file = "#![cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; @@ -9241,6 +10916,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"; @@ -9422,8 +11110,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 = [ @@ -9449,13 +11136,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. @@ -9486,13 +11188,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(); @@ -9507,7 +11207,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] @@ -9528,12 +11227,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"; @@ -9546,7 +11253,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] @@ -9747,7 +11466,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(); @@ -9849,6 +11568,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"; @@ -9916,6 +11665,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"; @@ -9954,6 +11705,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] @@ -11122,6 +12879,22 @@ 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 accented = local.replace("active", "sélection"); + assert_eq!(hits(&accented), [], "an unchanged selector name with non-ASCII letters"); + let accented_changed = changed.replace("active", "sélection"); + assert_eq!(hits(&accented_changed), [(7, "all-unguarded")], "a selector name with non-ASCII letters 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] @@ -11282,4 +13055,528 @@ 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 deleting_a_skip_comment_exposes_a_return_after_blank_lines() { + let path = "crates/x/src/tests.rs"; + let base = "#[test]\nfn t() {\n if unavailable() {\n // The fixture is optional.\n\n\n return;\n }\n assert_eq!(f(), 1);\n}\n"; + let src = base.replace(" // The fixture is optional.\n", ""); + assert_eq!(only("early-return", &src), [(6, "early-return")]); + let lines = lines_affecting_tests(base); + let can_change_test = |p: &str, line: usize| p == path && lines.contains(&line); + let code_after = |p: &str, line: usize| if p == path { next_code_line(&src, line) } else { 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_in(&diff, &can_change_test, &code_after); + 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()), "{changed:?}"); + let spaced = base.replace("\n\n return;", "\n /* spacer */\n\n return;"); + let src = spaced.replace(" // The fixture is optional.\n", ""); + let lines = lines_affecting_tests(&spaced); + let can_change_test = |p: &str, line: usize| p == path && lines.contains(&line); + let code_after = |p: &str, line: usize| if p == path { next_code_line(&src, line) } else { line }; + let changed = parse_diff_in(&diff, &can_change_test, &code_after); + 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()), "a block comment before the return: {changed:?}"); + let note = "#[test]\nfn t() {}\n// a note\n\n\nfn helper() {}\n"; + let after = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -3 +2,0 @@\n-// a note\n"); + let kept = note.replace("// a note\n", ""); + let code_after = |_: &str, line: usize| next_code_line(&kept, line); + assert_eq!(parse_diff_in(&after, &|_, _| false, &code_after)[path], Some(BTreeSet::new()), "a comment outside every test"); + let replaced = base.replace(" // The fixture is optional.", ""); + let replacement = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -4 +4 @@\n- // The fixture is optional.\n+\n"); + let code_after = |p: &str, line: usize| if p == path { next_code_line(&replaced, line) } else { line }; + let changed = parse_diff_in(&replacement, &can_change_test, &code_after); + let found = lint_file(path, &replaced, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::EarlyReturn).unwrap(); + assert!(touches(hit, changed[path].as_ref()), "a skip comment replaced by a blank line: {changed:?}"); + let import = "fn helper() {}\nuse x::y;\n\n\n#[test]\nfn t() {}\n"; + let kept = import.replace("use x::y;\n", ""); + let removed = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -2 +1,0 @@\n-use x::y;\n"); + let code_after = |_: &str, line: usize| next_code_line(&kept, line); + let changed = parse_diff_in(&removed, &|_, _| true, &code_after); + let found = lint_file(path, &kept, &ctx()); + assert_eq!(found[0].rule, Rule::NoAssertion); + assert!(!touches(&found[0], changed[path].as_ref()), "an import deleted before blank lines: {changed:?}"); + } + + #[test] + fn a_grouped_run_block_writes_to_the_environment_file() { + let block = "run: |\n {\n echo \"MY_SAMPLES=fixtures\"\n } >> \"$GITHUB_ENV\"\n"; + assert_eq!(upper_words(block).collect::>(), ["MY_SAMPLES"]); + let printed = "run: |\n echo \"MY_SAMPLES=fixtures\"\n echo OTHER=1 >> \"$GITHUB_ENV\"\n"; + assert!(!upper_words(printed).any(|n| n == "MY_SAMPLES")); + } + + #[test] + fn a_folded_run_block_is_one_command_line() { + let folded = "- run: >-\n echo\n MY_SAMPLES=fixtures\n"; + assert!(!upper_words(folded).any(|n| n == "MY_SAMPLES"), "an echo argument after folding"); + let separate = "- run: >-\n echo hi\n\n MY_SAMPLES=fixtures cargo test\n"; + assert_eq!(upper_words(separate).collect::>(), ["MY_SAMPLES"], "a blank line keeps the break"); + let deeper = "- run: >\n echo hi\n MY_SAMPLES=fixtures cargo test\n"; + assert_eq!(upper_words(deeper).collect::>(), ["MY_SAMPLES"], "a deeper line keeps its break"); + assert_eq!(fold_block(&[" a", " b", "", " c", " d", " e"], None), "a b\nc\n d\ne\n"); + let explicit = "- run: >2-\n echo hi\n MY_SAMPLES=fixtures cargo test\n"; + assert_eq!(upper_words(explicit).collect::>(), ["MY_SAMPLES"], "an indentation indicator sets the indentation"); + } + + #[test] + fn an_assignment_follows_a_separator_without_a_space() { + assert_eq!(upper_words("run: true&&MY_SAMPLES=fixtures cargo test\n").collect::>(), ["MY_SAMPLES"]); + assert!(!upper_words("run: echo \"a&&MY_SAMPLES=fixtures\"\n").any(|n| n == "MY_SAMPLES"), "inside quotes"); + } + + #[test] + fn only_a_stdout_redirection_writes_to_the_environment_file() { + assert!(!writes_env_file("echo \"MY_SAMPLES=fixtures\" 2>> \"$GITHUB_ENV\"")); + assert!(writes_env_file("echo \"MY_SAMPLES=fixtures\" 1>> \"$GITHUB_ENV\"")); + assert!(writes_env_file("echo \"MY_SAMPLES=fixtures\" &>> \"$GITHUB_ENV\"")); + let group = "run: { echo \"MY_SAMPLES=fixtures\" >> \"$GITHUB_ENV\"; echo done > setup.log; }\n"; + assert_eq!(upper_words(group).collect::>(), ["MY_SAMPLES"], "a redirection of the next command"); + assert!(writes_env_file("echo MY_SAMPLES=fixtures >> \"$GITHUB_ENV\" && echo done > setup.log")); + assert!(!writes_env_file("echo MY_SAMPLES=fixtures >> \"$GITHUB_ENV\" > a.log; echo done"), "the same command"); + } + + #[test] + fn a_literal_run_block_ends_at_the_next_step_key() { + let step = "- run: |\n cargo test\n env:\n MY_SAMPLES: fixtures\n"; + assert_eq!(upper_words(step).collect::>(), ["MY_SAMPLES"]); + let nested = "- run: |\n cargo test\n MY_SAMPLES: fixtures\n"; + assert!(!upper_words(nested).any(|n| n == "MY_SAMPLES"), "a line of the script"); + } + + #[test] + fn a_later_stdout_redirection_replaces_the_environment_file() { + assert!(writes_env_file("echo \"MY_SAMPLES=fixtures\" >> \"$GITHUB_ENV\"")); + assert!(!writes_env_file("echo \"MY_SAMPLES=fixtures\" >> \"$GITHUB_ENV\" > setup.log")); + assert!(!writes_env_file("echo MY_SAMPLES=fixtures >> ${GITHUB_ENV} >&2")); + assert!(writes_env_file("echo MY_SAMPLES=fixtures >> \"$GITHUB_ENV\" 2> err.log")); + assert!(writes_env_file("echo MY_SAMPLES=fixtures >> \"$GITHUB_ENV\" 2>&1")); + assert!(writes_env_file("echo MY_SAMPLES=fixtures >> \"$GITHUB_ENV\" | cat > out.log")); + assert!(writes_env_file("{ echo MY_SAMPLES=fixtures >> \"$GITHUB_ENV\"; } > out.log")); + let block = "run: echo \"MY_SAMPLES=fixtures\" >> \"$GITHUB_ENV\" > setup.log\n"; + assert!(!upper_words(block).any(|n| n == "MY_SAMPLES")); + } + + #[test] + fn an_unquoted_search_pattern_sets_no_variable() { + assert!(!upper_words("run: grep MY_SAMPLES=fixtures settings.txt").any(|n| n == "MY_SAMPLES")); + assert!(upper_words("run: A=1 MY_SAMPLES=fixtures cargo test").any(|n| n == "MY_SAMPLES")); + } + + #[test] + fn the_print_exemption_reads_the_command_name() { + assert!(upper_words("run: export NOTE='echo' \"MY_SAMPLES=fixtures\"; cargo test").any(|n| n == "MY_SAMPLES")); + assert!(upper_words("run: export NOTE=echo MY_SAMPLES=fixtures; cargo test").any(|n| n == "MY_SAMPLES")); + } + + #[test] + fn printing_the_environment_file_path_writes_nothing_to_it() { + for line in + [" echo \"MY_SAMPLES=fixtures\" \"$GITHUB_ENV\"", " echo MY_SAMPLES=fixtures $GITHUB_ENV", " echo \"MY_SAMPLES=x\" ${GITHUB_ENV}"] + { + assert!(!upper_words(line).any(|n| n == "MY_SAMPLES"), "{line}"); + } + } + + #[test] + fn a_discarded_tuple_runs_its_elements() { + let src = "#[test]\nfn t() {\n let _ = (|| (), { assert_eq!(f(), 1); });\n}\n"; + assert_eq!(only("no-assertion", src), []); + } + + #[test] + fn a_change_between_a_size_read_and_all_in_one_assertion_voids_the_guard() { + let mutated = + "#[test]\nfn t() {\n let mut xs = f();\n assert!({ let ok = xs.iter().all(|x| valid(x)); xs.push(1); ok } && xs.len() == 1);\n}\n"; + assert_eq!(only("all-unguarded", mutated), [(4, "all-unguarded")]); + } + + #[test] + fn a_length_guard_covers_only_its_own_collection() { + let other = "#[test]\nfn t() {\n let xs = f();\n let ys = g();\n assert_eq!(xs.len(), 2);\n assert!(ys.windows(2).all(|w| w[0] < w[1]));\n}\n"; + assert_eq!(only("all-unguarded", other), [(6, "all-unguarded")]); + assert_eq!(only("all-unguarded", &other.replace("ys.windows", "xs.windows")), []); + } + + #[test] + fn a_size_check_joined_by_or_guards_no_all() { + let joined = "#[test]\nfn t() {\n let xs = f();\n assert!(xs.len() >= 2 || xs.windows(2).all(|w| w[0] < w[1]));\n}\n"; + assert_eq!(only("all-unguarded", joined), [(4, "all-unguarded")]); + assert_eq!(only("all-unguarded", &joined.replace("||", "&&")), []); + } + + #[test] + fn an_index_guards_only_the_collection_it_reads() { + let other = "#[test]\nfn t() {\n let expected = f();\n let actual = g();\n let _ = expected[1];\n assert!(actual.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(only("all-unguarded", other), [(6, "all-unguarded")]); + assert_eq!(only("all-unguarded", &other.replace("expected[1]", "actual[1]")), []); + } + + #[test] + fn an_index_does_not_guard_full_chunks_of_its_item() { + let chunks = "#[test]\nfn t() {\n assert!(rows()[1].as_chunks::<2>().0.iter().all(|[a, b]| a == b));\n}\n"; + assert_eq!(only("all-unguarded", chunks), [(3, "all-unguarded")]); + } + + #[test] + fn a_selector_name_may_have_no_ascii_letters() { + 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"; + let changed = local.replace(" assert!(r.items(active)", " active = false;\n assert!(r.items(active)"); + assert_eq!(hits(&changed.replace("active", "选")), [(7, "all-unguarded")], "a selector changed after the snapshot"); + assert_eq!(hits(&local.replace("active", "选")), [], "an unchanged selector"); + } + + #[test] + fn an_indexed_local_may_have_no_ascii_letters() { + let indexed = "#[test]\nfn t() {\n let 数 = [Input { n: 5 }];\n assert_eq!(数[0].len(), 5);\n}\n"; + assert_eq!(only("fixture-only", indexed), []); + let whole = indexed.replace("数[0].len()", "数.len()"); + assert_eq!(only("fixture-only", &whole), only("fixture-only", &whole.replace('数', "xs"))); + } + + #[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);", "std::mem::take((xs));", "consume(a, ((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 }", + "fn unused() -> [u8; 1] {\n [probe()]\n }", + "fn vérifier() {\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); + let called = direct.replace("probe();", "fn vérifier() { probe(); }\n vérifier();"); + assert_eq!(hits(&called).iter().filter(|h| h.1 == "sleep").count(), 0, "a call to a non-ASCII nested fn polls"); + } + + #[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", + "#[test]\nfn t() {\n let pair = (5, Kind::A);\n assert_eq!(pair.1.to_string(), \"a\");\n}\n", + "#[test]\nfn t() {\n let xs = [Input { n: 5 }];\n assert_eq!(xs[0].len(), 5);\n}\n", + "#[test]\nfn t() {\n let xs = [[Input { n: 5 }]];\n assert_eq!(xs[0][0].len(), 5);\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 xs = [[1, 2]];\n assert_eq!(xs[0].len(), 2);\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", + "#[test]\nfn t() {\n let 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), []); + let non_ascii = "#[test]\nfn t() {\n let 数 = vec![Input { n: 5 }];\n assert_eq!(数.clone()[0].n, 6);\n}\n"; + assert_eq!(only("fixture-only", non_ascii), [], "a non-ASCII container local"); + let primitive = "#[test]\nfn t() {\n let 数 = vec![5];\n assert_eq!(数.clone()[0], 6);\n}\n"; + assert_eq!(only("fixture-only", primitive), [(2, "fixture-only")], "a non-ASCII local of primitive values"); + let element = "#[test]\nfn t() {\n let 数 = [Input { n: 5 }];\n assert_eq!(数[0].clone().n, 6);\n}\n"; + assert_eq!(only("fixture-only", element), [], "a clone of an element of a non-ASCII local"); + let primitive_element = "#[test]\nfn t() {\n let 数 = [5];\n assert_eq!(数[0].clone(), 6);\n}\n"; + assert_eq!(only("fixture-only", primitive_element), [(2, "fixture-only")], "a clone of a primitive element"); + 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"); + } }