xtask: test-lint reads run blocks, command names and guarded views more exactly

- A deleted line that can change a test also marks the blank lines after
  it up to the next line of code, so a `return` that a deleted skip
  comment leaves after blank lines counts as changed.
- A literal `run: |` block is read as one script, so a `{ ... }` group
  that spans lines keeps its redirection to `$GITHUB_ENV`.
- An unquoted `NAME=value` word counts only before the command name or
  for a command that reads it as an assignment, so
  `grep NAME=value file` sets nothing.
- The print exemption reads the command name (`echo`, `printf`) instead
  of any earlier word, and a write to `$GITHUB_ENV` needs a redirection
  or a `tee`, `Out-File`, `Add-Content` or `Set-Content` that takes it as
  its output file. `echo "NAME=x" "$GITHUB_ENV"` only prints.
- A discarded tuple (`let _ = (|| (), { ... });`) is not unwrapped like
  grouping parentheses, so its evaluated elements still count.
- A size check guards only the `.all(...)` views over the same local,
  and inside one assertion only while nothing between the read and the
  `.all(...)` changes the local.
- An index no longer guards full chunks of the indexed item
  (`rows[1].as_chunks::<2>().0`): the chain walk follows turbofish
  arguments.
- Selector locals and indexed locals may have names with no ASCII
  letters (`选`, `数`).
- `all_needs_a_non_empty_guard` is split in two and the size-check tuple
  has a type alias, so clippy passes.
