xtask: test-lint resolves shadowed helpers, literal selectors and aliases

- A renamed import (`use super::other::near as comparison;`) no longer
  counts as a call with a path; an import that keeps the name still does.
- A bare call to a helper's name checks for a local binding in scope
  (`let near = || {}; near();`), skipping type annotations, field labels
  and path segments in patterns.
- Helpers passed in assertion failure messages no longer count as checks.
- A match-arm binding covers the arm's guard, and the arm's pattern stops
  at the block of the arm before it.
- `#[ ignore = "..."]` with whitespace is read as an ignore attribute,
  both for diagnostic tests and for ignore-without-reason.
- Literal ranges read `0x`, `0o` and `0b` bounds.
- A pin compares literal arguments (`r.items("active")` against
  `r.items("archived")`), and does not count when a clone or borrow of the
  source made before the snapshot is still alive.
- A function parameter named like a constant table is not the table.
This commit is contained in:
dotCooCoo
2026-12-02 02:31:56 -08:00
parent df12f897d4
commit fde52f43a2
+397 -37
View File
@@ -1180,6 +1180,11 @@ const COMMON: &[&str] = &[
/// The names called in `m[from..to]`: functions (`name(`, also through a path), methods
/// (`.name(`), including calls with turbofish arguments, and macros (`name!`).
fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> {
calls_at(m, from, to).into_iter().map(|(name, method, _)| (name, method)).collect()
}
/// [`calls`] with the offset of each called name.
fn calls_at(m: &[u8], from: usize, to: usize) -> Vec<(String, bool, usize)> {
let m = &m[..to];
let mut out = vec![];
let mut i = from;
@@ -1196,7 +1201,7 @@ fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> {
let name = String::from_utf8_lossy(&m[i..end]).into_owned();
let method = i > 0 && m[i - 1] == b'.';
if !KEYWORDS.contains(&name.as_str()) {
out.push((if bang { format!("{name}!") } else { name }, method));
out.push((if bang { format!("{name}!") } else { name }, method, i));
}
}
i = end;
@@ -1369,10 +1374,50 @@ pub fn asserting_helpers(files: &[(String, String)]) -> HashMap<String, HashSet<
out
}
/// Whether the masked file names `name` (a function, or `name!` for a macro) after a `::` path.
/// Whether the masked file names `name` (a function, or `name!` for a macro) after a `::` path,
/// other than in a `use` declaration that renames it (`use other::near as comparison;`). An import
/// that keeps the name can bring another module's `name` into scope.
fn called_with_path(m: &[u8], name: &str) -> bool {
let name = name.trim_end_matches('!');
words(m, name.as_bytes(), 0, m.len()).into_iter().any(|at| m[..at].trim_ascii_end().ends_with(b"::"))
words(m, name.as_bytes(), 0, m.len()).into_iter().any(|at| {
let after = skip_ws(m, at + name.len());
let renamed = m[after..].starts_with(b"as") && !m.get(after + 2).copied().is_some_and(is_ident) && {
let mut alias = skip_ws(m, after + 2);
if m[alias..].starts_with(b"r#") {
alias += 2;
}
let alias_end = alias + m[alias..].iter().take_while(|&&c| is_ident(c)).count();
&m[alias..alias_end] != name.as_bytes()
};
m[..at].trim_ascii_end().ends_with(b"::") && !(renamed && in_use(m, at))
})
}
/// Whether the masked text at `at` is inside a `use` declaration, its groups (`use a::{b, c}`)
/// included.
fn in_use(m: &[u8], at: usize) -> bool {
let mut depth = 0usize;
let mut start = 0;
for i in (0..at).rev() {
match m[i] {
b'}' => depth += 1,
b'{' if depth > 0 => depth -= 1,
b'{' if m[..i].trim_ascii_end().ends_with(b"::") => {}
b'{' | b';' if depth == 0 => {
start = i + 1;
break;
}
_ => {}
}
}
let mut s = m[start..at].trim_ascii_start();
if let Some(rest) = s.strip_prefix(b"pub").filter(|r| !r.first().copied().is_some_and(is_ident)) {
s = rest.trim_ascii_start();
if s.first() == Some(&b'(') {
s = matching(s, 0).map_or(&[][..], |close| s[close + 1..].trim_ascii_start());
}
}
s.starts_with(b"use") && !s.get(3).copied().is_some_and(is_ident)
}
/// The asserting helpers a test in the file at `path` can reach: for a top-level test, the file's
@@ -1577,10 +1622,22 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec<Hit> {
let asserts: Vec<MacroCall> = macro_calls(m, t.open, t.close).into_iter().filter(|c| is_assert_macro(&c.name)).collect();
let none = HashSet::new();
let helpers = helpers_for(ctx, file.path, file.depths[t.attr] == 0).unwrap_or(&none);
let delegates = calls(m, t.open, t.close)
.iter()
.any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers))
|| passes_helper(m, t, helpers);
// Failure messages run only after an assertion has failed, so a helper there does not check.
let messages: Vec<(usize, usize)> = asserts.iter().flat_map(|a| a.args.iter().skip(guard_arg_count(&a.name)).copied()).collect();
let quiet = |at: usize| !messages.iter().any(|&(from, to)| from <= at && at < to);
// A bare call of a helper's name reaches a local binding of that name where one is in scope; a
// name that says it checks (`check_…`) counts either way.
let delegates = calls_at(m, t.open, t.close).iter().any(|(n, method, at)| {
n != &t.name
&& quiet(*at)
&& !(n.ends_with('!') && is_assert_macro(n))
&& is_helper_call(n, *method, helpers)
&& (*method
|| n.ends_with('!')
|| is_helper_call(n, false, &HashSet::new())
|| m[..*at].trim_ascii_end().ends_with(b"::")
|| !shadows_helper(m, t.fn_at, t.open, t.close, n.as_bytes(), *at))
}) || passes_helper(m, t, helpers, &quiet);
let checks = checks_itself(m, t.open, t.close);
let should_panic = should_panic_attr(m, t.attr, t.fn_at);
let diagnostic = ignored_with_reason(file, t.attr, t.fn_at) && prints(m, t.open, t.close);
@@ -1598,10 +1655,11 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec<Hit> {
/// Whether a test's body passes an asserting helper by name as a value, an argument or a tuple
/// element (`keeping_settings(the_test_body)`, `[("case", case_body), …]`), excluding local bindings
/// and parameters that shadow helper names.
fn passes_helper(m: &[u8], t: &TestFn, helpers: &HashSet<String>) -> bool {
/// and parameters that shadow helper names. Only names at offsets `counts` accepts count.
fn passes_helper(m: &[u8], t: &TestFn, helpers: &HashSet<String>, counts: &dyn Fn(usize) -> bool) -> bool {
passed_names(m, t.open, t.close).into_iter().any(|(name, pos)| {
name != t.name
counts(pos)
&& name != t.name
&& !COMMON.contains(&name.as_str())
&& helpers.contains(&name)
&& !shadows_helper(m, t.fn_at, t.open, t.close, name.as_bytes(), pos)
@@ -1629,7 +1687,7 @@ fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool {
}
end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 };
}
if words(body, name, start, end).is_empty() {
if !pattern_binds(body, name, start, end) {
return false;
}
let head = body[..at].trim_ascii_end();
@@ -1649,6 +1707,34 @@ fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool {
lets || loops || 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
/// (`let cb: body = …`) or as a field label (`let Row { near: _ } = …`).
fn pattern_binds(body: &[u8], name: &[u8], start: usize, end: usize) -> bool {
let annotation = annotation_start(body, start, end);
words(body, name, start, annotation).into_iter().any(|at| {
let after = skip_ws(body, at + name.len());
let label = after != annotation && body.get(after) == Some(&b':') && body.get(after + 1) != Some(&b':');
// A path segment (`let model::near = …`) names a constant or unit struct.
let path = body[..at].trim_ascii_end().ends_with(b"::") || body[after..].starts_with(b"::");
!label && !path
})
}
/// The offset of a `let` pattern's type annotation in `body[start..end]`: its `:` outside the
/// pattern's brackets (not a `::` path), or `end` when there is none.
fn annotation_start(body: &[u8], start: usize, end: usize) -> usize {
let mut i = start;
while i < end {
match body[i] {
b'(' | b'[' | b'{' => i = matching(body, i).map_or(end, |close| close + 1),
b':' if body.get(i + 1) == Some(&b':') => i += 2,
b':' => return i,
_ => i += 1,
}
}
end
}
/// The innermost unclosed `(`, `[` or `{` before `at`.
fn enclosing_open(m: &[u8], at: usize) -> Option<usize> {
let mut depth = 0usize;
@@ -1762,7 +1848,7 @@ fn ignored_with_reason(file: &File, from: usize, to: usize) -> bool {
let m = &file.m;
words(m, b"ignore", from, to).into_iter().any(|at| {
let j = skip_ws(m, at + "ignore".len());
m[..at].ends_with(b"#[")
m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#"))
&& m.get(j) == Some(&b'=')
&& ignore_reason(&file.src[skip_ws(m, j + 1)..]).is_some_and(|body| body.iter().any(|c| !c.is_ascii_whitespace()))
})
@@ -1843,13 +1929,19 @@ fn all_unguarded(v: &View) -> Vec<Hit> {
SIZE_CHECKS.iter().any(|g| norm(&body[from..to]).contains(g)) || reads_counted_local(&body, &locals, from, to)
})
});
let sizes = Sizes { file: &v.file.m, consts: OnceCell::new() };
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) {
return vec![];
}
v.asserts
.iter()
.filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && unguarded_all(&v.first_arg(a), &v.file.m[v.t.open..a.at], &sizes))
.filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str()))
.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();
*sizes.cond.borrow_mut() = (cond.as_ptr() as usize, cond.clone(), lits);
unguarded_all(&cond, &v.file.m[v.t.open..a.at], &sizes)
})
.map(|a| {
let mut h = v.hit(a.at, Rule::AllUnguarded, format!("{}!(…all(…)) with no length or emptiness check in the test", a.name));
h.first = v.file.lines.of(v.t.attr);
@@ -2308,7 +2400,8 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool {
return None;
}
let at = let_init(body, &s, bound).map_or(0, |(_, at)| statement_end(body, at));
Some((norm(text.as_bytes()), s, at))
let end = statement_end(body, bound);
Some((norm(text.as_bytes()), s, at, sizes.literals(let_value(body, bound, end), end)))
})
} else {
None
@@ -2318,7 +2411,7 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool {
return false;
}
let (left, right) = (norm(&body[a.args[0].0..a.args[0].1]), norm(&body[a.args[1].0..a.args[1].1]));
[(&left, &right), (&right, &left)].into_iter().any(|(pinned, literal)| {
[(&left, &right, a.args[0]), (&right, &left, a.args[1])].into_iter().any(|(pinned, literal, (from, to))| {
if literal_len(literal, sizes) == 0 {
return false;
}
@@ -2329,13 +2422,20 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool {
&& plain_local(pinned)
&& init(pinned, a.at).is_some_and(|(text, at)| {
let bound = statement_end(body, at);
let root = root_local(r);
let root_from = let_init(body, root, at).map_or(0, |(_, pos)| statement_end(body, pos));
keeping_base(&text, true) == r
&& 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_local(r), bound, r)
&& !touched_after(body, root, bound, r)
&& !gives_alias(&body[..at], root, root_from)
});
// The assertion compares the same call the receiver is bound to (`gaps(&word)`), so its
// literal is what the receiver holds.
read || source.as_ref().is_some_and(|(call, s, at)| pinned == call && !touched_after(body, s, *at, r))
// Literal arguments (`r.items("active")`) are masked, so they are compared from the source.
read || source
.as_ref()
.is_some_and(|(call, s, at, lits)| pinned == call && *lits == sizes.literals(from, to) && !touched_after(body, s, *at, r))
})
})
}
@@ -2369,6 +2469,66 @@ fn body_level_statement(body: &[u8], mut at: usize) -> bool {
statement
}
/// Where the value of the `let` at `at` starts: after its `=`, past the pattern and any type
/// annotation; `end` when it has none.
fn let_value(body: &[u8], at: usize, end: usize) -> usize {
let mut i = at + 3;
while i < end {
match body[i] {
b'(' | b'[' | b'{' => i = matching(body, i).map_or(end, |close| close + 1),
b'=' if !matches!(body.get(i + 1), Some(b'=' | b'>')) => return i + 1,
_ => i += 1,
}
}
end
}
/// Whether `body[from..]` may keep a second handle to the local `name` that can change what it
/// holds later: a `let` that binds it or a borrow of it (`let b = &r;`), or a clone of it
/// (`r.clone()`, `Rc::clone(&r)`) anywhere. A borrow that ends with its call (`populate(&mut r)`)
/// and a method call on it (`r.push(1)`, `let n = r.len();`) do not.
fn gives_alias(body: &[u8], name: &str, from: usize) -> bool {
if !plain_local(name) {
return true;
}
words(body, name.as_bytes(), from.min(body.len()), body.len()).into_iter().any(|at| {
let statement = body[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1);
let raw = body[statement..at].trim_ascii_start();
let head = norm(&body[statement..at]);
// `let b = &r;`, `let b = &mut r;` or `let b = r;` keeps the local itself; `let n = r.len();` reads it.
let whole = matches!(body.get(skip_ws(body, at + name.len())), Some(b';' | b',' | b')') | None);
let bound = raw.strip_prefix(b"let").is_some_and(|r| !r.first().copied().is_some_and(is_ident))
&& whole
&& ["=&", "=&mut", "="].iter().any(|end| head.ends_with(end));
let cloned = body[skip_ws(body, at + name.len())..].starts_with(b".clone()")
|| ["Rc::clone(&", "Arc::clone(&"].iter().any(|call| head.ends_with(call));
// A clone passed straight to `drop`, or bound to `_`, is gone before the snapshot.
let dropped = ["drop(", "drop(Rc::clone(&", "drop(Arc::clone(&"].iter().any(|call| head.ends_with(call))
|| head.starts_with("let_=")
|| head.starts_with("let_:");
if !(bound || (cloned && !dropped)) {
return false;
}
// A handle made in a block that closes before the snapshot, or a bound one dropped before
// it, is gone too.
let mut block = enclosing_open(body, at);
while let Some(open) = block.filter(|&o| body[o] != b'{') {
block = enclosing_open(body, open);
}
if block.is_some_and(|open| matching(body, open).is_some()) {
return false;
}
let pattern = raw.strip_prefix(b"let").map(<[u8]>::trim_ascii_start).unwrap_or_default();
let pattern = pattern.strip_prefix(b"mut ").map_or(pattern, <[u8]>::trim_ascii_start);
let alias = &pattern[..pattern.iter().take_while(|&&c| is_ident(c)).count()];
let dropped_later = !alias.is_empty()
&& words(body, alias, statement_end(body, at), body.len())
.into_iter()
.any(|use_at| body[..use_at].trim_ascii_end().strip_suffix(b"(").is_some_and(|h| h.trim_ascii_end().ends_with(b"drop")));
!dropped_later
})
}
/// The local a receiver path starts from: `r` of `r.items()`.
fn root_local(expr: &str) -> &str {
let end = expr.bytes().take_while(|&c| is_ident(c)).count();
@@ -2468,7 +2628,14 @@ fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool {
let table_end = body.bytes().take_while(|&c| is_ident(c) || c == b':').count();
let table = &body[..table_end];
let screaming = !table.is_empty() && table.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_');
if !screaming || item_len(table, sizes) == 0 || !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()")) {
// A parameter of the same name (`fn rows(TABLE: &[u8])`) is what the body reads.
let binds_table =
split_args(file, params_open + 1, params_close).into_iter().any(|(from, to)| pattern_binds(file, table.as_bytes(), from, to));
if !screaming
|| binds_table
|| item_len(table, sizes) == 0
|| !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()"))
{
return false;
}
// The body is the chain alone, of steps that keep every row.
@@ -2513,7 +2680,7 @@ fn let_binds(body: &[u8], name: &[u8]) -> bool {
}
end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 };
}
!words(body, name, start, end).is_empty()
pattern_binds(body, name, start, end)
})
}
@@ -3210,9 +3377,31 @@ fn field_len(receiver: &str, sizes: &Sizes) -> usize {
struct Sizes<'a> {
file: &'a [u8],
consts: OnceCell<HashMap<String, usize>>,
/// The file's source, and the offset in it of the test body that offsets are relative to.
src: &'a [u8],
open: usize,
/// The condition being checked: where its masked, whitespace-free text starts in memory, that
/// text, and its string literals' contents in order.
cond: RefCell<(usize, String, Vec<Vec<u8>>)>,
}
impl Sizes<'_> {
/// The contents of the string literals in `from..to` of the test body, in order.
fn literals(&self, from: usize, to: usize) -> Vec<Vec<u8>> {
literals_in(self.src, self.file, self.open + from, self.open + to)
}
/// The contents of the string literals of `r`, a slice of the condition being checked; `None`
/// when `r` is not one.
fn receiver_literals(&self, r: &str) -> Option<Vec<Vec<u8>>> {
// A character literal's masked text (`''`) does not say which character it holds.
(!r.contains("''")).then_some(())?;
let cond = self.cond.borrow();
let (base, masked, lits) = &*cond;
let at = (r.as_ptr() as usize).checked_sub(*base).filter(|&at| at + r.len() <= masked.len())?;
let first = masked.get(..at)?.matches('"').count() / 2;
lits.get(first..first + r.matches('"').count() / 2).map(<[Vec<u8>]>::to_vec)
}
/// An unsigned integer literal (with `_` and an integer suffix allowed) or a `const` of the
/// file whose value is one.
fn count(&self, text: &str) -> Option<usize> {
@@ -3220,14 +3409,27 @@ impl Sizes<'_> {
}
}
/// The contents of the string literals in `from..to`, in order: the source between each pair of
/// quotes that the masked text `m` keeps.
fn literals_in(src: &[u8], m: &[u8], from: usize, to: usize) -> Vec<Vec<u8>> {
let quotes: Vec<usize> = (from..to.min(m.len())).filter(|&i| m[i] == b'"').collect();
quotes.as_chunks::<2>().0.iter().map(|&[open, close]| src[open + 1..close].to_vec()).collect()
}
fn int_literal(text: &str) -> Option<usize> {
let digits = text.bytes().take_while(|c| c.is_ascii_digit() || *c == b'_').count();
let suffix = &text[digits..];
// A decimal literal, or a `0x`, `0o` or `0b` one, takes the same suffixes.
let (radix, body) = [("0x", 16), ("0o", 8), ("0b", 2)]
.into_iter()
.find_map(|(prefix, radix)| text.strip_prefix(prefix).map(|rest| (radix, rest)))
.unwrap_or((10, text));
let digits = body.bytes().take_while(|c| char::from(*c).is_digit(radix) || *c == b'_').count();
let suffix = &body[digits..];
let suffixes = ["", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize"];
if digits == 0 || !text.as_bytes()[0].is_ascii_digit() || !suffixes.contains(&suffix) {
let number = body[..digits].replace('_', "");
if number.is_empty() || (radix == 10 && !text.as_bytes()[0].is_ascii_digit()) || !suffixes.contains(&suffix) {
return None;
}
text[..digits].replace('_', "").parse().ok()
usize::from_str_radix(&number, radix).ok()
}
/// `const NAME: T = <integer literal>;` in a masked file. A name declared more than once with
@@ -3605,9 +3807,9 @@ fn ignore_hits(file: &File) -> Vec<Hit> {
let m = &file.m;
let mut out = vec![];
for at in words(m, b"ignore", 0, m.len()) {
if !m[..at].ends_with(b"#[") {
continue;
}
// `#[ignore`, with whitespace allowed between the tokens.
let Some(bracket) = m[..at].trim_ascii_end().len().checked_sub(1).filter(|&b| m[b] == b'[') else { continue };
let Some(hash) = m[..bracket].trim_ascii_end().len().checked_sub(1).filter(|&h| m[h] == b'#') else { continue };
let j = skip_ws(m, at + "ignore".len());
let reason = match m.get(j) {
Some(b'=') => {
@@ -3619,8 +3821,8 @@ fn ignore_hits(file: &File) -> Vec<Hit> {
if !reason {
let test = file.tests.iter().find(|t| t.fn_at > at).map_or("", |t| t.name.as_str());
// The hit sits on `#[ignore`; its span reaches the attribute's `]`, past a reason on a later line.
let mut hit = file.hit(at - 2, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into());
hit.last = matching(m, at - 1).map_or(hit.line, |close| file.lines.of(close));
let mut hit = file.hit(hash, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into());
hit.last = matching(m, bracket).map_or(hit.line, |close| file.lines.of(close));
out.push(hit);
}
}
@@ -4123,7 +4325,6 @@ fn closure_binding(body: &[u8], name: &str, before: usize) -> Option<usize> {
i = if opens { close + 1 } else { i + 1 };
continue;
}
let params = &body[i + 1..close];
let from = skip_ws(body, close + 1);
let end = match body.get(from) {
Some(b'{') => matching(body, from),
@@ -4155,7 +4356,9 @@ fn closure_binding(body: &[u8], name: &str, before: usize) -> Option<usize> {
end
}
};
if !words(params, name.as_bytes(), 0, params.len()).is_empty() && from <= before && end.is_some_and(|end| before < end) {
// A parameter's type (`|_: helper|`) binds nothing.
let binds = split_args(body, i + 1, close).into_iter().any(|(f, t)| pattern_binds(body, name.as_bytes(), f, t));
if binds && from <= before && end.is_some_and(|end| before < end) {
found = Some(i);
}
i = close + 1;
@@ -4163,16 +4366,24 @@ fn closure_binding(body: &[u8], name: &str, before: usize) -> Option<usize> {
found
}
/// The offset of the `=>` of the innermost match arm whose pattern binds `name` and whose body
/// holds `before`: `Some(n) => assert_eq!(n, 1)` binds `n`, `None => …` does not.
/// The offset of the guard, or of the `=>` when there is none, of the innermost match arm whose
/// pattern binds `name` and whose guard or body holds `before`: `Some(n) => assert_eq!(n, 1)` binds
/// `n`, `None => …` does not.
fn arm_binding(body: &[u8], name: &str, before: usize) -> Option<usize> {
let mut found = None;
for arrow in (0..before.min(body.len().saturating_sub(1))).filter(|&i| &body[i..i + 2] == b"=>") {
// The pattern runs back to the `{` or `,` that opens the arm.
for arrow in (0..body.len().saturating_sub(1)).filter(|&i| &body[i..i + 2] == b"=>") {
// The pattern runs back to the `{` or `,` that opens the arm, or to the `}` that ends the
// block body of the arm before it, which needs no comma.
let mut depth = 0usize;
let mut start = arrow;
while start > 0 {
match body[start - 1] {
b'}' if depth == 0
&& enclosing_open(body, start - 1)
.is_some_and(|open| matching(body, open) == Some(start - 1) && body[..open].trim_ascii_end().ends_with(b"=>")) =>
{
break;
}
b')' | b']' | b'}' => depth += 1,
b'(' | b'[' | b'{' if depth == 0 => break,
b'(' | b'[' | b'{' => depth -= 1,
@@ -4183,8 +4394,17 @@ fn arm_binding(body: &[u8], name: &str, before: usize) -> Option<usize> {
}
// A guard (`Some(x) if x == n`) reads names; it does not bind them.
let guard = words(body, b"if", start, arrow).first().copied().unwrap_or(arrow);
if guard >= before {
continue;
}
let pattern = norm_words(&body[start..guard]);
if words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() {
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)) {
continue;
}
// The arm's body: a block, or an expression up to the `,` or brace that ends the arm.
@@ -4209,7 +4429,8 @@ fn arm_binding(body: &[u8], name: &str, before: usize) -> Option<usize> {
}
};
if end.is_some_and(|end| before < end) {
found = Some(arrow);
// The binding starts at the guard, so a `let` inside the guard or the body is later.
found = Some(guard);
}
}
found
@@ -8066,5 +8287,144 @@ mod tests {
assert_eq!(hits(diagnostic), []);
assert_eq!(hits(&diagnostic.replace(" eprintln!(\"{n:?}\");\n", "")), [(3, "no-assertion")], "an ignored test that prints nothing");
assert_eq!(hits(&diagnostic.replace("#[ignore = \"manual timing\"]\n", "")), [(2, "no-assertion")], "a test that runs and only prints");
assert_eq!(hits(&diagnostic.replace("#[ignore", "#[ ignore")), [], "whitespace after the attribute's bracket");
assert_eq!(
hits(&diagnostic.replace("#[ignore = \"manual timing\"]", "#[ ignore = \" \"]")),
[(2, "ignore-without-reason"), (3, "no-assertion")],
"a blank reason after whitespace"
);
assert_eq!(hits("#[test]\n# [ ignore ]\nfn t() {\n assert!(f());\n}\n"), [(2, "ignore-without-reason")], "no reason, with whitespace");
}
/// Two files that each define `near`: `own` asserts in it, the other does not.
fn near_files(own: &str) -> Ctx {
let other = "fn near(a: f64) -> bool { a < 1.0 }\n#[test]\nfn u() {\n assert!(near(f()));\n}\n";
let files = [("crates/x/tests/it/own.rs".to_owned(), own.to_owned()), ("crates/x/tests/it/other.rs".to_owned(), other.to_owned())];
Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }
}
#[test]
fn an_import_of_another_files_helper_is_not_a_call_with_a_path() {
let own = "use super::other::near as comparison;\nfn near(a: f64) { assert!(a < 1.0); }\n#[test]\nfn t() {\n near(f());\n}\n";
assert_eq!(hits_in("crates/x/tests/it/own.rs", own, &near_files(own)), []);
let called = own.replace(" near(f());", " other::near(f());");
assert_eq!(hits_in("crates/x/tests/it/own.rs", &called, &near_files(&called)), [(4, "no-assertion")], "a call with a path");
let raw = own.replace(" as comparison", " as r#near");
assert_eq!(hits_in("crates/x/tests/it/own.rs", &raw, &near_files(&raw)), [(4, "no-assertion")], "a raw alias that keeps the name");
let imported = own.replace(" as comparison", "");
assert_eq!(hits_in("crates/x/tests/it/own.rs", &imported, &near_files(&imported)), [(4, "no-assertion")], "an import that keeps the name");
}
#[test]
fn a_local_binding_shadows_a_called_helper() {
let own = "fn near(a: f64) { assert!(a < 1.0); }\n#[test]\nfn t() {\n let near = |_: f64| {};\n near(f());\n}\n";
assert_eq!(hits_in("crates/x/tests/it/own.rs", own, &near_files(own)), [(3, "no-assertion")]);
let after = own.replace(" let near = |_: f64| {};\n near(f());", " near(f());\n let near = |_: f64| {};\n near(f());");
assert_eq!(hits_in("crates/x/tests/it/own.rs", &after, &near_files(&after)), [], "a call before the binding");
let named = "fn check_result() { assert!(f()); }\n#[test]\nfn t() {\n let check = check_result;\n check();\n}\n";
assert_eq!(hits_in("crates/x/tests/it/own.rs", named, &near_files(named)), [], "a name that says it checks");
}
/// A test that passes the asserting `body` to `keeping`, and its helpers.
fn body_src() -> (&'static str, Ctx) {
let src = "fn keeping(test: fn()) {\n test();\n}\nfn body() {\n assert_eq!(f(), 1);\n}\n#[test]\nfn t() {\n keeping(body);\n}\n";
(src, Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), src.to_owned())]), ..Ctx::default() })
}
#[test]
fn a_helper_in_an_assertion_message_does_not_delegate() {
let (src, ctx) = body_src();
let message = src.replace(" keeping(body);", " assert!(parse(input).is_ok(), \"{}\", keeping(body));");
assert_eq!(hits_in("crates/x/src/tests.rs", &message, &ctx), [(8, "only-weak")], "the message runs only when the check fails");
let condition = src.replace(" keeping(body);", " assert!(parse(input).is_ok(), \"{}\", 1);\n keeping(body);");
assert_eq!(hits_in("crates/x/src/tests.rs", &condition, &ctx), [], "a call of its own");
}
#[test]
fn a_match_arm_binding_shadows_a_helper_in_its_guard() {
let (src, ctx) = body_src();
let guard = src.replace(" keeping(body);", " match Some(noop as fn()) { Some(body) if run_body(body) => (), _ => () }");
assert_eq!(hits_in("crates/x/src/tests.rs", &guard, &ctx), [(8, "no-assertion")]);
let after = guard.replace("_ => () }", "_ => () }\n keeping(body);");
assert_eq!(hits_in("crates/x/src/tests.rs", &after, &ctx), [], "the helper after the match");
let label = src.replace(" keeping(body);", " match row() { Row { body: _ } if run_body(body) => (), _ => () }");
assert_eq!(hits_in("crates/x/src/tests.rs", &label, &ctx), [], "a field label binds nothing");
let next_arm = src.replace(" keeping(body);", " match row() { Some(body) if ready() => {} _ if run_body(body) => (), _ => () }");
assert_eq!(hits_in("crates/x/src/tests.rs", &next_arm, &ctx), [], "a guard after a block arm without a comma");
}
#[test]
fn a_type_annotation_does_not_shadow_a_helper() {
let (src, ctx) = body_src();
let typed = format!("type body = fn();\n{}", src.replace(" keeping(body);", " let cb: body = || {};\n keeping(body);"));
assert_eq!(hits_in("crates/x/src/tests.rs", &typed, &ctx), []);
let bound = format!("type body = fn();\n{}", src.replace(" keeping(body);", " let body: body = || {};\n keeping(body);"));
assert_eq!(hits_in("crates/x/src/tests.rs", &bound, &ctx), [(9, "no-assertion")], "a binding with the same name as its type");
let closure = format!("type body = u8;\n{}", src.replace(" keeping(body);", " let visit = |_: body| keeping(body);\n visit(0);"));
assert_eq!(hits_in("crates/x/src/tests.rs", &closure, &ctx), [], "a closure parameter's type binds nothing");
}
#[test]
fn all_over_a_hexadecimal_literal_range_is_guarded() {
let hex = "#[test]\nfn t() {\n assert!((0x1u8..0x3u8).all(|x| x > 0));\n}\n";
assert_eq!(hits(hex), []);
assert_eq!(hits(&hex.replace("0x1u8..0x3u8", "0b11..0o3")), [(3, "all-unguarded")], "an empty range");
assert_eq!(hits(&hex.replace("0x1u8..0x3u8", "0b1..0o3")), [], "binary and octal bounds");
}
#[test]
fn a_pin_reads_the_same_literal_selector() {
let pinned = "#[test]\nfn t() {\n let got: Vec<u32> = 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(pinned), []);
let other = pinned.replace("items(\"active\").iter().all", "items(\"archived\").iter().all");
assert_eq!(hits(&other), [(5, "all-unguarded")], "another selector");
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");
}
#[test]
fn a_parameter_named_like_a_table_is_not_the_table() {
let src = "mod other {\n const TABLE: [u8; 2] = [1, 2];\n}\nfn rows(TABLE: &[u8]) -> Vec<u8> {\n TABLE.iter().copied().collect()\n}\n#[test]\nfn t() {\n assert!(rows(&[]).iter().all(|x| *x > 0));\n}\n";
assert_eq!(hits(src), [(9, "all-unguarded")]);
}
#[test]
fn a_pin_does_not_count_when_an_earlier_alias_shares_the_source() {
let rc = "#[test]\nfn t() {\n let r = Rc::new(RefCell::new(vec![1u8]));\n let got: Vec<_> = r.borrow().iter().copied().collect();\n assert_eq!(got, [1]);\n assert!(r.borrow().iter().all(|n| *n > 0));\n}\n";
assert_eq!(hits(rc), [], "an unchanged source");
let aliased = rc
.replace(" let got", " let alias = Rc::clone(&r);\n let got")
.replace(" assert!(r.borrow()", " alias.borrow_mut().clear();\n assert!(r.borrow()");
assert_eq!(hits(&aliased), [(8, "all-unguarded")], "an alias made before the snapshot");
let populated = rc.replace(" let got", " populate(&mut r);\n let got");
assert_eq!(hits(&populated), [], "a borrow that ends with its call");
let counted = rc.replace(" let got", " let _n = r.borrow().len();\n let got");
assert_eq!(hits(&counted), [], "a getter read before the snapshot");
let borrowed = rc
.replace(" let got", " let alias = &r;\n let got")
.replace(" assert!(r.borrow()", " alias.borrow_mut().clear();\n assert!(r.borrow()");
assert_eq!(hits(&borrowed), [(8, "all-unguarded")], "a borrow bound before the snapshot");
let dropped = rc.replace(" let got", " drop(Rc::clone(&r));\n let got");
assert_eq!(hits(&dropped), [], "a clone dropped before the snapshot");
let scoped = rc.replace(" let got", " {\n let alias = Rc::clone(&r);\n use_it(&alias);\n }\n let got");
assert_eq!(hits(&scoped), [], "an alias whose block ends before the snapshot");
let released = rc.replace(" let got", " let alias = Rc::clone(&r);\n drop(alias);\n let got");
assert_eq!(hits(&released), [], "an alias dropped before the snapshot");
let discarded = rc.replace(" let got", " let _ = Rc::clone(&r);\n let got");
assert_eq!(hits(&discarded), [], "a clone bound to `_`");
let typed = "#[test]\nfn t() {\n let got: Vec<[u8; \"x\".len()]> = r.items(\"active\").to_vec();\n assert_eq!(got, vec![[1]]);\n assert!(r.items(\"active\").iter().all(|j| j.ok));\n}\n";
assert_eq!(hits(typed), [], "a literal in the snapshot's type");
}
#[test]
fn a_field_label_in_a_pattern_does_not_shadow_a_helper() {
let own = "fn near(a: f64) { assert!(a < 1.0); }\n#[test]\nfn t() {\n let Row { near: _ } = row();\n near(f());\n}\n";
assert_eq!(hits_in("crates/x/tests/it/own.rs", own, &near_files(own)), []);
let path = own.replace("Row { near: _ }", "model::near");
let alone = Ctx { helpers: asserting_helpers(&[("crates/x/tests/it/own.rs".to_owned(), path.clone())]), ..Ctx::default() };
assert_eq!(hits_in("crates/x/tests/it/own.rs", &path, &alone), [], "a path segment binds nothing");
let bound = own.replace("Row { near: _ }", "Row { near }");
assert_eq!(hits_in("crates/x/tests/it/own.rs", &bound, &near_files(&bound)), [(3, "no-assertion")], "a field shorthand binds");
}
}