Skip to content

Commit 7907249

Browse files
committed
WIP: Remove ResumeTy from async lowering
Instead of using the stdlib supported `ResumeTy`, which is being converting to a `&mut Context<'_>` during the Generator MIR pass, this will use `&mut Context<'_>` directly in HIR lowering. It pretty much reverts #105977 and re-applies an updated version of #105250. This still fails the testcase added in #106264 however, for reasons I don’t understand.
1 parent aa7e9f2 commit 7907249

File tree

12 files changed

+72
-198
lines changed

12 files changed

+72
-198
lines changed

compiler/rustc_ast_lowering/src/expr.rs

+30-32
Original file line numberDiff line numberDiff line change
@@ -615,17 +615,28 @@ impl<'hir> LoweringContext<'_, 'hir> {
615615
// whereas a generator does not.
616616
let (inputs, params, task_context): (&[_], &[_], _) = match desugaring_kind {
617617
hir::CoroutineDesugaring::Async | hir::CoroutineDesugaring::AsyncGen => {
618-
// Resume argument type: `ResumeTy`
619-
let unstable_span = self.mark_span_with_reason(
620-
DesugaringKind::Async,
621-
self.lower_span(span),
622-
Some(self.allow_gen_future.clone()),
623-
);
624-
let resume_ty = self.make_lang_item_qpath(hir::LangItem::ResumeTy, unstable_span);
618+
// Resume argument type: `&mut Context<'_>`.
619+
let context_lifetime_ident = Ident::with_dummy_span(kw::UnderscoreLifetime);
620+
let context_lifetime = self.arena.alloc(hir::Lifetime {
621+
hir_id: self.next_id(),
622+
ident: context_lifetime_ident,
623+
res: hir::LifetimeName::Infer,
624+
});
625+
let context_path =
626+
hir::QPath::LangItem(hir::LangItem::Context, self.lower_span(span));
627+
let context_ty = hir::MutTy {
628+
ty: self.arena.alloc(hir::Ty {
629+
hir_id: self.next_id(),
630+
kind: hir::TyKind::Path(context_path),
631+
span: self.lower_span(span),
632+
}),
633+
mutbl: hir::Mutability::Mut,
634+
};
635+
625636
let input_ty = hir::Ty {
626637
hir_id: self.next_id(),
627-
kind: hir::TyKind::Path(resume_ty),
628-
span: unstable_span,
638+
kind: hir::TyKind::Ref(context_lifetime, context_ty),
639+
span: self.lower_span(span),
629640
};
630641
let inputs = arena_vec![self; input_ty];
631642

@@ -725,7 +736,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
725736
/// mut __awaitee => loop {
726737
/// match unsafe { ::std::future::Future::poll(
727738
/// <::std::pin::Pin>::new_unchecked(&mut __awaitee),
728-
/// ::std::future::get_context(task_context),
739+
/// task_context,
729740
/// ) } {
730741
/// ::std::task::Poll::Ready(result) => break result,
731742
/// ::std::task::Poll::Pending => {}
@@ -766,29 +777,21 @@ impl<'hir> LoweringContext<'_, 'hir> {
766777
FutureKind::AsyncIterator => Some(self.allow_for_await.clone()),
767778
};
768779
let span = self.mark_span_with_reason(DesugaringKind::Await, await_kw_span, features);
769-
let gen_future_span = self.mark_span_with_reason(
770-
DesugaringKind::Await,
771-
full_span,
772-
Some(self.allow_gen_future.clone()),
773-
);
774780
let expr_hir_id = expr.hir_id;
775781

776782
// Note that the name of this binding must not be changed to something else because
777783
// debuggers and debugger extensions expect it to be called `__awaitee`. They use
778784
// this name to identify what is being awaited by a suspended async functions.
779785
let awaitee_ident = Ident::with_dummy_span(sym::__awaitee);
780-
let (awaitee_pat, awaitee_pat_hid) = self.pat_ident_binding_mode(
781-
gen_future_span,
782-
awaitee_ident,
783-
hir::BindingAnnotation::MUT,
784-
);
786+
let (awaitee_pat, awaitee_pat_hid) =
787+
self.pat_ident_binding_mode(full_span, awaitee_ident, hir::BindingAnnotation::MUT);
785788

786789
let task_context_ident = Ident::with_dummy_span(sym::_task_context);
787790

788791
// unsafe {
789792
// ::std::future::Future::poll(
790793
// ::std::pin::Pin::new_unchecked(&mut __awaitee),
791-
// ::std::future::get_context(task_context),
794+
// task_context,
792795
// )
793796
// }
794797
let poll_expr = {
@@ -806,21 +809,16 @@ impl<'hir> LoweringContext<'_, 'hir> {
806809
hir::LangItem::PinNewUnchecked,
807810
arena_vec![self; ref_mut_awaitee],
808811
);
809-
let get_context = self.expr_call_lang_item_fn_mut(
810-
gen_future_span,
811-
hir::LangItem::GetContext,
812-
arena_vec![self; task_context],
813-
);
814812
let call = match await_kind {
815813
FutureKind::Future => self.expr_call_lang_item_fn(
816814
span,
817815
hir::LangItem::FuturePoll,
818-
arena_vec![self; new_unchecked, get_context],
816+
arena_vec![self; new_unchecked, task_context],
819817
),
820818
FutureKind::AsyncIterator => self.expr_call_lang_item_fn(
821819
span,
822820
hir::LangItem::AsyncIteratorPollNext,
823-
arena_vec![self; new_unchecked, get_context],
821+
arena_vec![self; new_unchecked, task_context],
824822
),
825823
};
826824
self.arena.alloc(self.expr_unsafe(call))
@@ -831,14 +829,14 @@ impl<'hir> LoweringContext<'_, 'hir> {
831829
let loop_hir_id = self.lower_node_id(loop_node_id);
832830
let ready_arm = {
833831
let x_ident = Ident::with_dummy_span(sym::result);
834-
let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident);
835-
let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
836-
let ready_field = self.single_pat_field(gen_future_span, x_pat);
832+
let (x_pat, x_pat_hid) = self.pat_ident(full_span, x_ident);
833+
let x_expr = self.expr_ident(full_span, x_ident, x_pat_hid);
834+
let ready_field = self.single_pat_field(full_span, x_pat);
837835
let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field);
838836
let break_x = self.with_loop_scope(loop_node_id, move |this| {
839837
let expr_break =
840838
hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
841-
this.arena.alloc(this.expr(gen_future_span, expr_break))
839+
this.arena.alloc(this.expr(full_span, expr_break))
842840
});
843841
self.arm(ready_pat, break_x)
844842
};

