xtask: test-lint reads grouped values, later checks and non-ASCII names more exactly

- A closure or async block bound to `_` inside parentheses
  (`let _ = (|| { … });`) is dropped unrun; `(|| { … })()` still runs.
- A length check after an `.all(…)` assertion guards it only when no code
  between them changes the local's item count (`xs.push(1)` included).
- A strict bound (`xs.len() > 1`, `1 < xs.len()`) gives one item more
  than its count, so `.windows(2)` after `> 1` is guarded.
- An index into the outer collection no longer guards `.all(…)` over an
  item read through `.iter_mut()`, `.windows(…)`, `.chunks(…)` or
  `.chunks_exact(…)`.
- A grouped argument (`std::mem::take((xs))`) is found as a call that can
  change a `&mut` local; `(xs).len()` stays a read.
- A nested `fn` with a non-ASCII name is skipped by the polling scan.
- A non-ASCII container local is followed to its initializer when deciding
  whether a conversion can test a user value.
- A `cfg` attribute covers a function whose return type holds `;`
  (`-> Result<(), [u8; 2]>`), so `never-run` reports it.
- The test repository directory comes from `tempfile`, created for the
  test alone.
This commit is contained in:
dotCooCoo committed 2026-12-04 01:07:44 -08:00
1 parent fe8cdbf220
commit 9c8f31344a
1 file changed
+102 -37
+102 -37
View File
@@ -1992,6 +1992,18 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec<u8> {
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;
while m.get(value) == Some(&b'(') {
match matching(m, value) {
Some(close) if skip_ws(m, close + 1) == limit => {
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);
@@ -1999,11 +2011,10 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec<u8> {
if m[value..].starts_with(b"move") && !m.get(value + 4).copied().is_some_and(is_ident) {
value = skip_ws(m, value + 4);
}
let end = statement_end(m, at);
// 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) == end));
|| (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);
}
@@ -2362,7 +2373,7 @@ fn all_unguarded(v: &View) -> Vec<Hit> {
// 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).
let mut direct: Vec<(String, usize, Option<String>)> = vec![];
let mut direct: Vec<(String, usize, Option<(String, bool)>)> = 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);
@@ -2405,11 +2416,22 @@ fn all_unguarded(v: &View) -> Vec<Hit> {
.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);
let need = cond.match_indices(".all(").map(|(i, _)| receiver_need(&cond[..i], &sizes).1).max().unwrap_or(1);
!direct.iter().any(|(name, to, count)| {
let least = count.as_deref().and_then(|c| sizes.count(c)).unwrap_or(1).max(1);
least >= need && (*to >= at || !may_shrink(&body[..at], name.as_bytes(), *to))
let least = count.as_ref().and_then(|(c, strict)| sizes.count(c).map(|n| n + usize::from(*strict))).unwrap_or(1).max(1);
// A check inside the assertion guards it. A check before it holds while nothing between
// them shrinks or replaces the local; a check after it, while nothing between them
// changes its item count at all (`xs.push(1)` included).
let unchanged = if *to < at {
!may_shrink(&body[..at], name.as_bytes(), *to)
} else if *to <= end {
true
} else {
!may_change(&body[..*to], name.as_bytes(), end, false)
};
least >= need && unchanged
})
})
.filter(|a| {
@@ -2430,19 +2452,30 @@ fn all_unguarded(v: &View) -> Vec<Hit> {
/// 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.
fn compared_count(a: &MacroCall, body: &[u8], open: usize, around: (&str, &str), read: &str) -> Option<String> {
/// 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))?;
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[..r.find(|c: char| !token(c)).unwrap_or(r.len())]);
let left = ["==", "<=", "<"].iter().find_map(|op| before.strip_suffix(op)).map(|l| &l[l.rfind(|c: char| !token(c)).map_or(0, |p| p + 1)..]);
right.or(left).map(str::to_owned)
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(…))`)
@@ -3890,7 +3923,9 @@ fn first_item_guard(body: &[u8], sizes: &Sizes) -> bool {
};
}
let calls = &compact[end + 1..chain];
let all_over_item = [".iter()", ".into_iter()"].iter().any(|m| calls.starts_with(m)) && calls.ends_with('.');
let all_over_item =
[".iter()", ".into_iter()", ".iter_mut()", ".windows(", ".chunks(", ".chunks_exact("].iter().any(|m| calls.starts_with(m))
&& calls.ends_with('.');
!all_over_item && array_literal_len(&compact[..=end], sizes).is_none_or(|n| n == 0)
});
indexed || unwrapped.iter().any(|g| compact.contains(g)) || panicking_first_binding(body)
@@ -5002,11 +5037,13 @@ fn may_change(body: &[u8], name: &[u8], from: usize, allow_growth: bool) -> bool
false
};
// A local that already holds a `&mut` reborrows it when passed to a function or method
// (`std::mem::take(xs)`), which can change it; a macro such as `assert_eq!` only reads it.
// (`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
&& (before.ends_with(b"(") || before.ends_with(b","))
&& matches!(after.first(), Some(b')' | b','))
&& enclosing_open(body, p).is_some_and(|open| {
&& (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
@@ -5939,7 +5976,7 @@ fn polls_or_releases(m: &[u8], at: usize, imports: Imports) -> bool {
/// declaration without a body.
fn fn_item_span(m: &[u8], kw: usize, to: usize) -> Option<(usize, usize)> {
let name = skip_ws(m, kw + 2);
let name_end = name + m[name..to].iter().take_while(|&&c| is_ident(c)).count();
let name_end = name + m[name..to].iter().take_while(|&&c| is_ident(c) || c >= 0x80).count();
if name_end == name {
return None;
}
@@ -6794,7 +6831,8 @@ fn holds_user_value(expr: &str, pos: usize, local: &LocalAt) -> bool {
if let Some((base, field)) = last_field(expr) {
return field_value(base, field, pos, local).is_some_and(|(v, at)| holds_user_value(&v, at, local));
}
if plain_local(expr) {
// 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();
@@ -7429,10 +7467,15 @@ fn cfg_spans(m: &[u8], src: &[u8]) -> Vec<CfgSpan> {
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 });
@@ -8120,16 +8163,13 @@ mod tests {
lint_file(path, src, ctx).into_iter().map(|h| (h.line, h.rule.id())).collect()
}
/// A new directory under the system temporary directory, removed when the guard is dropped,
/// including when an assertion fails.
struct TempRepo(std::path::PathBuf);
/// 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 {
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("test-lint-{name}-{}-{unique}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
Self(tempfile::Builder::new().prefix(&format!("test-lint-{name}-")).tempdir().unwrap())
}
}
@@ -8137,13 +8177,7 @@ mod tests {
type Target = Path;
fn deref(&self) -> &Path {
&self.0
}
}
impl Drop for TempRepo {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
self.0.path()
}
}
@@ -8162,6 +8196,12 @@ mod tests {
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 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");
@@ -8207,6 +8247,12 @@ mod tests {
assert_eq!(hits(&cleaned), [], "a collection cleared after the assertion it guards");
let between = good.replace("> 0));\n", "> 0));\n xs.clear();\n assert!(xs.iter().all(|x| *x > 1));\n");
assert_eq!(hits(&between), [(7, "all-unguarded")], "only the assertion after the clear");
let 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);");
@@ -9061,6 +9107,10 @@ mod tests {
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");
}
@@ -9140,6 +9190,8 @@ mod tests {
"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}");
@@ -9148,6 +9200,8 @@ mod tests {
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");
@@ -10248,6 +10302,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";
@@ -12727,7 +12783,9 @@ mod tests {
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);"] {
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}");
}
@@ -12754,6 +12812,7 @@ mod tests {
"fn unused() {\n probe();\n }",
"fn unused<F: Fn(u8)>(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"
@@ -12763,6 +12822,8 @@ mod tests {
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]
@@ -12846,6 +12907,10 @@ mod tests {
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");
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}");