Skip to content

Commit 0c158f0

Browse files
committed
Add a test case for #[track_caller] on async fn
1 parent 43c22af commit 0c158f0

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// run-pass
2+
// edition:2021
3+
4+
use std::future::Future;
5+
use std::panic;
6+
use std::sync::{Arc, Mutex};
7+
use std::task::{Context, Poll, Wake};
8+
use std::thread::{self, Thread};
9+
10+
/// A waker that wakes up the current thread when called.
11+
struct ThreadWaker(Thread);
12+
13+
impl Wake for ThreadWaker {
14+
fn wake(self: Arc<Self>) {
15+
self.0.unpark();
16+
}
17+
}
18+
19+
/// Run a future to completion on the current thread.
20+
fn block_on<T>(fut: impl Future<Output = T>) -> T {
21+
// Pin the future so it can be polled.
22+
let mut fut = Box::pin(fut);
23+
24+
// Create a new context to be passed to the future.
25+
let t = thread::current();
26+
let waker = Arc::new(ThreadWaker(t)).into();
27+
let mut cx = Context::from_waker(&waker);
28+
29+
// Run the future to completion.
30+
loop {
31+
match fut.as_mut().poll(&mut cx) {
32+
Poll::Ready(res) => return res,
33+
Poll::Pending => thread::park(),
34+
}
35+
}
36+
}
37+
38+
async fn bar() {
39+
panic!()
40+
}
41+
42+
async fn foo() {
43+
bar().await
44+
}
45+
46+
#[track_caller]
47+
async fn bar_track_caller() {
48+
panic!()
49+
}
50+
51+
async fn foo_track_caller() {
52+
bar_track_caller().await
53+
}
54+
55+
fn panicked_at(f: impl FnOnce() + panic::UnwindSafe) -> u32 {
56+
let loc = Arc::new(Mutex::new(None));
57+
58+
let hook = panic::take_hook();
59+
{
60+
let loc = loc.clone();
61+
panic::set_hook(Box::new(move |info| {
62+
*loc.lock().unwrap() = info.location().map(|loc| loc.line())
63+
}));
64+
}
65+
panic::catch_unwind(f).unwrap_err();
66+
panic::set_hook(hook);
67+
let x = loc.lock().unwrap().unwrap();
68+
x
69+
}
70+
71+
fn main() {
72+
assert_eq!(panicked_at(|| block_on(foo())), 39);
73+
assert_eq!(panicked_at(|| block_on(foo_track_caller())), 52);
74+
}

0 commit comments

Comments
 (0)