xtask: test-lint sleep rule reads labels, block conditions and closure return types

The poll check now:

- keeps a block condition (`while { r.load(SeqCst) } { ... }`) in the
  loop header, so the loop counts as a poll, while a `m! { ... }` macro
  before a loop still ends the statement before it;
- strips a loop label (`'outer: while ...`) before looking for the
  keyword;
- treats `move || -> () { ... }` as a spawned closure, like `move || {`;
- does not take `return ::std::thread::spawn(...);` as a dropped handle,
  since a keyword is not a path segment;
- does not count a nested `fn` item's name as a call in the loop.
This commit is contained in:
dotCooCoo committed 2026-12-01 15:13:59 -08:00
1 parent 8662e69da8
commit f5d227fe23
1 file changed
+93 -29
+93 -29
View File
@@ -3026,34 +3026,78 @@ fn enclosing_block(m: &[u8], at: usize) -> Option<(usize, usize)> {
_ => false,
})?;
// The statement that opens the block starts after the last `;`, `{` or `}` outside brackets, so
// a condition such as `json!({}) != 1` stays whole.
// a condition such as `json!({}) != 1` stays whole. A block in the condition (`while { … } {`)
// belongs to the statement too.
let mut nest = 0usize;
let start = (0..open)
.rev()
.find(|&j| match m[j] {
b')' | b']' => {
nest += 1;
false
}
b'}' if nest > 0 => {
nest += 1;
false
}
b'(' | b'[' => {
nest = nest.saturating_sub(1);
false
}
b'{' if nest > 0 => {
nest -= 1;
false
}
b';' | b'{' | b'}' => true,
_ => false,
})
.map_or(0, |j| j + 1);
let mut j = open;
let start = loop {
let Some(k) = j.checked_sub(1) else { break 0 };
j = k;
match m[j] {
b')' | b']' => nest += 1,
b'}' if nest > 0 => nest += 1,
b'(' | b'[' => nest = nest.saturating_sub(1),
b'{' if nest > 0 => nest -= 1,
b'}' => match opening_brace(m, j).filter(|&o| condition_block(&m[..o])) {
Some(o) => j = o,
None => break j + 1,
},
b';' | b'{' => break j + 1,
_ => {}
}
};
Some((open, start))
}
/// The `{` that the `}` at `close` closes.
fn opening_brace(m: &[u8], close: usize) -> Option<usize> {
let mut depth = 0usize;
(0..close).rev().find(|&j| match m[j] {
b'}' => {
depth += 1;
false
}
b'{' if depth == 0 => true,
b'{' => {
depth -= 1;
false
}
_ => false,
})
}
/// Whether a block whose `{` follows `before` is an operand in a condition: it follows `while`,
/// `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"=")
}
/// `head` without a leading loop label (`'outer:`).
fn strip_label(head: &[u8]) -> &[u8] {
if head.first() == Some(&b'\'') {
let n = 1 + head[1..].iter().take_while(|&&c| is_ident(c)).count();
if let Some(rest) = head[n..].trim_ascii_start().strip_prefix(b":") {
return rest.trim_ascii_start();
}
}
head
}
/// Whether `head` opens the body of a closure without parameters: `|| {`, or `|| -> T {` with a return type.
fn closure_head(head: &[u8]) -> bool {
head.ends_with(b"||") || head.windows(2).rposition(|w| w == b"||").is_some_and(|p| head[p + 2..].trim_ascii_start().starts_with(b"->"))
}
/// Keywords that cannot be a path segment before `spawn`, such as the `return` of `return ::std::thread::spawn(…);`.
const NOT_PATH: &[&[u8]] = &[
b"return", b"break", b"yield", b"let", b"else", b"in", b"as", b"move", b"match", b"if", b"while", b"loop", b"for", b"box", b"unsafe", b"async",
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`] (a flag's `load`, a `poll`, a
@@ -3065,8 +3109,10 @@ fn polls_or_releases(m: &[u8], at: usize) -> bool {
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);
if keyword(b"while") || keyword(b"loop") || head.ends_with(b"||") {
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) {
break (open, start);
}
if !head.is_empty() && !keyword(b"if") && !keyword(b"else") && !keyword(b"match") && !head.ends_with(b"=>") {
@@ -3075,7 +3121,7 @@ fn polls_or_releases(m: &[u8], at: usize) -> bool {
at = open;
};
let head = m[start..open].trim_ascii();
if head.ends_with(b"||") {
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.
@@ -3087,9 +3133,13 @@ fn polls_or_releases(m: &[u8], at: usize) -> bool {
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;
@@ -3107,9 +3157,17 @@ fn polls_or_releases(m: &[u8], at: usize) -> bool {
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")));
calls(m, start, close)
.iter()
.any(|(name, _)| !name.ends_with('!') && !TIME_CALLS.contains(&name.as_str()) && !(name == "new" && only_duration_new))
// 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);
}
}
found.iter().any(|(name, _)| !name.ends_with('!') && !TIME_CALLS.contains(&name.as_str()) && !(name == "new" && only_duration_new))
}
/// The contents of the last string literal in `s`, without its quotes.
@@ -5325,6 +5383,10 @@ mod tests {
"fn wait(t: &mut T) {\n while t.waiting() {\n thread::sleep(D);\n t.poll();\n }\n}\n",
"fn wait(s: &S) {\n while s.execute(\"a\", &json!({})).unwrap()[\"n\"] != 1 && Instant::now() < until {\n thread::sleep(D);\n }\n}\n",
"#[test]\nfn t() {\n std::thread::spawn(move || {\n std::thread::sleep(Duration::from_secs(10));\n gate.open();\n });\n assert_eq!(f(), 1);\n}\n",
"fn wait(r: &R) {\n while { r.load(SeqCst) } {\n thread::sleep(D);\n }\n}\n",
"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",
];
for src in polls {
assert_eq!(hits(src), [], "{src}");
@@ -5332,6 +5394,8 @@ mod tests {
let timed = [
"fn wait() {\n for _ in 0..3 {\n if ready() {\n thread::sleep(D);\n }\n }\n}\n",
"fn start() -> JoinHandle<()> {\n return std::thread::spawn(move || {\n std::thread::sleep(D);\n });\n}\n",
"fn start() -> JoinHandle<()> {\n return ::std::thread::spawn(move || {\n std::thread::sleep(D);\n });\n}\n",
"fn wait() {\n let t0 = Instant::now();\n while t0.elapsed() < D {\n fn unused() {}\n thread::sleep(D);\n }\n}\n",
"fn wait() {\n let t0 = Instant::now();\n while t0.elapsed() < Duration::from_millis(50) {\n thread::sleep(Duration::from_millis(5));\n }\n}\n",
"fn wait() {\n let t0 = Instant::now();\n while t0.elapsed().as_millis() < 50 {\n thread::sleep(D);\n }\n}\n",
"fn wait() {\n let t0 = Instant::now();\n while t0.elapsed() < Duration::new(1, 0) {\n thread::sleep(D);\n }\n}\n",