From 8f66d6ce5041ef96fd99d55744104f181f8f91c5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 17:52:24 -0800 Subject: [PATCH] xtask: test-lint sleep rule reads counted loops, aliases and nested blocks - A `while n < bound` loop that adds to or subtracts from `n` in its body counts its own passes, so calls in the bound (`attempts.len()`) no longer exempt the sleep. A condition that also has `&&` or `||` keeps its calls as polling evidence. - A change to the loop or spawn closure around a reported sleep counts as a change to the hit, so an edit that removes the poll from the condition fails the changed-line check. - `use std::thread::spawn as spawn_thread;` and `use std::thread::sleep as nap;` no longer bring in the bare names, and `thread::sleep_ms` no longer matches `thread::sleep`. - A `thread::spawn` path counts only where a `use` binds `thread` to `std::thread`, so a local `mod thread` with its own `spawn` is not exempt. - A `;` inside a nested block in a loop condition (`while !ready({ let key = 1; key })`) no longer ends the header, and a block after `||` stays part of the condition. - A sleep in a `let` initializer block inside a dropped spawn closure is exempt like the closure's other sleeps; the same block inside a polling loop is still reported. --- xtask/src/test_lint.rs | 198 +++++++++++++++++++++++++++++++++-------- 1 file changed, 163 insertions(+), 35 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index c1a0682dad..3068e0ce83 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -244,7 +244,8 @@ pub struct Hit { pub first: usize, pub last: usize, /// Other lines whose change counts as a change to the hit, by file: the `cfg` attributes that - /// turn a `never-run` test off, on its module or on a `mod` declaration in another file. + /// turn a `never-run` test off, on its module or on a `mod` declaration in another file, and + /// the loop or spawn closure around a `sleep`. pub also: Vec<(String, usize, usize)>, } @@ -2961,11 +2962,20 @@ fn ignore_reason(src: &[u8]) -> Option<&[u8]> { src.get(body..end) } +/// What the file's `use` items bring in for a `thread::spawn` call. +#[derive(Clone, Copy)] +struct Imports { + /// `spawn` names `std::thread::spawn`. + spawn: bool, + /// `thread` names `std::thread`. + thread: bool, +} + fn sleep_hits(file: &File) -> Vec { let m = &file.m; // A bare `sleep(…)` counts only where a `use` brings in `thread::sleep`. let imported = thread_import(m, "sleep"); - let spawn_imported = thread_import(m, "spawn"); + let imports = Imports { spawn: thread_import(m, "spawn"), thread: std_thread_import(m) }; words(m, b"sleep", 0, m.len()) .into_iter() .filter(|&at| { @@ -2978,19 +2988,56 @@ fn sleep_hits(file: &File) -> Vec { Some(p) => p.ends_with(b"thread") && !p.ends_with(b"_thread"), None => imported && !before.ends_with(b".") && !before.ends_with(b"fn"), }; - thread_sleep && !polls_or_releases(m, at, spawn_imported) + thread_sleep && !polls_or_releases(m, at, imports) + }) + .map(|at| { + let mut hit = file.hit(at, Rule::Sleep, file.test_at(at), "sleeps in test code".into()); + // An edit to the loop or spawn around the sleep can remove what exempted it. + if let Some(WaitBlock { start, open, through_other }) = wait_block(m, at) { + let head_at = start + (m[start..open].len() - m[start..open].trim_ascii_start().len()); + if !through_other || closure_head(m[start..open].trim_ascii()) { + let close = matching(m, open).unwrap_or(m.len().saturating_sub(1)); + hit.also.push((hit.path.clone(), file.lines.of(head_at), file.lines.of(close))); + } + } + hit }) - .map(|at| file.hit(at, Rule::Sleep, file.test_at(at), "sleeps in test code".into())) .collect() } -/// Whether a `use` brings in `thread::`, alone or in a `thread::{…}` list. +/// Whether a `use` brings in `thread::` under its own name, alone or in a `thread::{…}` +/// list. An alias (`thread::spawn as spawn_thread`) brings in another name. fn thread_import(m: &[u8], name: &str) -> bool { let path = format!("thread::{name}"); + let alias = format!("as{name}"); + words(m, b"use", 0, m.len()).into_iter().any(|u| { + // `norm` drops spaces, so `spawn as s` reads `spawnass`. + let item = norm(&m[u..statement_end(m, u)]); + let named = |i: usize| { + let rest = &item[i + path.len()..]; + let rest = rest.strip_prefix(alias.as_str()).unwrap_or(rest); + !item.as_bytes()[..i].last().copied().is_some_and(is_ident) && !rest.bytes().next().is_some_and(is_ident) + }; + item.match_indices(&path).any(|(i, _)| named(i)) + || item.split_once("thread::{").is_some_and(|(_, list)| !words(list.as_bytes(), name.as_bytes(), 0, list.len()).is_empty()) + }) +} + +/// Whether a `use` binds the name `thread` to `std::thread`: `use std::thread;`, +/// `use std::{thread, …};` or `use std::thread::{self, …};`. +fn std_thread_import(m: &[u8]) -> bool { words(m, b"use", 0, m.len()).into_iter().any(|u| { let item = norm(&m[u..statement_end(m, u)]); - item.contains(&path) - || item.split_once("thread::{").is_some_and(|(_, list)| !words(list.as_bytes(), name.as_bytes(), 0, list.len()).is_empty()) + let item = item.strip_prefix("use").unwrap_or(&item); + let item = item.strip_prefix("::").unwrap_or(item); + let Some(rest) = item.strip_prefix("std::") else { return false }; + words(rest.as_bytes(), b"thread", 0, rest.len()).into_iter().any(|i| { + let before = rest.as_bytes()[..i].last().copied(); + let after = &rest[i + "thread".len()..]; + // Directly after `std::`, or a top-level member of a `std::{…}` list. + let top = i == 0 || (matches!(before, Some(b'{' | b',')) && rest[..i].matches('{').count() == 1 + rest[..i].matches('}').count()); + top && (after.is_empty() || after.starts_with([';', ',', '}']) || after.starts_with("::{self")) + }) }) } @@ -3058,7 +3105,8 @@ fn enclosing_block(m: &[u8], at: usize) -> Option<(usize, usize)> { Some(o) => j = o, None => break j + 1, }, - b';' | b'{' => break j + 1, + b';' if nest == 0 => break j + 1, + b'{' => break j + 1, _ => {} } }; @@ -3083,13 +3131,18 @@ fn opening_brace(m: &[u8], close: usize) -> Option { } /// Whether a block whose `{` follows `before` is an operand in a condition: it follows `while`, -/// `if`, `match`, `&&`, `!` or a comparison. +/// `if`, `match`, `&&`, `||`, `!` or a comparison. fn condition_block(before: &[u8]) -> bool { let before = before.trim_ascii_end(); let keyword = |w: &[u8]| before.ends_with(w) && !before.len().checked_sub(w.len() + 1).is_some_and(|j| is_ident(before[j])); // A `!` after a name is a macro's (`m! { … }`), not a negation. let not = before.strip_suffix(b"!").is_some_and(|b| !b.trim_ascii_end().last().copied().is_some_and(is_ident)); - keyword(b"while") || keyword(b"if") || keyword(b"match") || before.ends_with(b"&&") || not || before.ends_with(b"=") + // `||` after an operand is an `or`; after `(`, `,`, `=`, `move` or `return` it starts a closure. + let or = before.strip_suffix(b"||").map(<[u8]>::trim_ascii_end).is_some_and(|b| { + let ends_word = |w: &[u8]| b.ends_with(w) && !b.len().checked_sub(w.len() + 1).is_some_and(|j| is_ident(b[j])); + b.last().copied().is_some_and(|c| is_ident(c) || matches!(c, b')' | b']' | b'}' | b'?')) && !ends_word(b"move") && !ends_word(b"return") + }); + keyword(b"while") || keyword(b"if") || keyword(b"match") || before.ends_with(b"&&") || or || not || before.ends_with(b"=") } /// `head` without a leading loop label (`'outer:`). @@ -3114,20 +3167,22 @@ const NOT_PATH: &[&[u8]] = &[ b"await", b"const", b"static", b"mut", b"ref", b"dyn", b"impl", ]; -/// Whether the sleep at `at` is the pause of a loop that checks a condition, or the delay of a -/// spawned thread's fallback release. A `while` or `loop` around it polls when its condition or -/// body calls a function or method other than [`TIME_CALLS`] and [`PASS_THROUGH_CALLS`] (a -/// flag's `load`, a `poll`, a progress read). A macro such as `println!`, a call inside the -/// arguments of `stringify!` or of the sleep itself, a nested `fn` name and `Duration::new` do -/// not count. A closure passed to a `thread::spawn` call whose handle is dropped runs beside the -/// test, which does not wait for it. -fn polls_or_releases(m: &[u8], at: usize, spawn_imported: bool) -> bool { - if let Some((name, end)) = expression_closure_call(m, at) { - return &m[name..end] == b"spawn" && dropped_spawn(m, name, spawn_imported); - } +/// The block that decides whether the sleep at `at` waits: the nearest `while` or `loop`, or the +/// nearest closure without parameters, around it. +struct WaitBlock { + open: usize, + start: usize, + /// The walk passed a block other than an `if`, `else`, `match` or match arm, such as a `let` + /// initializer. Only a closure exempts the sleep then. + through_other: bool, +} + +/// The [`WaitBlock`] around `at`. The walk stops at a function. +fn wait_block(m: &[u8], at: usize) -> Option { let mut at = at; - let (open, start) = loop { - let Some((open, start)) = enclosing_block(m, at) else { return false }; + let mut through_other = false; + loop { + let (open, start) = enclosing_block(m, at)?; let head = m[start..open].trim_ascii(); let labeled = strip_label(head); let keyword = |w: &[u8]| head.starts_with(w) && !head.get(w.len()).copied().is_some_and(is_ident); @@ -3135,22 +3190,63 @@ fn polls_or_releases(m: &[u8], at: usize, spawn_imported: bool) -> bool { // A `loop` can be the value of a `let` (`let p = loop { … };`), so it ends the head. let ends_loop = labeled.ends_with(b"loop") && !labeled.len().checked_sub(5).is_some_and(|j| is_ident(labeled[j])); if starts_while || ends_loop || closure_head(head) { - break (open, start); + return Some(WaitBlock { open, start, through_other }); + } + if !words(head, b"fn", 0, head.len()).is_empty() { + return None; } if !head.is_empty() && !keyword(b"if") && !keyword(b"else") && !keyword(b"match") && !head.ends_with(b"=>") { - return false; + through_other = true; } at = open; - }; + } +} + +/// Whether the `while` loop with head `head` counts its own passes: its condition compares a name +/// with `<`, `<=`, `>`, `>=` or `!=` and nothing else, and its body adds to or subtracts from it. +fn counted_while(m: &[u8], head: &[u8], open: usize, close: usize) -> bool { + let Some(cond) = head.strip_prefix(b"while") else { return false }; + let cond = cond.trim_ascii_start(); + let n = cond.iter().take_while(|&&c| is_ident(c)).count(); + if n == 0 || cond[0].is_ascii_digit() || cond.windows(2).any(|w| w == b"&&" || w == b"||") { + return false; + } + let op = cond[n..].trim_ascii_start(); + let compares = (op.starts_with(b"<") && !op.starts_with(b"<<")) || (op.starts_with(b">") && !op.starts_with(b">>")) || op.starts_with(b"!="); + compares + && words(m, &cond[..n], open, close).into_iter().any(|w| { + let after = skip_ws(m, w + n); + matches!(m.get(after..after + 2), Some(b"+=" | b"-=")) + }) +} + +/// Whether the sleep at `at` is the pause of a loop that checks a condition, or the delay of a +/// spawned thread's fallback release. A `while` or `loop` around it polls when its condition or +/// body calls a function or method other than [`TIME_CALLS`] and [`PASS_THROUGH_CALLS`] (a +/// flag's `load`, a `poll`, a progress read). A macro such as `println!`, a call inside the +/// arguments of `stringify!` or of the sleep itself, a nested `fn` name and `Duration::new` do +/// not count. A closure passed to a `thread::spawn` call whose handle is dropped runs beside the +/// test, which does not wait for it. In `while n < bound` with `n += 1` or `n -= 1` in the body, +/// the loop counts its own passes, so only calls in the body count. +fn polls_or_releases(m: &[u8], at: usize, imports: Imports) -> bool { + if let Some((name, end)) = expression_closure_call(m, at) { + return &m[name..end] == b"spawn" && dropped_spawn(m, name, imports); + } + let Some(WaitBlock { open, start, through_other }) = wait_block(m, at) else { return false }; let head = m[start..open].trim_ascii(); if closure_head(head) { let head_at = start + (m[start..open].len() - m[start..open].trim_ascii_start().len()); return words(head, b"spawn", 0, head.len()) .into_iter() - .any(|s| head.get(skip_ws(head, s + "spawn".len())) == Some(&b'(') && dropped_spawn(m, head_at + s, spawn_imported)); + .any(|s| head.get(skip_ws(head, s + "spawn".len())) == Some(&b'(') && dropped_spawn(m, head_at + s, imports)); + } + // A sleep inside another block, such as a `let` initializer, in the loop is reported. + if through_other { + return false; } let close = matching(m, open).unwrap_or(m.len()); - let found = calls_at(m, start, close); + let from = if counted_while(m, strip_label(head), open, close) { open } else { start }; + let found = calls_at(m, from, close); // The arguments of `stringify!` and of a sleep are not polling work. let skipped: Vec<(usize, usize)> = found .iter() @@ -3220,17 +3316,18 @@ fn expression_closure_call(m: &[u8], at: usize) -> Option<(usize, usize)> { } /// Whether the `spawn(…)` call whose name starts at `at` starts a thread and drops its handle. -/// The call is the whole statement: a path ending in `thread::` (or none, where a `use` brings in -/// `thread::spawn`) before it and a `;` after it. A `let`, an assignment, an argument or a chained -/// `.join()` keeps the handle, and a test that joins it waits for the sleep. -fn dropped_spawn(m: &[u8], at: usize, spawn_imported: bool) -> bool { +/// The call is the whole statement: `std::thread::` before it (or `thread::` where a `use` binds +/// `thread` to `std::thread`, or no path where a `use` brings in `thread::spawn`) and a `;` after +/// it. A `let`, an assignment, an argument or a chained `.join()` keeps the handle, and a test +/// that joins it waits for the sleep. +fn dropped_spawn(m: &[u8], at: usize, imports: Imports) -> bool { let from = m[..at].iter().rposition(|&c| !(is_ident(c) || c == b':' || c.is_ascii_whitespace())).map_or(0, |j| j + 1); if !matches!(m[..from].last().copied(), None | Some(b';' | b'{' | b'}')) { return false; } let path = m[from..at].trim_ascii(); let path = path.strip_prefix(b"::").map_or(path, <[u8]>::trim_ascii_start); - let mut last: &[u8] = b""; + let mut segments: Vec<&[u8]> = vec![]; let mut i = 0; while i < path.len() { if !is_ident(path[i]) || path[i].is_ascii_digit() { @@ -3240,17 +3337,24 @@ fn dropped_spawn(m: &[u8], at: usize, spawn_imported: bool) -> bool { while i < path.len() && is_ident(path[i]) { i += 1; } - last = &path[segment..i]; + let last = &path[segment..i]; if NOT_PATH.contains(&last) { return false; } + segments.push(last); i = skip_ws(path, i); if path.get(i..i + 2) != Some(&b"::"[..]) { return false; } i = skip_ws(path, i + 2); } - let thread = if path.is_empty() { spawn_imported } else { last == b"thread" }; + // A `thread::` path names the standard library's module only where a `use` binds it. + let thread = match segments[..] { + [] => imports.spawn, + [b"thread"] => imports.thread, + [b"std", b"thread"] => true, + _ => false, + }; let paren = skip_ws(m, at + "spawn".len()); thread && matching(m, paren).is_some_and(|close| m.get(skip_ws(m, close + 1)) == Some(&b';')) } @@ -5477,6 +5581,12 @@ mod tests { "fn wait() {\n while ScheduleDuration::new().pending {\n thread::sleep(D);\n }\n}\n", "#[test]\nfn t() {\n std::thread::spawn(|| std::thread::sleep(D));\n assert_eq!(f(), 1);\n}\n", "use std::thread::{self, spawn};\n#[test]\nfn t() {\n spawn(|| {\n thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n", + "fn wait() {\n while !ready({ let key = 1; key }) {\n thread::sleep(D);\n }\n}\n", + "fn wait(pending: bool) {\n while pending || { ready() } {\n thread::sleep(D);\n }\n}\n", + "#[test]\nfn t() {\n std::thread::spawn(|| {\n let () = {\n std::thread::sleep(D);\n };\n });\n assert_eq!(f(), 1);\n}\n", + "use std::thread;\n#[test]\nfn t() {\n thread::spawn(|| {\n thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n", + "use std::{thread, time::Duration};\n#[test]\nfn t() {\n thread::spawn(|| {\n thread::sleep(Duration::ZERO);\n });\n assert_eq!(f(), 1);\n}\n", + "fn wait(q: &Q) {\n while q.len() < 3 {\n thread::sleep(D);\n }\n}\n", ]; for src in polls { assert_eq!(hits(src), [], "{src}"); @@ -5503,12 +5613,26 @@ mod tests { "fn wait(t0: Instant) {\n while t0.elapsed() < D {\n let _ = stringify!(probe());\n std::thread::sleep(D);\n }\n}\n", "#[test]\nfn t() {\n while !ready() {\n std::thread::spawn(|| std::thread::sleep(D)).join().unwrap();\n }\n assert_eq!(f(), 1);\n}\n", "fn wait() -> u8 {\n let mut n = 0;\n let r = loop {\n n += 1;\n if n == 3 {\n break n;\n }\n thread::sleep(D);\n };\n r\n}\n", + "fn wait() {\n let attempts = [0, 1, 2];\n let mut n = 0;\n while n < attempts.len() {\n thread::sleep(D);\n n += 1;\n }\n}\n", + "use std::thread::spawn as spawn_thread;\nfn spawn(f: impl FnOnce()) {\n f();\n}\n#[test]\nfn t() {\n spawn(|| {\n std::thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n", + "mod thread {\n pub fn spawn(f: impl FnOnce()) {\n f();\n }\n}\n#[test]\nfn t() {\n thread::spawn(|| {\n std::thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n", + "#[test]\nfn t() {\n let h = std::thread::spawn(|| {\n let () = {\n std::thread::sleep(D);\n };\n });\n h.join().unwrap();\n}\n", + "fn wait(r: &R) {\n while !r.load(SeqCst) {\n let x = {\n thread::sleep(D);\n 1\n };\n }\n}\n", ]; for src in timed { assert_eq!(hits(src).iter().filter(|h| h.1 == "sleep").count(), 1, "{src}"); } } + #[test] + fn an_edit_to_the_loop_around_a_sleep_counts_as_a_change() { + let src = "fn wait() {\n let mut n = 0;\n while n < 3 {\n thread::sleep(D);\n n += 1;\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.iter().map(|h| (h.rule, h.line)).collect::>(), [(Rule::Sleep, 4)]); + assert!(touches(&found[0], Some(&[3].into_iter().collect())), "a change to the loop's condition"); + assert!(!touches(&found[0], Some(&[2].into_iter().collect())), "a change outside the loop"); + } + #[test] fn sleep_needs_the_thread_function() { let local = "fn sleep() -> u8 { 42 }\n#[test]\nfn t() {\n assert_eq!(sleep(), 42);\n}\n"; @@ -5517,6 +5641,10 @@ mod tests { let src = format!("{import}\n#[test]\nfn t() {{\n sleep(D);\n assert_eq!(f(), 42);\n}}\n"); assert_eq!(hits(&src), [(4, "sleep")], "{import}"); } + for import in ["use std::thread::sleep as nap;", "use std::thread::sleep_ms;", "use std::thread::{sleep as nap};"] { + let src = format!("{import}\nfn sleep(_: u8) {{}}\n#[test]\nfn t() {{\n sleep(1);\n assert_eq!(f(), 42);\n}}\n"); + assert_eq!(hits(&src), [], "{import}"); + } assert_eq!(hits("#[test]\nfn t() {\n std :: thread :: sleep(D);\n assert_eq!(f(), 1);\n}\n"), [(3, "sleep")]); }