From 40cd9932ebae7faea379d4f8becab28016bfb5ff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 18:25:16 -0800 Subject: [PATCH] xtask: test-lint sleep rule checks the spawn call, std imports and counted loops MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A spawned sleep is exempt only when the closure is the direct argument of `spawn`, not of a call inside it such as `spawn(prepare(|| …))`. - A bare `spawn` or `sleep`, and a `thread::` path, count only where a `use` brings them in from `std::thread`; `crate::thread::spawn` and `std::thread::{self as worker}` do not. - A sleep hit inside a spawned closure spans through the end of the spawn statement, so an edit that adds `.join()` there counts as a change. The brace-less `spawn(|| thread::sleep(D))` form gets the same span. - A block operand after a spaced `<` or `>` stays in the loop condition. - `while n < bound` with `n = n + 1` or `n = n - 1` in the body is a counted loop, like `n += 1`. - Calls inside the arguments of `println!`, `eprintln!` and the log macros are not polling work. --- xtask/src/test_lint.rs | 135 ++++++++++++++++++++++++++++++++--------- 1 file changed, 107 insertions(+), 28 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 3068e0ce83..69f3f50744 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2993,10 +2993,15 @@ fn sleep_hits(file: &File) -> Vec { .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) { + if let Some((name, _)) = expression_closure_call(m, at).filter(|&(name, end)| &m[name..end] == b"spawn") { + let end = spawn_statement_end(m, name).unwrap_or(m.len().saturating_sub(1)); + hit.also.push((hit.path.clone(), file.lines.of(name), file.lines.of(end))); + } else 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)); + // A spawn's span runs through the statement, which holds the use of its handle. + let close = closure_spawn(m, start, open).and_then(|s| spawn_statement_end(m, s)).map_or(close, |end| end.max(close)); hit.also.push((hit.path.clone(), file.lines.of(head_at), file.lines.of(close))); } } @@ -3005,8 +3010,9 @@ fn sleep_hits(file: &File) -> Vec { .collect() } -/// 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. +/// Whether a `use` brings in `std::thread::` under its own name, alone or in a `thread::{…}` +/// list. An alias (`thread::spawn as spawn_thread`) brings in another name, and `crate::thread` +/// is not the standard library's module. fn thread_import(m: &[u8], name: &str) -> bool { let path = format!("thread::{name}"); let alias = format!("as{name}"); @@ -3018,25 +3024,35 @@ fn thread_import(m: &[u8], name: &str) -> bool { 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()) + item.match_indices(&path).any(|(i, _)| named(i) && under_std(&item[..i])) + || item.match_indices("thread::{").any(|(i, _)| { + let list = &item[i + "thread::{".len()..]; + let list = &list[..list.find('}').unwrap_or(list.len())]; + under_std(&item[..i]) && !words(list.as_bytes(), name.as_bytes(), 0, list.len()).is_empty() + }) }) } +/// Whether a member of a `use` item whose normalized text before the member is `pre` sits directly +/// under `std`: right after `use std::`, or a top-level member of a `use std::{…}` list. +fn under_std(pre: &str) -> bool { + let pre = pre.strip_prefix("use").unwrap_or(pre); + let pre = pre.strip_prefix("::").unwrap_or(pre); + let Some(rest) = pre.strip_prefix("std::") else { return false }; + rest.is_empty() || (rest.starts_with('{') && rest.ends_with(['{', ',']) && rest.matches('{').count() == 1 + rest.matches('}').count()) +} + /// 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)]); - 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")) + words(item.as_bytes(), b"thread", 0, item.len()).into_iter().any(|i| { + let after = &item[i + "thread".len()..]; + // `{self as worker}` binds another name. + let self_member = + after.strip_prefix("::{").is_some_and(|list| list[..list.find('}').unwrap_or(list.len())].split(',').any(|x| x == "self")); + under_std(&item[..i]) && (after.is_empty() || after.starts_with([';', ',', '}']) || self_member) }) }) } @@ -3045,6 +3061,10 @@ fn std_thread_import(m: &[u8]) -> bool { /// `elapsed().checked_sub(D).unwrap()`. const PASS_THROUGH_CALLS: &[&str] = &["unwrap", "expect", "unwrap_or", "unwrap_or_default", "unwrap_or_else"]; +/// Macros that print or log their arguments, such as the `println!("{}", t0.elapsed())` of a +/// wait on the clock. +const LOG_MACROS: &[&str] = &["print!", "println!", "eprint!", "eprintln!", "trace!", "debug!", "info!", "warn!", "error!", "log!"]; + /// Calls that only read or build a time, which a wait on the clock alone makes. const TIME_CALLS: &[&str] = &[ "sleep", @@ -3142,7 +3162,11 @@ fn condition_block(before: &[u8]) -> bool { 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"=") + // A comparison or shift has a space before `<` or `>` (`0 < { … }`); a generic (`Option {`), + // `->` and `=>` do not. + let angles = before.iter().rev().take_while(|&&c| c == b'<' || c == b'>').count(); + let compares = (1..=2).contains(&angles) && before.len().checked_sub(angles + 1).is_some_and(|j| before[j].is_ascii_whitespace()); + keyword(b"while") || keyword(b"if") || keyword(b"match") || before.ends_with(b"&&") || or || not || compares || before.ends_with(b"=") } /// `head` without a leading loop label (`'outer:`). @@ -3213,10 +3237,21 @@ fn counted_while(m: &[u8], head: &[u8], open: usize, close: usize) -> bool { } 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"!="); + let name = &cond[..n]; compares - && words(m, &cond[..n], open, close).into_iter().any(|w| { + && words(m, name, open, close).into_iter().any(|w| { let after = skip_ws(m, w + n); - matches!(m.get(after..after + 2), Some(b"+=" | b"-=")) + if matches!(m.get(after..after + 2), Some(b"+=" | b"-=")) { + return true; + } + // `n = n + 1` or `n = n - 1`. + if m.get(after) != Some(&b'=') || m.get(after + 1) == Some(&b'=') { + return false; + } + let value = skip_ws(m, after + 1); + m.get(value..value + n) == Some(name) + && !m.get(value + n).copied().is_some_and(is_ident) + && matches!(m.get(skip_ws(m, value + n)), Some(b'+' | b'-')) }) } @@ -3224,10 +3259,11 @@ fn counted_while(m: &[u8], head: &[u8], open: usize, close: usize) -> bool { /// 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. +/// arguments of `stringify!`, of a [`LOG_MACROS`] macro or of the sleep itself, a nested `fn` name +/// and `Duration::new` do not count. A closure passed directly 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`, `n -= 1`, `n = n + 1` or `n = 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); @@ -3235,10 +3271,7 @@ fn polls_or_releases(m: &[u8], at: usize, imports: Imports) -> bool { 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, imports)); + return closure_spawn(m, start, open).is_some_and(|s| dropped_spawn(m, s, imports)); } // A sleep inside another block, such as a `let` initializer, in the loop is reported. if through_other { @@ -3247,10 +3280,10 @@ fn polls_or_releases(m: &[u8], at: usize, imports: Imports) -> bool { let close = matching(m, open).unwrap_or(m.len()); 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. + // The arguments of `stringify!`, of a logging macro and of a sleep are not polling work. let skipped: Vec<(usize, usize)> = found .iter() - .filter(|(_, name, _)| name == "stringify!" || name == "sleep") + .filter(|(_, name, _)| name == "stringify!" || name == "sleep" || LOG_MACROS.contains(&name.as_str())) .filter_map(|(p, name, _)| { let o = skip_ws(m, p + name.len()); matching(m, o).map(|c| (o, c)) @@ -3279,6 +3312,32 @@ fn polls_or_releases(m: &[u8], at: usize, imports: Imports) -> bool { }) } +/// The start of the name of the `spawn(…)` call that takes the closure whose head is `m[start..open]` +/// as its argument directly (`spawn(|| {`, `spawn(move || {`), not through another call such as +/// `spawn(prepare(|| {`. +fn closure_spawn(m: &[u8], start: usize, open: usize) -> Option { + let head = &m[start..open]; + words(head, b"spawn", 0, head.len()).into_iter().rev().find_map(|s| { + let paren = skip_ws(head, s + "spawn".len()); + if head.get(paren) != Some(&b'(') { + return None; + } + let arg = head[paren + 1..].trim_ascii_start(); + let arg = match arg.strip_prefix(b"move") { + Some(rest) if !rest.first().copied().is_some_and(is_ident) => rest.trim_ascii_start(), + _ => arg, + }; + arg.starts_with(b"||").then_some(start + s) + }) +} + +/// The offset of the `;` that ends the statement holding the `spawn(…)` call whose name starts at +/// `at`, so an edit that keeps or joins the handle (`).join().unwrap();`) falls in the hit's span. +fn spawn_statement_end(m: &[u8], at: usize) -> Option { + let close = matching(m, skip_ws(m, at + "spawn".len()))?; + Some(statement_end(m, close + 1).min(m.len().saturating_sub(1))) +} + /// For a sleep that is the whole body of a closure without braces (`spawn(|| thread::sleep(D))`), /// the start and end of the name of the call that takes the closure. fn expression_closure_call(m: &[u8], at: usize) -> Option<(usize, usize)> { @@ -3317,7 +3376,7 @@ 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: `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 +/// `thread` to `std::thread`, or no path where a `use` brings in `std::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 { @@ -5587,6 +5646,8 @@ mod tests { "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", + "fn wait(q: &Q) {\n while 0 < { q.len() } {\n thread::sleep(D);\n }\n}\n", + "fn wait(q: &Q) {\n while 3 > { q.len() } {\n thread::sleep(D);\n }\n}\n", ]; for src in polls { assert_eq!(hits(src), [], "{src}"); @@ -5618,6 +5679,11 @@ mod tests { "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", + "fn wait() {\n let attempts = [0, 1, 2];\n let mut n = 0;\n while n < attempts.len() {\n thread::sleep(D);\n n = n + 1;\n }\n}\n", + "#[test]\nfn t() {\n std::thread::spawn(prepare(|| {\n std::thread::sleep(D);\n }));\n assert_eq!(f(), 1);\n}\n", + "fn wait(t0: Instant) {\n while t0.elapsed() < D {\n println!(\"{}\", 1u8.to_string());\n thread::sleep(D);\n }\n}\n", + "use crate::thread::spawn;\n#[test]\nfn t() {\n spawn(|| {\n std::thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n", + "use std::thread::{self as worker};\nmod 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", ]; for src in timed { assert_eq!(hits(src).iter().filter(|h| h.1 == "sleep").count(), 1, "{src}"); @@ -5633,6 +5699,19 @@ mod tests { assert!(!touches(&found[0], Some(&[2].into_iter().collect())), "a change outside the loop"); } + #[test] + fn an_edit_that_joins_a_spawned_sleep_counts_as_a_change() { + let block = "#[test]\nfn t() {\n std::thread::spawn(move || {\n std::thread::sleep(D);\n })\n .join()\n .unwrap();\n assert_eq!(f(), 1);\n}\n"; + let bare = + "#[test]\nfn t() {\n std::thread::spawn(|| std::thread::sleep(D))\n .join()\n .unwrap();\n assert_eq!(f(), 1);\n}\n"; + for (src, line, join) in [(block, 4, 7), (bare, 3, 5)] { + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.iter().map(|h| (h.rule, h.line)).collect::>(), [(Rule::Sleep, line)], "{src}"); + assert!(touches(&found[0], Some(&[join].into_iter().collect())), "a change to the join: {src}"); + assert!(!touches(&found[0], Some(&[join + 1].into_iter().collect())), "a change after the statement: {src}"); + } + } + #[test] fn sleep_needs_the_thread_function() { let local = "fn sleep() -> u8 { 42 }\n#[test]\nfn t() {\n assert_eq!(sleep(), 42);\n}\n";