compiler/rustc_hir/src/lang_items.rs

-5
Original file line numberDiff line numberDiff line change
@@ -299,11 +299,6 @@ language_item_table! {
299299
AsyncGenPending, sym::AsyncGenPending, async_gen_pending, Target::AssocConst, GenericRequirement::Exact(1);
300300
AsyncGenFinished, sym::AsyncGenFinished, async_gen_finished, Target::AssocConst, GenericRequirement::Exact(1);
301301

302-
// FIXME(swatinem): the following lang items are used for async lowering and
303-
// should become obsolete eventually.
304-
ResumeTy, sym::ResumeTy, resume_ty, Target::Struct, GenericRequirement::None;
305-
GetContext, sym::get_context, get_context_fn, Target::Fn, GenericRequirement::None;
306-
307302
Context, sym::Context, context, Target::Struct, GenericRequirement::None;
308303
FuturePoll, sym::poll, future_poll_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
309304

compiler/rustc_middle/src/ty/sty.rs

-9
Original file line numberDiff line numberDiff line change
@@ -2234,15 +2234,6 @@ impl<'tcx> Ty<'tcx> {
22342234
let def_id = tcx.require_lang_item(LangItem::MaybeUninit, None);
22352235
Ty::new_generic_adt(tcx, def_id, ty)
22362236
}
2237-
2238-
/// Creates a `&mut Context<'_>` [`Ty`] with erased lifetimes.
2239-
pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2240-
let context_did = tcx.require_lang_item(LangItem::Context, None);
2241-
let context_adt_ref = tcx.adt_def(context_did);
2242-
let context_args = tcx.mk_args(&[tcx.lifetimes.re_erased.into()]);
2243-
let context_ty = Ty::new_adt(tcx, context_adt_ref, context_args);
2244-
Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty)
2245-
}
22462237
}
22472238

