Skip to content

Commit b6097f2

Browse files
committed
Auto merge of #104219 - bryangarza:async-track-caller-dup, r=eholk
Support `#[track_caller]` on async fns Adds `#[track_caller]` to the generator that is created when we desugar the async fn. Fixes #78840 Open questions: - What is the performance impact of adding `#[track_caller]` to every `GenFuture`'s `poll(...)` function, even if it's unused (i.e., the parent span does not set `#[track_caller]`)? We might need to set it only conditionally, if the indirection causes overhead we don't want.
2 parents 36db030 + 79c06fc commit b6097f2

File tree

4 files changed

+109
-7
lines changed

4 files changed

+109
-7
lines changed

compiler/rustc_ast_lowering/src/expr.rs

+31-6
Original file line numberDiff line numberDiff line change
@@ -655,15 +655,40 @@ impl<'hir> LoweringContext<'_, 'hir> {
655655

656656
hir::ExprKind::Closure(c)
657657
};
658-
let generator = hir::Expr {
659-
hir_id: self.lower_node_id(closure_node_id),
660-
kind: generator_kind,
661-
span: self.lower_span(span),
658+
let parent_has_track_caller = self
659+
.attrs
660+
.values()
661+
.find(|attrs| attrs.into_iter().find(|attr| attr.has_name(sym::track_caller)).is_some())
662+
.is_some();
663+
let unstable_span =
664+
self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
665+
666+
let hir_id = if parent_has_track_caller {
667+
let generator_hir_id = self.lower_node_id(closure_node_id);
668+
self.lower_attrs(
669+
generator_hir_id,
670+
&[Attribute {
671+
kind: AttrKind::Normal(ptr::P(NormalAttr {
672+
item: AttrItem {
673+
path: Path::from_ident(Ident::new(sym::track_caller, span)),
674+
args: MacArgs::Empty,
675+
tokens: None,
676+
},
677+
tokens: None,
678+
})),
679+
id: self.tcx.sess.parse_sess.attr_id_generator.mk_attr_id(),
680+
style: AttrStyle::Outer,
681+
span: unstable_span,
682+
}],
683+
);
684+
generator_hir_id
685+
} else {
686+
self.lower_node_id(closure_node_id)
662687
};
663688

689+
let generator = hir::Expr { hir_id, kind: generator_kind, span: self.lower_span(span) };
690+
664691
// `future::from_generator`:
665-
let unstable_span =
666-
self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
667692
let gen_future = self.expr_lang_item_path(
668693
unstable_span,
669694
hir::LangItem::FromGenerator,

compiler/rustc_ast_lowering/src/item.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> {
8686
impl_trait_defs: Vec::new(),
8787
impl_trait_bounds: Vec::new(),
8888
allow_try_trait: Some([sym::try_trait_v2, sym::yeet_desugar_details][..].into()),
89-
allow_gen_future: Some([sym::gen_future][..].into()),
89+
allow_gen_future: Some([sym::gen_future, sym::closure_track_caller][..].into()),
9090
allow_into_future: Some([sym::into_future][..].into()),
9191
generics_def_id_map: Default::default(),
9292
};

library/core/src/future/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ where
8282

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

0 commit comments

Comments
 (0)