mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 04:25:52 -05:00
xtask: test-lint sleep rule checks thread spawns and real polling calls
- A dropped-handle spawn counts only as `thread::spawn` through a path, with or without a leading `::`, or as a bare `spawn` that a `use` brings in. A local `fn spawn` that runs the closure at once is reported. - A sleep that is the whole body of a closure without braces is judged by the call that takes the closure: a dropped `thread::spawn` is exempt, and a joined one is reported even inside a polling loop. - A `loop` used as a `let` value is checked for polling calls. - Calls inside the sleep's own argument and inside `stringify!` are not polling work, and neither are `unwrap`, `expect` and the `unwrap_or` family. - `Duration::new` is matched per call, with `Duration` as a whole path segment, so a local named `new` or `ScheduleDuration::new()` does not change the result.
This commit is contained in:
1 parent
249207671d
commit
f91fe5bf54
1 file changed
+151
-54
+151
-54
@@ -987,6 +987,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 index where each name starts.
|
||||
fn calls_at(m: &[u8], from: usize, to: usize) -> Vec<(usize, String, bool)> {
|
||||
let m = &m[..to];
|
||||
let mut out = vec![];
|
||||
let mut i = from;
|
||||
@@ -1003,7 +1008,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((i, if bang { format!("{name}!") } else { name }, method));
|
||||
}
|
||||
}
|
||||
i = end;
|
||||
@@ -2959,11 +2964,8 @@ fn ignore_reason(src: &[u8]) -> Option<&[u8]> {
|
||||
fn sleep_hits(file: &File) -> Vec<Hit> {
|
||||
let m = &file.m;
|
||||
// A bare `sleep(…)` counts only where a `use` brings in `thread::sleep`.
|
||||
let imported = words(m, b"use", 0, m.len()).into_iter().any(|u| {
|
||||
let item = norm(&m[u..statement_end(m, u)]);
|
||||
item.contains("thread::sleep")
|
||||
|| item.split_once("thread::{").is_some_and(|(_, list)| !words(list.as_bytes(), b"sleep", 0, list.len()).is_empty())
|
||||
});
|
||||
let imported = thread_import(m, "sleep");
|
||||
let spawn_imported = thread_import(m, "spawn");
|
||||
words(m, b"sleep", 0, m.len())
|
||||
.into_iter()
|
||||
.filter(|&at| {
|
||||
@@ -2976,12 +2978,26 @@ fn sleep_hits(file: &File) -> Vec<Hit> {
|
||||
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)
|
||||
thread_sleep && !polls_or_releases(m, at, spawn_imported)
|
||||
})
|
||||
.map(|at| file.hit(at, Rule::Sleep, file.test_at(at), "sleeps in test code".into()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a `use` brings in `thread::<name>`, alone or in a `thread::{…}` list.
|
||||
fn thread_import(m: &[u8], name: &str) -> bool {
|
||||
let path = format!("thread::{name}");
|
||||
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())
|
||||
})
|
||||
}
|
||||
|
||||
/// Calls that pass a value through without reading any state, such as the `unwrap` of
|
||||
/// `elapsed().checked_sub(D).unwrap()`.
|
||||
const PASS_THROUGH_CALLS: &[&str] = &["unwrap", "expect", "unwrap_or", "unwrap_or_default", "unwrap_or_else"];
|
||||
|
||||
/// Calls that only read or build a time, which a wait on the clock alone makes.
|
||||
const TIME_CALLS: &[&str] = &[
|
||||
"sleep",
|
||||
@@ -3100,19 +3116,25 @@ const NOT_PATH: &[&[u8]] = &[
|
||||
|
||||
/// 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`] (a flag's `load`, a `poll`, a
|
||||
/// progress read); a macro such as `println!` does not count. A
|
||||
/// closure passed to a `spawn` call whose handle is dropped runs beside the test, which does not
|
||||
/// wait for it.
|
||||
fn polls_or_releases(m: &[u8], at: usize) -> bool {
|
||||
/// 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);
|
||||
}
|
||||
let mut at = at;
|
||||
let (open, start) = loop {
|
||||
let Some((open, start)) = enclosing_block(m, at) else { return false };
|
||||
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);
|
||||
let loop_keyword = |w: &[u8]| labeled.starts_with(w) && !labeled.get(w.len()).copied().is_some_and(is_ident);
|
||||
if loop_keyword(b"while") || loop_keyword(b"loop") || closure_head(head) {
|
||||
let starts_while = labeled.starts_with(b"while") && !labeled.get(5).copied().is_some_and(is_ident);
|
||||
// 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);
|
||||
}
|
||||
if !head.is_empty() && !keyword(b"if") && !keyword(b"else") && !keyword(b"match") && !head.ends_with(b"=>") {
|
||||
@@ -3122,52 +3144,115 @@ fn polls_or_releases(m: &[u8], at: usize) -> bool {
|
||||
};
|
||||
let head = m[start..open].trim_ascii();
|
||||
if closure_head(head) {
|
||||
// The thread's handle is dropped only when the `spawn` call is the whole statement: a
|
||||
// path 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.
|
||||
let head_at = start + (m[start..open].len() - m[start..open].trim_ascii_start().len());
|
||||
let dropped = |s: usize| {
|
||||
let path = &head[..s];
|
||||
let mut i = 0;
|
||||
while i < path.len() {
|
||||
if !is_ident(path[i]) || path[i].is_ascii_digit() {
|
||||
return false;
|
||||
}
|
||||
let segment = i;
|
||||
while i < path.len() && is_ident(path[i]) {
|
||||
i += 1;
|
||||
}
|
||||
if NOT_PATH.contains(&&path[segment..i]) {
|
||||
return false;
|
||||
}
|
||||
i = skip_ws(path, i);
|
||||
if path.get(i..i + 2) != Some(&b"::"[..]) {
|
||||
return false;
|
||||
}
|
||||
i = skip_ws(path, i + 2);
|
||||
}
|
||||
let paren = skip_ws(m, head_at + s + "spawn".len());
|
||||
matching(m, paren).is_some_and(|close| m.get(skip_ws(m, close + 1)) == Some(&b';'))
|
||||
};
|
||||
return words(head, b"spawn", 0, head.len()).into_iter().any(|s| head.get(skip_ws(head, s + "spawn".len())) == Some(&b'(') && dropped(s));
|
||||
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));
|
||||
}
|
||||
let close = matching(m, open).unwrap_or(m.len());
|
||||
// `new` builds a time only as `Duration::new`; any other `new` call counts as a condition.
|
||||
let span = &m[start..close];
|
||||
let only_duration_new = words(span, b"new", 0, span.len())
|
||||
.into_iter()
|
||||
.all(|s| span[..s].trim_ascii_end().strip_suffix(b"::").is_some_and(|p| p.trim_ascii_end().ends_with(b"Duration")));
|
||||
let found = calls_at(m, start, close);
|
||||
// The arguments of `stringify!` and of a sleep are not polling work.
|
||||
let skipped: Vec<(usize, usize)> = found
|
||||
.iter()
|
||||
.filter(|(_, name, _)| name == "stringify!" || name == "sleep")
|
||||
.filter_map(|(p, name, _)| {
|
||||
let o = skip_ws(m, p + name.len());
|
||||
matching(m, o).map(|c| (o, c))
|
||||
})
|
||||
.collect();
|
||||
let before = |p: usize| m[..p].trim_ascii_end();
|
||||
// `new` builds a time only as `Duration::new`, with `Duration` as a whole path segment.
|
||||
let duration_new = |p: usize| {
|
||||
before(p)
|
||||
.strip_suffix(b"::")
|
||||
.map(<[u8]>::trim_ascii_end)
|
||||
.is_some_and(|q| q.ends_with(b"Duration") && !q.len().checked_sub(9).is_some_and(|j| is_ident(q[j])))
|
||||
};
|
||||
// A nested `fn` item's name is a declaration, not a call.
|
||||
let mut found = calls(m, start, close);
|
||||
for f in words(span, b"fn", 0, span.len()) {
|
||||
let s = skip_ws(span, f + "fn".len());
|
||||
let n = span[s..].iter().take_while(|&&c| is_ident(c)).count();
|
||||
let name = String::from_utf8_lossy(&span[s..s + n]);
|
||||
if let Some(p) = found.iter().position(|(called, method)| !method && *called == name) {
|
||||
found.remove(p);
|
||||
let declared = |p: usize| {
|
||||
let b = before(p);
|
||||
b.ends_with(b"fn") && !b.len().checked_sub(3).is_some_and(|j| is_ident(b[j]))
|
||||
};
|
||||
found.iter().any(|&(p, ref name, method)| {
|
||||
!name.ends_with('!')
|
||||
&& !TIME_CALLS.contains(&name.as_str())
|
||||
&& !PASS_THROUGH_CALLS.contains(&name.as_str())
|
||||
&& !skipped.iter().any(|&(o, c)| o < p && p < c)
|
||||
&& !(name == "new" && !method && duration_new(p))
|
||||
&& !(!method && declared(p))
|
||||
})
|
||||
}
|
||||
|
||||
/// 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)> {
|
||||
// The `(` of the call, or the `,` before the argument, that starts the argument holding `at`.
|
||||
let argument_start = |from: usize, comma: bool| {
|
||||
let mut depth = 0usize;
|
||||
let mut j = from;
|
||||
loop {
|
||||
j = j.checked_sub(1)?;
|
||||
match m[j] {
|
||||
b')' | b']' | b'}' => depth += 1,
|
||||
b'(' | b'[' | b'{' if depth > 0 => depth -= 1,
|
||||
b'(' if depth == 0 => return Some(j),
|
||||
b',' if depth == 0 && comma => return Some(j),
|
||||
b'[' | b'{' | b';' if depth == 0 => return None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
};
|
||||
let stop = argument_start(at, true)?;
|
||||
let arg = m[stop + 1..at].trim_ascii();
|
||||
let arg = match arg.strip_prefix(b"move") {
|
||||
Some(rest) if !rest.first().copied().is_some_and(is_ident) => rest.trim_ascii_start(),
|
||||
_ => arg,
|
||||
};
|
||||
let params = arg.strip_prefix(b"|")?;
|
||||
let body = ¶ms[params.iter().position(|&c| c == b'|')? + 1..];
|
||||
if !body.iter().all(|&c| is_ident(c) || c == b':' || c.is_ascii_whitespace()) {
|
||||
return None;
|
||||
}
|
||||
found.iter().any(|(name, _)| !name.ends_with('!') && !TIME_CALLS.contains(&name.as_str()) && !(name == "new" && only_duration_new))
|
||||
let paren = if m[stop] == b'(' { stop } else { argument_start(stop, false)? };
|
||||
let end = m[..paren].trim_ascii_end().len();
|
||||
let name = m[..end].iter().rposition(|&c| !is_ident(c)).map_or(0, |j| j + 1);
|
||||
(name < end).then_some((name, end))
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
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 i = 0;
|
||||
while i < path.len() {
|
||||
if !is_ident(path[i]) || path[i].is_ascii_digit() {
|
||||
return false;
|
||||
}
|
||||
let segment = i;
|
||||
while i < path.len() && is_ident(path[i]) {
|
||||
i += 1;
|
||||
}
|
||||
last = &path[segment..i];
|
||||
if NOT_PATH.contains(&last) {
|
||||
return false;
|
||||
}
|
||||
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" };
|
||||
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';'))
|
||||
}
|
||||
|
||||
/// The contents of the last string literal in `s`, without its quotes.
|
||||
@@ -5387,6 +5472,11 @@ mod tests {
|
||||
"fn wait(r: &R) {\n m! { r }\n while !r.load(SeqCst) {\n thread::sleep(D);\n }\n}\n",
|
||||
"fn wait(r: &R) {\n 'outer: while !r.load(SeqCst) {\n thread::sleep(D);\n }\n}\n",
|
||||
"#[test]\nfn t() {\n std::thread::spawn(move || -> () {\n std::thread::sleep(D);\n gate.open();\n });\n assert_eq!(f(), 1);\n}\n",
|
||||
"fn wait() -> P {\n let p = loop {\n let p = progress();\n if p.done {\n break p;\n }\n std::thread::sleep(D);\n };\n p\n}\n",
|
||||
"#[test]\nfn t() {\n ::std::thread::spawn(move || {\n std::thread::sleep(D);\n release();\n });\n assert_eq!(f(), 1);\n}\n",
|
||||
"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",
|
||||
];
|
||||
for src in polls {
|
||||
assert_eq!(hits(src), [], "{src}");
|
||||
@@ -5406,6 +5496,13 @@ mod tests {
|
||||
"#[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",
|
||||
"#[test]\nfn t() {\n handles.push(std::thread::spawn(move || {\n std::thread::sleep(D);\n }));\n assert_eq!(f(), 1);\n}\n",
|
||||
"#[test]\nfn t() {\n let release = std::thread::spawn(move || {\n std::thread::sleep(D);\n gate.open();\n });\n assert_eq!(f(), 1);\n release.join().unwrap();\n}\n",
|
||||
"fn spawn(f: impl FnOnce()) {\n f();\n}\n#[test]\nfn t() {\n spawn(|| {\n thread::sleep(D);\n });\n assert_eq!(f(), 1);\n}\n",
|
||||
"fn wait(t0: Instant) {\n while t0.elapsed() < Duration::new(1, 0) {\n let new = t0.elapsed();\n thread::sleep(D);\n }\n}\n",
|
||||
"fn wait() {\n let mut n = 0;\n while n < 3 {\n thread::sleep(delay());\n n += 1;\n }\n}\n",
|
||||
"fn wait(t0: Instant) {\n while t0.elapsed().checked_sub(Duration::ZERO).unwrap() < D {\n thread::sleep(D);\n }\n}\n",
|
||||
"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",
|
||||
];
|
||||
for src in timed {
|
||||
assert_eq!(hits(src).iter().filter(|h| h.1 == "sleep").count(), 1, "{src}");
|
||||
|
||||
Reference in new issue
Block a user