Skip to content

Commit c485d79

Browse files
Fix capture analysis for by-move closure bodies
1 parent efd800d commit c485d79

File tree

2 files changed

+99
-0
lines changed

2 files changed

+99
-0
lines changed

tests/pass/async-closure-captures.rs

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
#![feature(async_closure, noop_waker)]
2+
3+
use std::future::Future;
4+
use std::pin::pin;
5+
use std::task::*;
6+
7+
pub fn block_on<T>(fut: impl Future<Output = T>) -> T {
8+
let mut fut = pin!(fut);
9+
let ctx = &mut Context::from_waker(Waker::noop());
10+
11+
loop {
12+
match fut.as_mut().poll(ctx) {
13+
Poll::Pending => {}
14+
Poll::Ready(t) => break t,
15+
}
16+
}
17+
}
18+
19+
fn main() {
20+
block_on(async_main());
21+
}
22+
23+
async fn call<T>(f: &impl async Fn() -> T) -> T {
24+
f().await
25+
}
26+
27+
async fn call_once<T>(f: impl async FnOnce() -> T) -> T {
28+
f().await
29+
}
30+
31+
#[derive(Debug)]
32+
#[allow(unused)]
33+
struct Hello(i32);
34+
35+
async fn async_main() {
36+
// Capture something by-ref
37+
{
38+
let x = Hello(0);
39+
let c = async || {
40+
println!("{x:?}");
41+
};
42+
call(&c).await;
43+
call_once(c).await;
44+
45+
let x = &Hello(1);
46+
let c = async || {
47+
println!("{x:?}");
48+
};
49+
call(&c).await;
50+
call_once(c).await;
51+
}
52+
53+
// Capture something and consume it (force to `AsyncFnOnce`)
54+
{
55+
let x = Hello(2);
56+
let c = async || {
57+
println!("{x:?}");
58+
drop(x);
59+
};
60+
call_once(c).await;
61+
}
62+
63+
// Capture something with `move`, don't consume it
64+
{
65+
let x = Hello(3);
66+
let c = async move || {
67+
println!("{x:?}");
68+
};
69+
call(&c).await;
70+
call_once(c).await;
71+
72+
let x = &Hello(4);
73+
let c = async move || {
74+
println!("{x:?}");
75+
};
76+
call(&c).await;
77+
call_once(c).await;
78+
}
79+
80+
// Capture something with `move`, also consume it (so `AsyncFnOnce`)
81+
{
82+
let x = Hello(5);
83+
let c = async move || {
84+
println!("{x:?}");
85+
drop(x);
86+
};
87+
call_once(c).await;
88+
}
89+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
Hello(0)
2+
Hello(0)
3+
Hello(1)
4+
Hello(1)
5+
Hello(2)
6+
Hello(3)
7+
Hello(3)
8+
Hello(4)
9+
Hello(4)
10+
Hello(5)

0 commit comments

Comments
 (0)