diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 8aab64ef85..595fc978f0 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1032,19 +1032,59 @@ fn workflow_scalar(line: &str) -> Option { Some(out) } -/// Whether the text at `from` is an argument of `echo` or `printf` in its shell command, on a line -/// that does not write to `$GITHUB_ENV`. +/// Whether the text at `from` is an argument of `echo` or `printf` in its shell command, in a +/// pipeline that does not write to `$GITHUB_ENV`. fn printed(line: &str, from: usize) -> bool { - // A line break ends the command unless a backslash continues it. - let head = &line[..from]; - let cut = head - .char_indices() - .rev() - .find(|&(i, c)| matches!(c, ';' | '&' | '|') || (c == '\n' && !head[..i].ends_with('\\'))) - .map_or(0, |(i, c)| i + c.len_utf8()); - let command = &head.as_bytes()[cut..]; + let separators = shell_separators(line); + // The command starts after the last separator before `from`; the pipeline runs between the + // list separators (`;`, `&&`, `||`, `&` and line breaks) around it. + let command_start = separators.iter().rev().find(|s| s.end <= from).map_or(0, |s| s.end); + let pipeline_start = separators.iter().rev().find(|s| s.end <= from && !s.pipe).map_or(0, |s| s.end); + let pipeline_end = separators.iter().find(|s| s.start >= from && !s.pipe).map_or(line.len(), |s| s.start); + let command = &line.as_bytes()[command_start..from]; let prints = ["echo", "printf"].iter().any(|w| !words(command, w.as_bytes(), 0, command.len()).is_empty()); - prints && !line.contains("GITHUB_ENV") + prints && !line[pipeline_start..pipeline_end].contains("GITHUB_ENV") +} + +/// A shell control operator outside quotes: its byte range, and whether it is a pipe (`|`) rather +/// than a list separator. +struct ShellSeparator { + start: usize, + end: usize, + pipe: bool, +} + +/// The control operators of a shell script outside quotes, in order. A line break counts as a list +/// separator unless a backslash continues it. +fn shell_separators(script: &str) -> Vec { + let bytes = script.as_bytes(); + let (mut out, mut quote, mut escaped, mut i) = (vec![], None, false, 0); + while i < bytes.len() { + let c = bytes[i]; + if escaped { + escaped = false; + } else if c == b'\\' && quote != Some(b'\'') { + escaped = true; + } else if quote == Some(c) { + quote = None; + } else if quote.is_none() { + match c { + b'\'' | b'"' => quote = Some(c), + b'|' | b'&' if bytes.get(i + 1) == Some(&c) => { + out.push(ShellSeparator { start: i, end: i + 2, pipe: false }); + i += 1; + } + // `2>&1`, `&>` and `>|` are redirections. + b'&' | b'|' if i > 0 && matches!(bytes[i - 1], b'>' | b'<') => {} + b'&' if bytes.get(i + 1) == Some(&b'>') => {} + b'|' => out.push(ShellSeparator { start: i, end: i + 1, pipe: true }), + b';' | b'&' | b'\n' => out.push(ShellSeparator { start: i, end: i + 1, pipe: false }), + _ => {} + } + } + i += 1; + } + out } fn env_assignment_name(name: &str) -> bool { @@ -1069,7 +1109,8 @@ fn open_quote(line: &str, at: usize) -> Option { quote.map(|(_, i)| i) } -/// Removes comment text outside quotes from a workflow line. +/// Removes comment text outside quotes from a workflow line. A `#` starts a comment only at the +/// start of the line or after whitespace, as in YAML and the shell (`build#1` is one word). fn workflow_code(line: &str) -> &str { let (mut quote, mut escaped) = (None, false); for (at, c) in line.char_indices() { @@ -1082,7 +1123,7 @@ fn workflow_code(line: &str) -> &str { } else if quote.is_none() { match c { '\'' | '"' => quote = Some(c), - '#' => return &line[..at], + '#' if line[..at].chars().next_back().is_none_or(char::is_whitespace) => return &line[..at], _ => {} } } @@ -1091,9 +1132,11 @@ fn workflow_code(line: &str) -> &str { } /// 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. +/// `run` value): each comment ends at its line break, quotes stay open across line breaks, and a +/// `#` starts a comment only where a word starts (`build#1` is one word). 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 previous = None; for c in script.chars() { if comment { comment = c != '\n'; @@ -1106,13 +1149,14 @@ fn shell_code(script: &str) -> String { } else if quote.is_none() { match c { '\'' | '"' => quote = Some(c), - '#' => comment = true, + '#' => comment = previous.is_none_or(|p: char| p.is_whitespace() || matches!(p, ';' | '&' | '|' | '(' | ')')), _ => {} } } if !comment { out.push(c); } + previous = Some(c); } out } @@ -1371,6 +1415,30 @@ fn norm_words(b: &[u8]) -> String { String::from_utf8_lossy(&out).into_owned() } +/// [`norm`], with each cast to a primitive type (`Kind::A as u8`) written as an element of an array +/// literal (`[Kind::A][0]`): the names the operand reads still count, but the result, a primitive +/// value whatever the type of the operand, is not a [`user_value`]. +fn norm_values(b: &[u8]) -> String { + const PRIMITIVES: &[&[u8]] = + &[b"u8", b"u16", b"u32", b"u64", b"u128", b"usize", b"i8", b"i16", b"i32", b"i64", b"i128", b"isize", b"f32", b"f64", b"bool", b"char"]; + let mut text = norm_words(b).into_bytes(); + let mut from = 0; + while let Some(at) = text[from..].windows(4).position(|w| w == b" as ").map(|p| p + from) { + let start = receiver_start(&text, at); + let ty = at + 4; + let end = ty + text[ty..].iter().take_while(|&&c| is_ident(c)).count(); + if start < at && PRIMITIVES.contains(&&text[ty..end]) { + let element: Vec = [&b"["[..], &text[start..at], b"][0]"].concat(); + from = start + element.len(); + text.splice(start..end, element); + } else { + from = at + 1; + } + } + text.retain(|c| !c.is_ascii_whitespace()); + String::from_utf8_lossy(&text).into_owned() +} + /// Line starts, to turn byte offsets into 1-based lines. struct Lines(Vec); @@ -1901,8 +1969,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. +/// A closure or async block bound to `_` (`let _ = async { … };`, `let _ = async || { … };`), or to +/// a name the rest of the test never mentions, is never run, so its statement is replaced too. fn executed(m: &[u8], tests: &[TestFn]) -> Vec { let mut out = m.to_vec(); for t in tests { @@ -1916,15 +1984,13 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec { .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'=') - { + let name = skip_ws(m, at + 3); + let name_end = name + m[name..t.close].iter().copied().take_while(|&c| is_ident(c)).count(); + let eq = skip_ws(m, name_end); + if name_end == name || m.get(eq) != Some(&b'=') || m.get(eq + 1) == Some(&b'=') { continue; } + let wild = &m[name..name_end] == b"_"; let mut value = skip_ws(m, eq + 1); let is_async = m[value..].starts_with(b"async") && !m.get(value + 5).copied().is_some_and(is_ident); if is_async { @@ -1934,13 +2000,14 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec { value = skip_ws(m, value + 4); } let end = statement_end(m, at); - // The block alone is the value; `async { … }.await` runs it. - let unrun = if is_async { - m.get(value) == Some(&b'{') && matching(m, value).is_some_and(|close| skip_ws(m, close + 1) == end) - } else { - m.get(value) == Some(&b'|') - }; - if unrun && end < t.close { + // A closure (`|…| …`, `async |…| …`, `async move |…| …`) runs only when called. The block + // alone is the value; `async { … }.await` runs it. + let closure = m.get(value) == Some(&b'|'); + let unrun = closure || (is_async && m.get(value) == Some(&b'{') && matching(m, value).is_some_and(|close| skip_ws(m, close + 1) == end)); + // A value bound to `_` is dropped; one bound to a name the rest of the test never + // mentions is never called or awaited. + let dropped = wild || words(m, &m[name..name_end], end, t.close).is_empty(); + if unrun && dropped && end < t.close { blank(&mut out, at, end + 1); } } @@ -2060,13 +2127,8 @@ fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool { } statement_end(body, at) < pos && pos < block_close(body, at) }); - let loops = words(body, b"for", 0, pos).into_iter().any(|at| { - let Some((open, close)) = block_after(body, at + 3) else { return false }; - let Some(&in_at) = words(body, b"in", at + 3, open).first() else { return false }; - open < pos && pos < close && !words(body, name, at + 3, in_at).is_empty() - }); let name = String::from_utf8_lossy(name); - lets || loops || arm_binding(body, &name, pos).is_some() || closure_binding(body, &name, pos).is_some() + lets || for_binding(body, &name, pos).is_some() || arm_binding(body, &name, pos).is_some() || closure_binding(body, &name, pos).is_some() } /// Whether the `let` pattern in `body[start..end]` binds `name`: not in its type annotation @@ -2116,14 +2178,16 @@ fn enclosing_open(m: &[u8], at: usize) -> Option { /// where its value is kept: not in a statement of its own (`(body,);`), a `let _` or `let _name` /// binding, or a `drop` or `forget` call. fn passed_names(m: &[u8], open: usize, close: usize) -> Vec<(String, usize)> { + // Non-ASCII letters (`vérifier`) 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 names = Vec::new(); let mut at = open + 1; while at < close { - if !is_ident(m[at]) || (at > 0 && (is_ident(m[at - 1]) || m[at - 1] == b'.')) { + if !ident(m[at]) || (at > 0 && (ident(m[at - 1]) || m[at - 1] == b'.')) { at += 1; continue; } - let end = at + m[at..close].iter().take_while(|&&c| is_ident(c)).count(); + let end = at + m[at..close].iter().take_while(|&&c| ident(c)).count(); let before = m[..at].trim_ascii_end().last().copied(); let after = m.get(skip_ws(m, end)).copied(); if matches!(before, Some(b'(' | b'[' | b',')) && matches!(after, Some(b')' | b']' | b',')) && value_kept(m, open, at) { @@ -5063,6 +5127,8 @@ struct Binding { counts: bool, /// The local whose method the initializer calls (`xs` in `let n = xs.len()`). source: Option>, + /// Where the block that holds the `let` closes, after which the name no longer refers to it. + scope_end: usize, } /// Every `let` of a plain name in `body`, in order. @@ -5084,7 +5150,8 @@ fn bindings(body: &[u8]) -> Vec { let counts = SIZE_CHECKS.iter().any(|g| init.contains(g)); let ident = init.bytes().take_while(|&c| is_ident(c)).count(); let source = (ident > 0 && init[ident..].starts_with('.')).then(|| init.as_bytes()[..ident].to_vec()); - Some(Binding { name: body[start..end].to_vec(), end: stop, counts, source }) + let scope_end = enclosing_block(body, at).and_then(|(open, _)| matching(body, open)).unwrap_or(body.len()); + Some(Binding { name: body[start..end].to_vec(), end: stop, counts, source, scope_end }) }) .collect() } @@ -5099,7 +5166,7 @@ fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> if field_or_path(prefix) { return false; } - let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p); + let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p && p < o.scope_end); 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))) }) @@ -5171,37 +5238,45 @@ 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]); - let c = unparenthesized(&c); - let mut start = 0; - top_level_at(c, "||").into_iter().chain([c.len()]).any(|end| { - if end < start { - return false; - } - let alternative = c.get(start..end); - start = end.saturating_add(2); - alternative.is_some_and(|alternative| { - let mut start = 0; - top_level_at(alternative, "&&").into_iter().chain([alternative.len()]).all(|end| { - if end < start { - return true; - } - let operand = alternative.get(start..end); - start = end.saturating_add(2); - operand.is_some_and(|operand| operand.contains(".success()") || operand.contains(".code()")) - }) - }) - }) - }) - }; + let status_only = |a: &MacroCall| a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| status_condition(&norm(&v.file.m[from..to]), 0)); 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 pass on an exit status alone: one of its `||` +/// alternatives is made only of `&&` operands that read `.success()` or `.code()`, with each +/// parenthesized operand judged the same way. Conditions nested more than 64 levels deep are not +/// judged. +fn status_condition(c: &str, depth: usize) -> bool { + if depth > 64 { + return false; + } + fn split<'a>(s: &'a str, op: &str) -> Vec<&'a str> { + let mut parts = vec![]; + let mut start = 0; + for at in top_level_at(s, op) { + if at >= start { + parts.push(&s[start..at]); + start = at + op.len(); + } + } + parts.push(&s[start..]); + parts + } + let c = unparenthesized(c); + split(c, "||").into_iter().any(|alternative| { + split(alternative, "&&").into_iter().all(|operand| { + if operand.starts_with('(') && matching(operand.as_bytes(), 0) == Some(operand.len() - 1) { + status_condition(operand, depth + 1) + } 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]) { @@ -6534,7 +6609,8 @@ fn fixture_operator_runs(op: &str, at: usize, pos: usize, local: &LocalAt) -> bo return false; } let width = if matches!(c, b'<' | b'>') { - if next != Some(c) || previous == Some(c) || b.get(at + 2) == Some(&b'=') { + // `>>` can also close two generic argument lists (`None::>`). + if next != Some(c) || previous == Some(c) || b.get(at + 2) == Some(&b'=') || (c == b'>' && generic_depth(&b[..at]) > 0) { return false; } 2 @@ -6569,6 +6645,27 @@ fn fixture_operator_runs(op: &str, at: usize, pos: usize, local: &LocalAt) -> bo holds_user_value(&op[from..end], pos, local) } +/// How many turbofish generic argument lists (`::<…>`, with the `<…>` nested in them) are still +/// open at the end of a whitespace-free operand. +fn generic_depth(op: &[u8]) -> usize { + let mut depth = 0usize; + let mut i = 0; + while i < op.len() { + if op[i..].starts_with(b"::<") { + depth += 1; + i += 3; + continue; + } + match op[i] { + b'<' if depth > 0 => depth += 1, + b'>' if depth > 0 => depth -= 1, + _ => {} + } + i += 1; + } + depth +} + /// 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. @@ -6661,9 +6758,17 @@ fn holds_user_value(expr: &str, pos: usize, local: &LocalAt) -> bool { let b = expr.as_bytes(); let Some(open) = b.iter().position(|c| matches!(c, b'(' | b'[' | b'{')) else { return user_value(expr, pos, local) }; let Some(close) = matching(b, open) else { return false }; - // An element indexed out of a local (`xs[0]`) is a user value when the local's value holds one. - if b[open] == b'[' && close + 1 == b.len() && plain_local(&expr[..open]) && b[0].is_ascii_lowercase() { - return holds_user_value(&expr[..open], pos, local); + // An element indexed out of a local (`xs[0]`, `rows[0][1]`) is a user value when the local's + // value holds one. + if b[open] == b'[' && plain_local(&expr[..open]) && b[0].is_ascii_lowercase() { + let mut end = close + 1; + while b.get(end) == Some(&b'[') { + let Some(next) = matching(b, end) else { return false }; + end = next + 1; + } + if end == b.len() { + return holds_user_value(&expr[..open], pos, local); + } } // Only a whole container exposes its elements, not the result of a method such as `len`. if close + 1 != b.len() || expr[..open].bytes().any(|c| !is_ident(c) && !matches!(c, b':' | b'!')) { @@ -6901,7 +7006,7 @@ fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, u if stop > before || block_close(body, at) < before { continue; } - let rest = norm(&body[n1..stop]); + let rest = norm_values(&body[n1..stop]); let plain = n1 > n0 && (rest.is_empty() || rest.starts_with(':') || rest.starts_with('=')); if plain && &body[n0..n1] == name.as_bytes() { let init = rest.split_once('=').filter(|(ty, _)| ty.is_empty() || ty.starts_with(':')).map(|(_, init)| (init.to_owned(), at)); @@ -7012,7 +7117,7 @@ fn echoes(v: &View) -> Option { return None; } for &(from, to) in a.args.iter().take(n) { - let op = norm(&body[from - v.t.open..to - v.t.open]); + let op = norm_values(&body[from - v.t.open..to - v.t.open]); reads_local |= inert_at(&body, &op, from - v.t.open, 0)?.0; } } @@ -8957,12 +9062,17 @@ mod tests { "let _ = async move { assert_eq!(f(), 1); };", "let _ = || assert_eq!(f(), 1);", "let _ = move |x| assert_eq!(x, 1);", + "let _ = async || { assert_eq!(compute(), 1); };", + "let _ = async move |x| { assert_eq!(x, 1); };", + "let _future = 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"); + assert_eq!(hits(&kept.replace(" check();\n", "")), [(2, "no-assertion")], "a named closure that is never called"); + assert_eq!(hits(&kept.replace(" check();\n", " run(check);\n")), [], "a named closure passed on can be called"); let awaited = "#[test]\nfn t() {\n let _ = async { assert_eq!(f(), 1); }.await;\n}\n"; assert_eq!(hits(awaited), [], "an awaited block runs"); let conditional = "#[test]\nfn t() {\n if let _ = || () {\n assert_eq!(f(), 1);\n };\n}\n"; @@ -9044,6 +9154,14 @@ mod tests { } } + #[test] + fn process_status_checks_judge_parenthesized_operands_by_their_own_operands() { + let good = "#[test]\nfn t() {\n let status = Command::new(\"cp\").arg(src).arg(&destination).status().unwrap();\n assert!(status.success() && (status.success() && destination.exists()));\n}\n"; + assert_eq!(hits(good), []); + let alternative = good.replace("(status.success() && destination.exists())", "(status.success() || destination.exists())"); + assert_eq!(hits(&alternative), [(2, "exit-status-only")]); + } + #[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"] { @@ -9580,6 +9698,38 @@ mod tests { } } + #[test] + fn printed_assignments_are_found_past_quoted_separators() { + for line in [" printf '%s;' 'MY_SAMPLES=fixtures'", " echo 'a|b' \"MY_SAMPLES=fixtures\"", " echo \"a && b\" MY_SAMPLES=x"] { + assert_eq!(upper_words(line).collect::>(), Vec::::new(), "{line}"); + } + assert_eq!(upper_words(" printf '%s;' 'MY_SAMPLES=fixtures' >> \"$GITHUB_ENV\"").collect::>(), ["MY_SAMPLES"]); + } + + #[test] + fn only_the_printing_pipeline_writes_the_environment_file() { + let script = "run: \"echo \\\"MY_SAMPLES=fixtures\\\"\\necho \\\"OTHER=x\\\" >> \\\"$GITHUB_ENV\\\"\""; + assert_eq!(upper_words(script).collect::>(), ["OTHER"]); + for line in [ + " echo \"MY_SAMPLES=fixtures\" | tee -a \"$GITHUB_ENV\"", + " echo \"MY_SAMPLES=fixtures\" 2>&1 >> \"$GITHUB_ENV\"", + " true; echo \"MY_SAMPLES=fixtures\" >> \"$GITHUB_ENV\"", + ] { + assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); + } + assert_eq!(upper_words(" echo \"MY_SAMPLES=fixtures\"; echo x >> \"$GITHUB_ENV\"").collect::>(), Vec::::new()); + } + + #[test] + fn a_hash_inside_a_word_does_not_start_a_comment() { + for line in ["run: \"echo build#1; export MY_SAMPLES=fixtures; cargo test\"", "run: echo build#1; export MY_SAMPLES=fixtures"] { + assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); + } + for line in ["run: \"echo build # MY_SAMPLES=fixtures\"", "run: echo build # MY_SAMPLES=fixtures", "run: \"true;# MY_SAMPLES=fixtures\""] { + assert_eq!(upper_words(line).collect::>(), Vec::::new(), "{line}"); + } + } + #[test] fn quoted_assignment_command_arguments_set_workflow_variables() { for line in [ @@ -9845,6 +9995,14 @@ mod tests { assert_eq!(hits(inside), []); } + #[test] + fn counts_bound_in_a_closed_block_do_not_guard_all() { + let src = "#[test]\nfn t() {\n let xs = f();\n let n = 1;\n {\n let n = xs.len();\n use_it(n);\n }\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), [(10, "all-unguarded")]); + let same_block = src.replace(" {\n let n = xs.len();\n use_it(n);\n }\n", " let n = xs.len();\n"); + assert_eq!(hits(&same_block), []); + } + #[test] fn constants_with_several_values_are_unknown() { let src = "mod a { const START: usize = 0; }\nmod b {\nconst START: usize = 2;\nconst END: usize = 2;\n#[test]\nfn t() {\n let xs: Vec = (START..END).collect();\n assert!(xs.iter().all(|x| *x > 0));\n}\n}\n"; @@ -9859,6 +10017,10 @@ mod tests { assert_eq!(hits(src), []); let cleared = src.replace(" assert_eq!(n, 1);", " xs.clear();\n assert_eq!(n, 1);"); assert_eq!(hits(&cleared), [(7, "all-unguarded")]); + let field = src.replace(" assert_eq!(n, 1);", " assert_eq!(n, 1);\n (other.xs, _) = (vec![], 0);"); + assert_eq!(hits(&field), [], "a field with the same name is another collection"); + let replaced = src.replace(" assert_eq!(n, 1);", " assert_eq!(n, 1);\n (xs, _) = (vec![], 0);"); + assert_eq!(hits(&replaced), [(7, "all-unguarded")]); } #[test] @@ -11343,12 +11505,23 @@ mod tests { assert_eq!(hits_in("crates/x/src/tests.rs", &looped, &ctx), [(8, "no-assertion")], "a loop pattern shadows the helper in the loop body"); let after_loop = src.replace(" keeping(body);", " for body in [|| {}] {\n let _ = body;\n }\n keeping(body);"); assert_eq!(hits_in("crates/x/src/tests.rs", &after_loop, &ctx), [], "the helper after the loop"); + let block_source = src.replace(" keeping(body);", " for body in { [noop as fn()] } {\n keeping(body);\n }"); + assert_eq!( + hits_in("crates/x/src/tests.rs", &block_source, &ctx), + [(8, "no-assertion")], + "a loop over a block expression shadows the helper in the loop body" + ); + let in_source = src.replace(" keeping(body);", " for body in { keeping(body); [noop as fn()] } {\n let _ = body;\n }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &in_source, &ctx), [], "a loop pattern does not reach the loop's source"); let unused = src.replace(" keeping(body);", " let _unused = (body,);"); assert_eq!(hits_in("crates/x/src/tests.rs", &unused, &ctx), [(8, "no-assertion")], "a tuple that is never called"); let dropped = src.replace(" keeping(body);", " (body,);"); assert_eq!(hits_in("crates/x/src/tests.rs", &dropped, &ctx), [(8, "no-assertion")], "a tuple in a statement of its own"); let table = src.replace(" keeping(body);", " let cases = [(\"case\", body)];\n run(&cases);"); assert_eq!(hits_in("crates/x/src/tests.rs", &table, &ctx), [], "a table of named cases"); + let accented = src.replace("body", "vérifier"); + let accented_ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), accented.clone())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &accented, &accented_ctx), [], "a helper with a non-ASCII name"); let idle = src.replace("assert_eq!(f(), 1);", "f();"); let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), idle.clone())]), ..Ctx::default() }; assert_eq!(hits_in("crates/x/src/tests.rs", &idle, &ctx), [(8, "no-assertion")], "a passed body that checks nothing"); @@ -12572,6 +12745,31 @@ mod tests { 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"); + let nested = "#[test]\nfn t() {\n let rows = [[Amount(2), Amount(3)]];\n assert_eq!(rows[0][0] + rows[0][1], Amount(5));\n}\n"; + assert_eq!(only("fixture-only", nested), [], "an element indexed twice out of a user-value array"); + let nested_primitive = nested.replace("Amount(2), Amount(3)", "2, 3"); + assert_eq!(only("fixture-only", &nested_primitive), [(2, "fixture-only")], "an element indexed twice out of a primitive array"); + } + + #[test] + fn casts_and_turbofish_types_are_not_operators_on_user_values() { + for expr in ["Kind::A as u8 + 1", "(Kind::A as u8) << 2", "None::>"] { + 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 ["Kind::A + 1", "Some::(Amount(2)) >> 1"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({expr}, EXPECTED);\n}}\n"); + assert_eq!(only("constant-echo", &src), [], "{expr} runs an operator on a user value"); + } + let cast_local = "#[test]\nfn t() {\n let k = Kind::A as u8;\n assert_eq!(k + 1, 2);\n}\n"; + assert_eq!(only("fixture-only", cast_local), [(2, "fixture-only")]); + for computed in [ + "#[test]\nfn t() {\n let got = compute();\n assert_eq!(got as u8, 2);\n}\n", + "#[test]\nfn t() {\n let got = compute() as u8;\n assert_eq!(got, 2);\n}\n", + ] { + assert_eq!(only("constant-echo", computed), [], "{computed}"); + assert_eq!(only("fixture-only", computed), [], "{computed}"); + } } #[test]