22482239
/// Type utilities

compiler/rustc_mir_transform/src/coroutine.rs

+1-107
Original file line numberDiff line numberDiff line change
@@ -616,112 +616,14 @@ fn replace_local<'tcx>(
616616
new_local
617617
}
618618

619-
/// Transforms the `body` of the coroutine applying the following transforms:
620-
///
621-
/// - Eliminates all the `get_context` calls that async lowering created.
622-
/// - Replace all `Local` `ResumeTy` types with `&mut Context<'_>` (`context_mut_ref`).
623-
///
624-
/// The `Local`s that have their types replaced are:
625-
/// - The `resume` argument itself.
626-
/// - The argument to `get_context`.
627-
/// - The yielded value of a `yield`.
628-
///
629-
/// The `ResumeTy` hides a `&mut Context<'_>` behind an unsafe raw pointer, and the
630-
/// `get_context` function is being used to convert that back to a `&mut Context<'_>`.
631-
///
632-
/// Ideally the async lowering would not use the `ResumeTy`/`get_context` indirection,
633-
/// but rather directly use `&mut Context<'_>`, however that would currently
634-
/// lead to higher-kinded lifetime errors.
635-
/// See <https://github.com/rust-lang/rust/issues/105501>.
636-
///
637-
/// The async lowering step and the type / lifetime inference / checking are
638-
/// still using the `ResumeTy` indirection for the time being, and that indirection
639-
/// is removed here. After this transform, the coroutine body only knows about `&mut Context<'_>`.
640-
fn transform_async_context<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
641-
let context_mut_ref = Ty::new_task_context(tcx);
642-
643-
// replace the type of the `resume` argument
644-
replace_resume_ty_local(tcx, body, Local::new(2), context_mut_ref);
645-
646-
let get_context_def_id = tcx.require_lang_item(LangItem::GetContext, None);
647-
648-
for bb in START_BLOCK..body.basic_blocks.next_index() {
649-
let bb_data = &body[bb];
650-
if bb_data.is_cleanup {
651-
continue;
652-
}
653-
654-
match &bb_data.terminator().kind {
655-
TerminatorKind::Call { func, .. } => {
656-
let func_ty = func.ty(body, tcx);
657-
if let ty::FnDef(def_id, _) = *func_ty.kind() {
658-
if def_id == get_context_def_id {
659-
let local = eliminate_get_context_call(&mut body[bb]);
660-
replace_resume_ty_local(tcx, body, local, context_mut_ref);
661-
}
662-
} else {
663-
continue;
664-
}
665-
}
666-
TerminatorKind::Yield { resume_arg, .. } => {
667-
replace_resume_ty_local(tcx, body, resume_arg.local, context_mut_ref);
668-
}
669-
_ => {}
670-
}
671-
}
672-
}
673-
674-
fn eliminate_get_context_call<'tcx>(bb_data: &mut BasicBlockData<'tcx>) -> Local {
675-
let terminator = bb_data.terminator.take().unwrap();
676-
if let TerminatorKind::Call { mut args, destination, target, .. } = terminator.kind {
677-
let arg = args.pop().unwrap();
678-
let local = arg.place().unwrap().local;
679-
680-
let arg = Rvalue::Use(arg);
681-
let assign = Statement {
682-
source_info: terminator.source_info,
683-
kind: StatementKind::Assign(Box::new((destination, arg))),
684-
};
685-
bb_data.statements.push(assign);
686-
bb_data.terminator = Some(Terminator {
687-
source_info: terminator.source_info,
688-
kind: TerminatorKind::Goto { target: target.unwrap() },
689-
});
690-
local
691-
} else {
692-
bug!();
693-
}
694-
}
695-
696-
#[cfg_attr(not(debug_assertions), allow(unused))]
697-
fn replace_resume_ty_local<'tcx>(
698-
tcx: TyCtxt<'tcx>,
699-
body: &mut Body<'tcx>,
700-
local: Local,
701-
context_mut_ref: Ty<'tcx>,
702-
) {
703-
let local_ty = std::mem::replace(&mut body.local_decls[local].ty, context_mut_ref);
704-
// We have to replace the `ResumeTy` that is used for type and borrow checking
705-
// with `&mut Context<'_>` in MIR.
706-
#[cfg(debug_assertions)]
707-
{
708-
if let ty::Adt(resume_ty_adt, _) = local_ty.kind() {
709-
let expected_adt = tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, None));
710-
assert_eq!(*resume_ty_adt, expected_adt);
711-
} else {
712-
panic!("expected `ResumeTy`, found `{:?}`", local_ty);
713-
};
714-
}
715-
}
716-
717619
/// Transforms the `body` of the coroutine applying the following transform:
718620
///
719621
/// - Remove the `resume` argument.
720622
///
721623
/// Ideally the async lowering would not add the `resume` argument.
722624
///
723625
/// The async lowering step and the type / lifetime inference / checking are
724-
/// still using the `resume` argument for the time being. After this transform,
626+
/// still using the `resume` argument for the time being. After this transform
725627
/// the coroutine body doesn't have the `resume` argument.
726628
fn transform_gen_context<'tcx>(_tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
727629
// This leaves the local representing the `resume` argument in place,
@@ -1644,14 +1546,6 @@ impl<'tcx> MirPass<'tcx> for StateTransform {
16441546
// RETURN_PLACE then is a fresh unused local with type ret_ty.
16451547
let old_ret_local = replace_local(RETURN_PLACE, new_ret_ty, body, tcx);
16461548

1647-
// Replace all occurrences of `ResumeTy` with `&mut Context<'_>` within async bodies.
1648-
if matches!(
1649-
coroutine_kind,
1650-
CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _)
1651-
) {
1652-
transform_async_context(tcx, body);
1653-
}
1654-
16551549
// We also replace the resume argument and insert an `Assign`.
16561550
// This is needed because the resume argument `_2` might be live across a `yield`, in which
16571551
// case there is no `Assign` to it that the transform can turn into a store to the coroutine

