From 0c158f0e9d708e7705249bca8e38757ebf2e5c8c Mon Sep 17 00:00:00 2001 From: Eric Holk Date: Mon, 10 Oct 2022 16:00:46 -0700 Subject: [PATCH] Add a test case for #[track_caller] on async fn --- .../ui/async-await/panic-no-track-caller.rs | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/test/ui/async-await/panic-no-track-caller.rs diff --git a/src/test/ui/async-await/panic-no-track-caller.rs b/src/test/ui/async-await/panic-no-track-caller.rs new file mode 100644 index 00000000000..934764912d3 --- /dev/null +++ b/src/test/ui/async-await/panic-no-track-caller.rs @@ -0,0 +1,74 @@ +// run-pass +// edition:2021 + +use std::future::Future; +use std::panic; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll, Wake}; +use std::thread::{self, Thread}; + +/// A waker that wakes up the current thread when called. +struct ThreadWaker(Thread); + +impl Wake for ThreadWaker { + fn wake(self: Arc) { + self.0.unpark(); + } +} + +/// Run a future to completion on the current thread. +fn block_on(fut: impl Future) -> T { + // Pin the future so it can be polled. + let mut fut = Box::pin(fut); + + // Create a new context to be passed to the future. + let t = thread::current(); + let waker = Arc::new(ThreadWaker(t)).into(); + let mut cx = Context::from_waker(&waker); + + // Run the future to completion. + loop { + match fut.as_mut().poll(&mut cx) { + Poll::Ready(res) => return res, + Poll::Pending => thread::park(), + } + } +} + +async fn bar() { + panic!() +} + +async fn foo() { + bar().await +} + +#[track_caller] +async fn bar_track_caller() { + panic!() +} + +async fn foo_track_caller() { + bar_track_caller().await +} + +fn panicked_at(f: impl FnOnce() + panic::UnwindSafe) -> u32 { + let loc = Arc::new(Mutex::new(None)); + + let hook = panic::take_hook(); + { + let loc = loc.clone(); + panic::set_hook(Box::new(move |info| { + *loc.lock().unwrap() = info.location().map(|loc| loc.line()) + })); + } + panic::catch_unwind(f).unwrap_err(); + panic::set_hook(hook); + let x = loc.lock().unwrap().unwrap(); + x +} + +fn main() { + assert_eq!(panicked_at(|| block_on(foo())), 39); + assert_eq!(panicked_at(|| block_on(foo_track_caller())), 52); +}