From 5594da577bfcfbc3aaff8e23b30ccac151d56e59 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:09:47 -0800 Subject: [PATCH] xtask: test-lint census rule ends tail assignments at their block and tells closure locals from captures An assignment that ends a block without a semicolon (`{ input = c }`) now makes its alias at the block's close instead of after the next statement. A `let` inside a move closure, or one of its parameters, now counts as a local binding: an assignment to it ends the alias as it does outside a closure. Assignments to outer captures are still skipped. A closure stored with `let` in `Some`, `Ok`, `Err`, `Box::new`, `Rc::new` or `Arc::new` and never used again does not run, so its assignments no longer end an alias. A closure passed to any other call may run and still ends it. An async closure called where it is written now runs when the call is passed straight to `block_on` (a trailing comma included), unless the `block_on` sits inside another closure. --- xtask/src/test_lint.rs | 122 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 111 insertions(+), 11 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 19c8bf3c8d..418cc75b1f 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1843,7 +1843,8 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { for (at, assigned) in steps { if let Some(eq) = assigned { let name = String::from_utf8_lossy(b[at..eq].trim_ascii_end()).into_owned(); - let end = statement_end(&b[..to], eq); + // A block's tail (`{ input = c }`) ends at the block's close. + let end = statement_end(&b[..to], eq).min(block_close(b, at)); let until = words(b, b"let", from, at) .into_iter() .filter(|&l| block_close(b, l) > at) @@ -1859,7 +1860,7 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { .map_or(to, |(_, until)| until); // Assignments in move closures leave outer bindings unchanged. Assignments in async // blocks or uncalled closures do not run; conditional assignments do not make aliases. - if in_move_closure(b, from, to, at) || in_async_block(b, from, at) || in_uncalled_closure(b, from, to, at, &[]) { + if in_move_closure(b, from, to, at, &name) || in_async_block(b, from, at) || in_uncalled_closure(b, from, to, at, &[]) { continue; } if live(value_start(eq, end), end, &derived, &shadows) { @@ -2297,7 +2298,19 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac if b.get(call) != Some(&b'(') { return false; } - if !asynchronous { + // An async closure's future runs when it is passed straight to `block_on` or awaited. A `|` + // before `block_on` may open a closure around it (`let _saved = || block_on(…);`) that + // never runs. + let outer = (stmt..open.saturating_sub(1)).rev().find(|&i| !b[i].is_ascii_whitespace()); + let blocked = matching(b, call).is_some_and(|call_close| { + outer.is_some_and(|o| { + b[o] == b'(' + && !b[stmt..o].contains(&b'|') + && b[..o].trim_ascii_end().strip_suffix(b"block_on").is_some_and(|h| !h.last().copied().is_some_and(is_ident)) + && matching(b, o).is_some_and(|c| matches!(b[call_close + 1..c].trim_ascii(), b"" | b",")) + }) + }); + if !asynchronous || blocked { return true; } let next = matching(b, call).map_or(b.len(), |c| skip_ws(b, c + 1)); @@ -2400,8 +2413,9 @@ fn in_async_block(b: &[u8], from: usize, start: usize) -> bool { }) } -/// Whether `start` lies in the block or expression body of a move closure. -fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize) -> bool { +/// Whether `start` lies in the block or expression body of a move closure that captures `name`: +/// neither the closure's parameters nor a `let` in its body before `start` binds `name`. +fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize, name: &str) -> bool { words(b, b"move", from, start).into_iter().any(|at| { let pipe = skip_ws(b, at + 4); if b.get(pipe) != Some(&b'|') { @@ -2417,12 +2431,22 @@ fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize) -> bool { until = if matches!(b[until], b'(' | b'[' | b'{') { matching(b, until).unwrap_or(to) + 1 } else { until + 1 }; } } - body <= start && start < until + let inside = body <= start && start < until; + let binds = |text: &[u8]| pattern_names(&String::from_utf8_lossy(text)).any(|n| n == name); + let local = inside + && words(b, b"let", body, start).into_iter().any(|l| { + block_close(b, l) > start + && (l + 3..start) + .find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) + .is_some_and(|eq| binds(&b[l + 3..eq])) + }); + inside && !binds(&b[pipe + 1..end]) && !local }) } /// Whether `start` lies in the block body of a closure bound with `let` in `b[from..to]` -/// (`let run = || { … };`, also `move` or `async`) with no call that [`closure_calls`] finds. +/// (`let run = || { … };`, also `move` or `async`) with no call that [`closure_calls`] finds, or of +/// a closure that a `let` stores without a call ([`stored_closure`]). fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool { let mut depth = 0usize; for i in (from..start).rev() { @@ -2435,11 +2459,15 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & let Some(pipe) = params.iter().rposition(|&c| c == b'|') else { continue }; let text = String::from_utf8_lossy(params[..pipe].trim_ascii_end()); let (head, asynchronous) = strip_closure_keywords(&text); - let Some(binding) = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { continue }; - let Some(name) = pattern_names(binding).last() else { continue }; - let bound = words(b, b"let", from, from + pipe).last().copied().unwrap_or(from); let close = matching(b, i).unwrap_or(to); - if !closure_calls(b, &name, bound, close, to, asynchronous).into_iter().any(|at| runs_with_assertion_within(b, from, to, at, active)) + let binding = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b); + let stored = binding.is_none() && stored_closure(b, head, close, to); + let Some(name) = binding.and_then(|binding| pattern_names(binding).last()).or_else(|| stored.then(String::new)) else { continue }; + let bound = words(b, b"let", from, from + pipe).last().copied().unwrap_or(from); + if stored + || !closure_calls(b, &name, bound, close, to, asynchronous) + .into_iter() + .any(|at| runs_with_assertion_within(b, from, to, at, active)) { return true; } @@ -2450,6 +2478,28 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & false } +/// Whether the closure whose block body ends at `close`, with `head` the text before its +/// parameters, is the only argument of `Some`, `Ok`, `Err`, `Box::new`, `Rc::new` or `Arc::new` in +/// a `let` initializer (`let _saved = Some(|| { … });`) whose names `b[..to]` never uses again, so +/// nothing can call it. A closure passed to any other call, a drop guard's included, may run there. +fn stored_closure(b: &[u8], head: &str, close: usize, to: usize) -> bool { + let Some(callee_end) = head.strip_suffix('(').map(str::trim_end) else { return false }; + let path_len = callee_end.bytes().rev().take_while(|&c| is_ident(c) || c == b':').count(); + let (rest, path) = callee_end.split_at(callee_end.len() - path_len); + let mut segments = path.rsplit("::"); + let last = segments.next().unwrap_or_default(); + let owner = segments.next().unwrap_or_default(); + let constructor = matches!(last, "Some" | "Ok" | "Err") || (last == "new" && matches!(owner, "Box" | "Rc" | "Arc")); + let Some(binding) = rest.trim_end().strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { return false }; + let paren = skip_ws(b, close + 1); + let semi = skip_ws(b, paren + 1); + constructor + && binding.starts_with(char::is_whitespace) + && b.get(paren) == Some(&b')') + && b.get(semi) == Some(&b';') + && pattern_names(binding).all(|n| words(b, n.as_bytes(), semi, to).is_empty()) +} + /// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and /// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while /// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions @@ -9254,6 +9304,36 @@ mod tests { [], "an assignment to a move capture leaves the outer alias unchanged" ); + assert_eq!( + census("let mut input = fallback(); { input = c } app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment that ends a block without a semicolon makes an alias there" + ); + assert_eq!( + census("let mut input = fallback(); { input = c; } app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment that ends with a semicolon in a block makes an alias" + ); + assert_eq!( + census("let run = move || { let mut input = c; input = fallback(); app.run(input); }; run(); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment to a binding declared in a move closure ends its alias" + ); + assert_eq!( + census("let mut input = c; let _saved = Some(|| { input = fallback(); }); app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in a closure stored in a call argument does not end an alias" + ); + assert_eq!( + census("let mut input = c; let _ = Some(input).map(|_| { input = fallback(); }); app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment in a closure passed to a call that may run it ends an alias" + ); + assert_eq!( + census("let mut input = c; { let _guard = RunOnDrop(|| { input = fallback(); }); } app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment in a closure kept by another type, which may run it, ends an alias" + ); } #[test] @@ -9316,6 +9396,26 @@ mod tests { "an async closure called where it is written only makes a future" ); assert_eq!(census("assert!((async || app.run(c))().await.is_ok());"), [], "an awaited async closure called where it is written runs"); + assert_eq!( + census("let _ = block_on((async || app.run(c))()); assert!(menu(c).is_some());"), + [], + "an async closure called where it is written and passed to block_on runs" + ); + assert_eq!( + census("let _ = block_on((async || app.run(c))(),); assert!(menu(c).is_some());"), + [], + "a trailing comma after the future passed to block_on" + ); + assert_eq!( + census("let _ = wrap((async || app.run(c))()); assert!(menu(c).is_some());"), + [(2, "census")], + "an async closure called where it is written and passed to another call does not run" + ); + assert_eq!( + census("let _saved = || block_on((async || app.run(c))()); assert!(menu(c).is_some());"), + [(2, "census")], + "block_on in an uncalled closure does not run the async closure" + ); assert_eq!( census("let _saved = Some(|| { app.run(c) }); assert!(menu(c).is_some());"), [(2, "census")],