This commit is contained in:
dotCooCoo committed 2026-12-04 01:51:40 -08:00
1 parent 9c8f31344a
commit 53c7350eb4
1 file changed
+402 -59
+402 -59
View File
@@ -788,17 +788,41 @@ fn changed_lines(root: &Path, base: &str) -> Result<BTreeMap<String, Option<BTre
cache.entry(path.to_owned()).or_insert_with(|| read_git_blob_verbatim(root, base, path, MAX_FILE).map(|src| lines_affecting_tests(&src)));
lines.as_ref().is_none_or(|l| l.contains(&line))
};
let mut out = parse_diff(&diff, &can_change_test);
// The work tree is the new side of the diff. A file that cannot be read adds no blank lines.
let new_files: RefCell<HashMap<String, Option<String>>> = 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<String, Option<BTreeSet<usize>>> {
parse_diff_in(diff, can_change_test, &|_, line| line)
}
/// The first line of `src`, from 1-based `line` on, that is not blank, or `line` when none is.
fn next_code_line(src: &str, line: usize) -> usize {
src.lines().enumerate().skip(line.saturating_sub(1)).find(|(_, l)| !l.trim().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, unless it deletes only blank lines and line comments
/// ([`inert_deleted_line`]) that `can_change_test(path, old line)` places outside literals and tests.
fn parse_diff(diff: &str, can_change_test: &dyn Fn(&str, usize) -> bool) -> BTreeMap<String, Option<BTreeSet<usize>>> {
/// It also includes the blank lines after it up to `code_after(path, line)`, the next new-side line
/// with code, so a `return` that the deletion leaves after blank lines 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<String, Option<BTreeSet<usize>>> {
let mut out: BTreeMap<String, Option<BTreeSet<usize>>> = BTreeMap::new();
let mut current: Option<String> = None;
// Inside a file's header (from `diff --git` to its first hunk), where `+++ ` names the file.
@@ -808,8 +832,12 @@ fn parse_diff(diff: &str, can_change_test: &dyn Fn(&str, usize) -> bool) -> BTre
// the old line number of the next deleted line.
let mut deletion: Option<(usize, bool, usize)> = None;
let flush = |deletion: &mut Option<(usize, bool, usize)>, current: &Option<String>, out: &mut BTreeMap<String, Option<BTreeSet<usize>>>| {
if let (Some((start, true, _)), Some(Some(lines))) = (deletion.take(), current.as_ref().and_then(|p| out.get_mut(p))) {
lines.extend(start.max(1)..=start.saturating_add(1));
if let (Some((start, true, _)), Some(path)) = (deletion.take(), current.as_ref()) {
let next = start.saturating_add(1);
let end = next.max(code_after(path, next));
if let Some(Some(lines)) = out.get_mut(path) {
lines.extend(start.max(1)..=end);
}
}
};
for line in diff.lines() {
@@ -955,31 +983,141 @@ fn ci_env(root: &Path, files: &[String]) -> Result<HashSet<String>, String> {
Ok(names)
}
/// Workflow mapping keys and assignments with capitalized environment variable names.
/// Workflow mapping keys and assignments with capitalized environment variable names. A literal
/// `run: |` block is read as one script, so a `{ … }` group that spans lines keeps its redirection.
fn upper_words(text: &str) -> impl Iterator<Item = String> + '_ {
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 shell = workflow_scalar(start).unwrap_or_else(|| line.to_owned());
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 indent = line.len() - line.trim_start().len();
let start = code.trim_start().strip_prefix("- ").unwrap_or(code.trim_start()).trim_start();
let literal_block = start
.strip_prefix("run:")
.filter(|rest| rest.starts_with(char::is_whitespace))
.is_some_and(|rest| rest.trim().strip_prefix('|').is_some_and(|m| m.bytes().all(|c| matches!(c, b'-' | b'+') || c.is_ascii_digit())));
if !literal_block {
units.push((line.to_owned(), false));
continue;
}
let mut script = String::new();
while let Some(next) = lines.peek().filter(|l| l.trim().is_empty() || l.len() - l.trim_start().len() > indent) {
script.push_str(next.trim_start());
script.push('\n');
lines.next();
}
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(move |(at, _)| {
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 word_start = |p: usize| p == 0 || line.as_bytes().get(p - 1).is_some_and(|c| c.is_ascii_whitespace() || *c == b';');
// Inside quotes, only a quote that opens a whole word right before the name starts
// an assignment, not one inside a value (`m="NAME=x"`).
// A quoted word is an assignment only 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`).
// 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),
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).collect::<Vec<_>>()
mapping.into_iter().chain(assignments).collect::<Vec<_>>()
})
}
/// 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.
fn writes_env_file(command: &str) -> bool {
command.match_indices("GITHUB_ENV").any(|(at, _)| {
let before = command[..at].trim_end_matches(['"', '\'', '$', '{']);
let before = before.strip_suffix("env:").unwrap_or(before).trim_end_matches(['"', '\'', '$', '{']).trim_end();
if before.ends_with('>') {
return true;
}
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()))
})
}
@@ -1034,23 +1172,20 @@ fn workflow_scalar(line: &str) -> Option<String> {
Some(out)
}
/// Whether the text at `from` is an argument of `echo` or `printf` in its shell command, and that
/// command's pipeline does not write to `$GITHUB_ENV`.
/// 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 (start, end) = shell_command(line, from);
let command = &line.as_bytes()[start..from];
let prints = ["echo", "printf"].iter().any(|w| !words(command, w.as_bytes(), 0, command.len()).is_empty());
prints && !line[start..end].contains("GITHUB_ENV")
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 quoted word at `quote` reads it as an assignment: an
/// `export`, `env`, `declare`, `local`, `readonly` or `typeset` command, or a pipeline that writes
/// to `$GITHUB_ENV`.
fn assigned_by_command(line: &str, quote: usize) -> bool {
let (start, end) = shell_command(line, quote);
let head = &line.as_bytes()[start..quote];
["export", "env", "declare", "local", "readonly", "typeset"].iter().any(|w| !words(head, w.as_bytes(), 0, head.len()).is_empty())
|| line[start..end].contains("GITHUB_ENV")
/// 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
@@ -1995,9 +2130,11 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec<u8> {
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 => {
Some(close) if skip_ws(m, close + 1) == limit && !tuple_parts(&m[value + 1..close]) => {
limit = close;
value = skip_ws(m, value + 1);
}
@@ -2365,6 +2502,10 @@ 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<Hit> {
let mut body = v.body_without_messages();
strip_all_predicates(&mut body);
@@ -2373,7 +2514,8 @@ 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, bool)>)> = vec![];
// Each also keeps where the local is read, for a check in the assertion that holds `.all(…)`.
let mut direct: Vec<SizeCheck> = 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);
@@ -2396,10 +2538,10 @@ fn all_unguarded(v: &View) -> Vec<Hit> {
let kept = words(&body, receiver.as_bytes(), from, to)
.into_iter()
.filter(|&p| norm(&body[p..to]).starts_with(&read))
.any(|p| !may_shrink(&body[..to], receiver.as_bytes(), p + receiver.len()));
if plain && kept {
.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, count));
direct.push((receiver.to_owned(), to, read_at, count));
}
!plain
})
@@ -2418,21 +2560,51 @@ fn all_unguarded(v: &View) -> Vec<Hit> {
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_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
})
// The body offset of each byte of `cond`, which has no whitespace.
let offsets: Vec<usize> = 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| {
direct.iter().any(|(name, to, read_at, count)| {
let least = count.as_ref().and_then(|(c, strict)| sizes.count(c).map(|n| n + usize::from(*strict))).unwrap_or(1).max(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) };
!may_change(&body[..until], name.as_bytes(), from, false)
} 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 !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);
@@ -2449,6 +2621,45 @@ fn all_unguarded(v: &View) -> Vec<Hit> {
.collect()
}
/// 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 `==`, `<=`
@@ -3918,14 +4129,20 @@ fn first_item_guard(body: &[u8], sizes: &Sizes) -> bool {
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("].iter().any(|m| calls.starts_with(m))
&& calls.ends_with('.');
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)
});
indexed || unwrapped.iter().any(|g| compact.contains(g)) || panicking_first_binding(body)
@@ -4178,21 +4395,21 @@ fn selector_touched(body: &[u8], name: &str, from: usize) -> bool {
fn selector_locals(expr: &str) -> Vec<&str> {
let b = expr.as_bytes();
let mut out = vec![];
let mut at = b.iter().take_while(|&&c| is_ident(c)).count();
let mut at = b.iter().take_while(|&&c| name_byte(c)).count();
while at < b.len() {
if !is_ident(b[at]) {
if !name_byte(b[at]) {
at += 1;
continue;
}
let start = at;
while at < b.len() && is_ident(b[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 plain_local(word) && !named && !matches!(word, "true" | "false" | "as" | "mut") && !out.contains(&word) {
if local_name(word) && !named && !matches!(word, "true" | "false" | "as" | "mut") && !out.contains(&word) {
out.push(word);
}
}
@@ -4204,7 +4421,7 @@ fn selector_locals(expr: &str) -> Vec<&str> {
/// 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| {
@@ -4608,6 +4825,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);
@@ -4860,6 +5088,23 @@ fn repeat_count(contents: &[u8], sizes: &Sizes) -> Option<usize> {
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;
@@ -6681,7 +6926,8 @@ fn inert(op: &str, pos: usize, local: &LocalAt) -> Option<(bool, bool)> {
fn indexed_local(expr: &str) -> Option<&str> {
let expr = expr.trim_start_matches(['&', '*']);
let b = expr.as_bytes();
let n = b.iter().take_while(|&&c| is_ident(c)).count();
// 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;
@@ -6692,7 +6938,7 @@ fn indexed_local(expr: &str) -> Option<&str> {
}
at = matching(b, at)? + 1;
}
plain_local(&expr[..n]).then(|| &expr[..n])
local_name(&expr[..n]).then(|| &expr[..n])
}
/// Whether the operator at `at` can call an implementation on a user value. Comparisons, logical
@@ -8247,6 +8493,11 @@ 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");
}
#[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()");
@@ -12692,6 +12943,98 @@ mod tests {
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 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");
}
#[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::<Vec<_>>(), ["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 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 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<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";
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\""] {