compiler/rustc_span/src/symbol.rs

-2
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,6 @@ symbols! {
293293
Relaxed,
294294
Release,
295295
Result,
296-
ResumeTy,
297296
Return,
298297
Right,
299298
Rust,
@@ -835,7 +834,6 @@ symbols! {
835834
generic_const_exprs,
836835
generic_const_items,
837836
generic_param_attrs,
838-
get_context,
839837
global_allocator,
840838
global_asm,
841839
globs,

compiler/rustc_ty_utils/src/abi.rs

+2-30
Original file line numberDiff line numberDiff line change
@@ -140,21 +140,7 @@ fn fn_sig_for_fn_abi<'tcx>(
140140
let poll_args = tcx.mk_args(&[sig.return_ty.into()]);
141141
let ret_ty = Ty::new_adt(tcx, poll_adt_ref, poll_args);
142142

143-
// We have to replace the `ResumeTy` that is used for type and borrow checking
144-
// with `&mut Context<'_>` which is used in codegen.
145-
#[cfg(debug_assertions)]
146-
{
147-
if let ty::Adt(resume_ty_adt, _) = sig.resume_ty.kind() {
148-
let expected_adt =
149-
tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, None));
150-
assert_eq!(*resume_ty_adt, expected_adt);
151-
} else {
152-
panic!("expected `ResumeTy`, found `{:?}`", sig.resume_ty);
153-
};
154-
}
155-
let context_mut_ref = Ty::new_task_context(tcx);
156-
157-
(Some(context_mut_ref), ret_ty)
143+
(Some(sig.resume_ty), ret_ty)
158144
}
159145
hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _) => {
160146
// The signature should be `Iterator::next(_) -> Option<Yield>`
@@ -176,21 +162,7 @@ fn fn_sig_for_fn_abi<'tcx>(
176162
// Yield type is already `Poll<Option<yield_ty>>`
177163
let ret_ty = sig.yield_ty;
178164

179-
// We have to replace the `ResumeTy` that is used for type and borrow checking
180-
// with `&mut Context<'_>` which is used in codegen.
181-
#[cfg(debug_assertions)]
182-
{
183-
if let ty::Adt(resume_ty_adt, _) = sig.resume_ty.kind() {
184-
let expected_adt =
185-
tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, None));
186-
assert_eq!(*resume_ty_adt, expected_adt);
187-
} else {
188-
panic!("expected `ResumeTy`, found `{:?}`", sig.resume_ty);
189-
};
190-
}
191-
let context_mut_ref = Ty::new_task_context(tcx);
192-
193-
(Some(context_mut_ref), ret_ty)
165+
(Some(sig.resume_ty), ret_ty)
194166
}
195167
hir::CoroutineKind::Coroutine(_) => {
196168
// The signature should be `Coroutine::resume(_, Resume) -> CoroutineState<Yield, Return>`

library/core/src/future/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ pub use poll_fn::{poll_fn, PollFn};
4444
/// non-Send/Sync as well, and we don't want that.
4545
///
4646
/// It also simplifies the HIR lowering of `.await`.
47-
#[lang = "ResumeTy"]
47+
#[cfg_attr(bootstrap, lang = "ResumeTy")]
4848
#[doc(hidden)]
4949
#[unstable(feature = "gen_future", issue = "50547")]
5050
#[derive(Debug, Copy, Clone)]
@@ -56,7 +56,7 @@ unsafe impl Send for ResumeTy {}
5656
#[unstable(feature = "gen_future", issue = "50547")]
5757
unsafe impl Sync for ResumeTy {}
5858

59-
#[lang = "get_context"]
59+
#[cfg_attr(bootstrap, lang = "get_context")]
6060
#[doc(hidden)]
6161
#[unstable(feature = "gen_future", issue = "50547")]
6262
#[must_use]

tests/ui/async-await/issue-69446-fnmut-capture.stderr

+3
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ LL | | });
1414
|
1515
= note: `FnMut` closures only have access to their captured variables while they are executing...
1616
= note: ...therefore, they cannot allow references to captured variables to escape
17+
= note: requirement occurs because of a mutable reference to `Context<'_>`
18+
= note: mutable references are invariant over their type parameter
19+
= help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance
1720

1821
error: aborting due to 1 previous error
1922

tests/ui/async-await/unreachable-lint.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
// check-pass
21
// edition:2018
32
#![deny(unreachable_code)]
43

54
async fn foo() {
65
endless().await;
6+
//~^ ERROR unreachable expression
77
}
88

99
async fn endless() -> ! {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
error: unreachable expression
2+
--> $DIR/unreachable-lint.rs:5:5
3+
|
4+
LL | endless().await;
5+
| ^^^^^^^^^^^^^^^
6+
| |
7+
| unreachable expression
8+
| any code following this expression is unreachable
9+
|
10+
note: the lint level is defined here
11+
--> $DIR/unreachable-lint.rs:2:9
12+
|
13+
LL | #![deny(unreachable_code)]
14+
| ^^^^^^^^^^^^^^^^
15+
16+
error: aborting due to 1 previous error
17+

0 commit comments

Comments
 (0)