diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 7927f48eaa..50c4187406 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2261,15 +2261,15 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { ) .max_by_key(|&(since, _)| since) .map_or(to, |(_, until)| until); - // Assignments in move closures leave outer bindings unchanged. Assignments in async - // blocks that are not awaited, or in closures that nothing calls, do not run; - // conditional assignments do not make aliases. - if in_move_closure(b, from, to, at, &name) - || in_async_block(b, from, at, &name) - || !runs_with_assertion_within(b, from, to, at, &[], true) - { + // Assignments in async blocks that are not awaited, or in closures that nothing calls, + // do not run; conditional assignments do not make aliases. + if in_async_block(b, from, at) || !runs_with_assertion_within(b, from, to, at, &[], true) { continue; } + // Assignments to a capture in a move closure or an `async move` block change the + // block's own copy, so they end at the block and leave the outer binding unchanged. + let until = + move_closure_copy_end(b, from, to, at, &name).into_iter().chain(async_move_copy_end(b, from, at, &name)).fold(until, usize::min); if live(value_start(eq, end), end, &derived, &shadows) { if !runs_with_assertion(b, from, to, at) { continue; @@ -2564,26 +2564,30 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); // Where the `async` of an async block starts, with any whitespace before `move`. let async_kw = async_block_keyword(b, prefix_at, open).map(|(kw, _)| kw); + // A closure body, an async block or a nested `for` body can be left before the call + // (`block_on(async { if skip { return; } app.run(c); })`) while the loop's assertions still run. + let left_early = !may_run && (async_kw.is_some() || nested_for || closure_params_head(prefix)) && exits_before(b, open, start, nested_for); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { - if !runs_with_assertion_within(b, from, to, open, &active, may_run) { + if left_early || !runs_with_assertion_within(b, from, to, open, &active, may_run) { return false; } - } else if nested_for && !literal_source_yields(prefix).unwrap_or(may_run) { + } else if nested_for && (left_early || !literal_source_yields(prefix).unwrap_or(may_run)) { // A nested `for` body runs only when its source yields an item. return false; } else if let Some(kw) = async_kw { // An async block needs polling where it is written, by await or block_on. let polled = polled_in_place(b, from, kw, open); - if !polled || !runs_with_assertion_within(b, from, to, kw, &active, may_run) { + if !polled || left_early || !runs_with_assertion_within(b, from, to, kw, &active, may_run) { return false; } - } else if !may_run - && !prefix.ends_with(b"|") - && !nested_for - && (prefix.ends_with(b"=>") - || [b"if".as_slice(), b"else", b"match", b"while"].iter().any(|kw| !words(prefix, kw, 0, prefix.len()).is_empty()) - || (!words(prefix, b"loop", 0, prefix.len()).is_empty() - && matching(b, open).is_some_and(|close| !words(b, b"break", open + 1, close).is_empty()))) + } else if left_early + || (!may_run + && !prefix.ends_with(b"|") + && !nested_for + && (prefix.ends_with(b"=>") + || [b"if".as_slice(), b"else", b"match", b"while"].iter().any(|kw| !words(prefix, kw, 0, prefix.len()).is_empty()) + || (!words(prefix, b"loop", 0, prefix.len()).is_empty() + && matching(b, open).is_some_and(|close| !words(b, b"break", open + 1, close).is_empty())))) { // A nested `for` body whose source yields an item runs, like the loop body itself; // [`feeds_entry`] keeps its own bindings apart. @@ -2885,15 +2889,65 @@ fn required_conjunction(b: &[u8], mut f: usize, mut t: usize, at: usize, depth: b.get(open) == Some(&b'(') && matching(b, open) == close.checked_sub(1) && required_conjunction(b, open, close, at, depth + 1) } -/// Whether `start` lies in the body of an `async move` block, which writes to its own copies of the -/// captures, or of an `async` block that is not polled where it is written ([`polled_in_place`]). -/// A write to `name` that a `let` in the block before `start` declares is a write to the block's own -/// local, not to a capture. -fn in_async_block(b: &[u8], from: usize, start: usize, name: &str) -> bool { - (from..start).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)).any(|open| { - async_block_keyword(b, from, open) - .is_some_and(|(kw, moved)| (moved && !declared_in(b, open + 1, start, name)) || !polled_in_place(b, from, kw, open)) - }) +/// Whether `start` lies in the body of an `async` block that is not polled where it is written +/// ([`polled_in_place`]). +fn in_async_block(b: &[u8], from: usize, start: usize) -> bool { + (from..start) + .filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)) + .any(|open| async_block_keyword(b, from, open).is_some_and(|(kw, _)| !polled_in_place(b, from, kw, open))) +} + +/// The close of the innermost `async move` block around `start` that captures `name`: a write to +/// `name` there changes the block's own copy, which ends with the block. A write to `name` that a +/// `let` in the block before `start` declares is a write to the block's own local, not to a capture. +fn async_move_copy_end(b: &[u8], from: usize, start: usize, name: &str) -> Option { + (from..start) + .rev() + .filter(|&i| b[i] == b'{') + .filter_map(|open| matching(b, open).filter(|&close| start < close).map(|close| (open, close))) + .find(|&(open, _)| async_block_keyword(b, from, open).is_some_and(|(_, moved)| moved && !declared_in(b, open + 1, start, name))) + .map(|(_, close)| close) +} + +/// Whether `head`, the text of a statement before a `{`, ends with a closure's parameter list +/// (`let run = ||`, `move |c: Command|`), not with a logical OR (`ready ||`). +fn closure_params_head(head: &[u8]) -> bool { + // A return type follows the parameters (`|| -> bool`, `|c: Command| -> Result<(), E>`). + let head = match head.iter().rposition(|&c| c == b'|') { + Some(p) if head[p + 1..].trim_ascii_start().starts_with(b"->") => &head[..=p], + _ => head, + }; + let Some(rest) = head.strip_suffix(b"||") else { + return head.ends_with(b"|"); + }; + let rest = rest.trim_ascii_end(); + rest.is_empty() + || matches!(rest.last(), Some(b'=' | b'(' | b',' | b'{' | b';')) + || [b"move".as_slice(), b"async"].iter().any(|kw| rest.strip_suffix(*kw).is_some_and(|h| !h.last().copied().is_some_and(is_ident))) +} + +/// Whether the block opening at `open` can be left before `start`: a closure body or async block by +/// a `return` or a `?`, and a loop body (`loop_body`) by a `break` or a `continue` (a `return` or `?` +/// there leaves the test, and the assertions with it). An exit inside a nested closure or async +/// block leaves only that one, and a `break` or `continue` inside a nested loop leaves only that loop. +fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool) -> bool { + let nested = |at: usize, loops: bool| { + (open + 1..at).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| at < close)).any(|inner| { + let stmt = (open + 1..inner).rev().find(|&i| matches!(b[i], b';' | b'{' | b'}')).map_or(open + 1, |i| i + 1); + let head = b[stmt..inner].trim_ascii(); + closure_params_head(head) + || async_block_keyword(b, stmt, inner).is_some() + || (loops + && [b"for".as_slice(), b"while", b"loop"] + .iter() + .any(|kw| head.starts_with(kw) && !head.get(kw.len()).copied().is_some_and(is_ident))) + }) + }; + let returns = words(b, b"return", open + 1, start).into_iter().any(|at| !nested(at, false)); + let tries = (open + 2..start).any(|i| b[i] == b'?' && (is_ident(b[i - 1]) || matches!(b[i - 1], b')' | b']')) && !nested(i, false)); + let loops = + loop_body && [b"break".as_slice(), b"continue"].iter().any(|kw| words(b, kw, open + 1, start).into_iter().any(|at| !nested(at, true))); + if loop_body { loops } else { returns || tries } } /// Whether a `let` in `b[body..start]` whose scope reaches `start` binds `name`. @@ -2963,15 +3017,13 @@ fn polled_in_place(b: &[u8], from: usize, kw: usize, open: usize) -> bool { (b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident)) || passed_to_block_on(b, start, close + 1) } -/// 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'|') { - return false; - } - let Some(end) = (pipe + 1..to).find(|&i| b[i] == b'|') else { return false }; +/// Where the body of the innermost move closure around `start` that captures `name` ends: neither +/// the closure's parameters nor a `let` in its body before `start` binds `name`. A write to `name` +/// there changes the closure's own copy, which ends with the body. +fn move_closure_copy_end(b: &[u8], from: usize, to: usize, start: usize, name: &str) -> Option { + words(b, b"move", from, start).into_iter().rev().find_map(|at| { + let pipe = Some(skip_ws(b, at + 4)).filter(|&pipe| b.get(pipe) == Some(&b'|'))?; + let end = (pipe + 1..to).find(|&i| b[i] == b'|')?; let body = skip_ws(b, end + 1); let mut until = body; if b.get(body) == Some(&b'{') { @@ -2990,7 +3042,7 @@ fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize, name: &str) - .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 + (inside && !binds(&b[pipe + 1..end]) && !local).then_some(until) }) } @@ -10857,6 +10909,66 @@ mod tests { [], "a write to a local declared inside an async move block makes an alias" ); + assert_eq!( + census("block_on(async { if skip { return; } app.run(c); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a return before the call leaves a polled async block without running it" + ); + assert_eq!( + census("block_on(async { prepare()?; app.run(c); Ok(()) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a ? before the call can leave a polled async block" + ); + assert_eq!( + census("block_on(async { let _f = || { return; }; app.run(c); }); assert!(menu(c).is_some());"), + [], + "a return in a nested closure does not leave the polled async block" + ); + assert_eq!( + census("let run = || { if skip { return; } app.run(c); }; run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a return before the call leaves a called closure without running it" + ); + assert_eq!( + census("for _ in [1] { if skip { continue; } app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a continue before the call skips it in a nested for body" + ); + assert_eq!( + census("for _ in [1] { for _ in [2] { break; } app.run(c); } assert!(menu(c).is_some());"), + [], + "a break in an inner loop does not leave the nested for body" + ); + assert_eq!( + census("for _ in [1] { prepare()?; app.run(c); } assert!(menu(c).is_some());"), + [], + "a ? in a nested for body fails the test instead of skipping the call" + ); + assert_eq!( + census("block_on(async { let _ready = || -> bool { return true; }; app.run(c); }); assert!(menu(c).is_some());"), + [], + "a return in a nested closure with a return type does not leave the async block" + ); + assert_eq!( + census("let mut input = c; block_on(async move { input = fallback(); render(input, offset); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a write to a capture in an async move block replaces the entry inside the block" + ); + assert_eq!( + census("let mut input = c; let run = move || { input = fallback(); render(input, offset); }; run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a write to a capture in a move closure replaces the entry inside the closure" + ); + assert_eq!( + census("let input = c; block_on(async move { render(input, offset); }); assert!(menu(c).is_some());"), + [], + "an async move block that renders the captured entry feeds it" + ); + assert_eq!( + census("let mut input = c; block_on(async move { input = fallback(); }); render(input, offset); assert!(menu(c).is_some());"), + [], + "the outer binding keeps the entry after an async move block writes its copy" + ); assert_eq!( census( "let mut input = c; let mut reset = || { input = fallback(); }; false && { reset(); true }; app.run(input); assert!(menu(c).is_some());"