Skip to content

Commit 4fd5a13

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 4316d0c commit 4fd5a13

File tree

14 files changed

+77
-203
lines changed

14 files changed

+77
-203
lines changed

compiler/rustc_ast_lowering/src/expr.rs

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

@@ -731,7 +742,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
731742
/// mut __awaitee => loop {
732743
/// match unsafe { ::std::future::Future::poll(
733744
/// <::std::pin::Pin>::new_unchecked(&mut __awaitee),
734-
/// ::std::future::get_context(task_context),
745+
/// task_context,
735746
/// ) } {
736747
/// ::std::task::Poll::Ready(result) => break result,
737748
/// ::std::task::Poll::Pending => {}
@@ -772,29 +783,21 @@ impl<'hir> LoweringContext<'_, 'hir> {
772783
FutureKind::AsyncIterator => Some(self.allow_for_await.clone()),
773784
};
774785
let span = self.mark_span_with_reason(DesugaringKind::Await, await_kw_span, features);
775-
let gen_future_span = self.mark_span_with_reason(
776-
DesugaringKind::Await,
777-
full_span,
778-
Some(self.allow_gen_future.clone()),
779-
);
780786
let expr_hir_id = expr.hir_id;
781787

782788
// Note that the name of this binding must not be changed to something else because
783789
// debuggers and debugger extensions expect it to be called `__awaitee`. They use
784790
// this name to identify what is being awaited by a suspended async functions.
785791
let awaitee_ident = Ident::with_dummy_span(sym::__awaitee);
786-
let (awaitee_pat, awaitee_pat_hid) = self.pat_ident_binding_mode(
787-
gen_future_span,
788-
awaitee_ident,
789-
hir::BindingAnnotation::MUT,
790-
);
792+
let (awaitee_pat, awaitee_pat_hid) =
793+
self.pat_ident_binding_mode(full_span, awaitee_ident, hir::BindingAnnotation::MUT);
791794

792795
let task_context_ident = Ident::with_dummy_span(sym::_task_context);
793796

794797
// unsafe {
795798
// ::std::future::Future::poll(
796799
// ::std::pin::Pin::new_unchecked(&mut __awaitee),
797-
// ::std::future::get_context(task_context),
800+
// task_context,
798801
// )
799802
// }
800803
let poll_expr = {
@@ -812,21 +815,16 @@ impl<'hir> LoweringContext<'_, 'hir> {
812815
hir::LangItem::PinNewUnchecked,
813816
arena_vec![self; ref_mut_awaitee],
814817
);
815-
let get_context = self.expr_call_lang_item_fn_mut(
816-
gen_future_span,
817-
hir::LangItem::GetContext,
818-
arena_vec![self; task_context],
819-
);
820818
let call = match await_kind {
821819
FutureKind::Future => self.expr_call_lang_item_fn(
822820
span,
823821
hir::LangItem::FuturePoll,
824-
arena_vec![self; new_unchecked, get_context],
822+
arena_vec![self; new_unchecked, task_context],
825823
),
826824
FutureKind::AsyncIterator => self.expr_call_lang_item_fn(
827825
span,
828826
hir::LangItem::AsyncIteratorPollNext,
829-
arena_vec![self; new_unchecked, get_context],
827+
arena_vec![self; new_unchecked, task_context],
830828
),
831829
};
832830
self.arena.alloc(self.expr_unsafe(call))
@@ -837,14 +835,14 @@ impl<'hir> LoweringContext<'_, 'hir> {
837835
let loop_hir_id = self.lower_node_id(loop_node_id);
838836
let ready_arm = {
839837
let x_ident = Ident::with_dummy_span(sym::result);
840-
let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident);
841-
let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
842-
let ready_field = self.single_pat_field(gen_future_span, x_pat);
838+
let (x_pat, x_pat_hid) = self.pat_ident(full_span, x_ident);
839+
let x_expr = self.expr_ident(full_span, x_ident, x_pat_hid);
840+
let ready_field = self.single_pat_field(full_span, x_pat);
843841
let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field);
844842
let break_x = self.with_loop_scope(loop_node_id, move |this| {
845843
let expr_break =
846844
hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
847-
this.arena.alloc(this.expr(gen_future_span, expr_break))
845+
this.arena.alloc(this.expr(full_span, expr_break))
848846
});
849847
self.arm(ready_pat, break_x)
850848
};

compiler/rustc_hir/src/lang_items.rs

-5
Original file line numberDiff line numberDiff line change
@@ -305,11 +305,6 @@ language_item_table! {
305305
AsyncGenPending, sym::AsyncGenPending, async_gen_pending, Target::AssocConst, GenericRequirement::Exact(1);
306306
AsyncGenFinished, sym::AsyncGenFinished, async_gen_finished, Target::AssocConst, GenericRequirement::Exact(1);
307307

308-
// FIXME(swatinem): the following lang items are used for async lowering and
309-
// should become obsolete eventually.
310-
ResumeTy, sym::ResumeTy, resume_ty, Target::Struct, GenericRequirement::None;
311-
GetContext, sym::get_context, get_context_fn, Target::Fn, GenericRequirement::None;
312-
313308
Context, sym::Context, context, Target::Struct, GenericRequirement::None;
314309
FuturePoll, sym::poll, future_poll_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
315310

compiler/rustc_middle/src/ty/sty.rs

-9
Original file line numberDiff line numberDiff line change
@@ -1800,15 +1800,6 @@ impl<'tcx> Ty<'tcx> {
18001800
let def_id = tcx.require_lang_item(LangItem::MaybeUninit, None);
18011801
Ty::new_generic_adt(tcx, def_id, ty)
18021802
}
1803-
1804-
/// Creates a `&mut Context<'_>` [`Ty`] with erased lifetimes.
1805-
pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1806-
let context_did = tcx.require_lang_item(LangItem::Context, None);
1807-
let context_adt_ref = tcx.adt_def(context_did);
1808-
let context_args = tcx.mk_args(&[tcx.lifetimes.re_erased.into()]);
1809-
let context_ty = Ty::new_adt(tcx, context_adt_ref, context_args);
1810-
Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty)
1811-
}
18121803
}
18131804

18141805
/// Type utilities

compiler/rustc_mir_transform/src/coroutine.rs

+1-107
Original file line numberDiff line numberDiff line change
@@ -619,112 +619,14 @@ fn replace_local<'tcx>(
619619
new_local
620620
}
621621

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

1658-
// Replace all occurrences of `ResumeTy` with `&mut Context<'_>` within async bodies.
1659-
if matches!(
1660-
coroutine_kind,
1661-
CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _)
1662-
) {
1663-
transform_async_context(tcx, body);
1664-
}
1665-
16661560
// We also replace the resume argument and insert an `Assign`.
16671561
// This is needed because the resume argument `_2` might be live across a `yield`, in which
16681562
// 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
@@ -286,7 +286,6 @@ symbols! {
286286
Relaxed,
287287
Release,
288288
Result,
289-
ResumeTy,
290289
Return,
291290
Right,
292291
Rust,
@@ -841,7 +840,6 @@ symbols! {
841840
generic_const_exprs,
842841
generic_const_items,
843842
generic_param_attrs,
844-
get_context,
845843
global_allocator,
846844
global_asm,
847845
globs,

compiler/rustc_ty_utils/src/abi.rs

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

224-
// We have to replace the `ResumeTy` that is used for type and borrow checking
225-
// with `&mut Context<'_>` which is used in codegen.
226-
#[cfg(debug_assertions)]
227-
{
228-
if let ty::Adt(resume_ty_adt, _) = sig.resume_ty.kind() {
229-
let expected_adt =
230-
tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, None));
231-
assert_eq!(*resume_ty_adt, expected_adt);
232-
} else {
233-
panic!("expected `ResumeTy`, found `{:?}`", sig.resume_ty);
234-
};
235-
}
236-
let context_mut_ref = Ty::new_task_context(tcx);
237-
238-
(Some(context_mut_ref), ret_ty)
224+
(Some(sig.resume_ty), ret_ty)
239225
}
240226
hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _) => {
241227
// The signature should be `Iterator::next(_) -> Option<Yield>`
@@ -257,21 +243,7 @@ fn fn_sig_for_fn_abi<'tcx>(
257243
// Yield type is already `Poll<Option<yield_ty>>`
258244
let ret_ty = sig.yield_ty;
259245

260-
// We have to replace the `ResumeTy` that is used for type and borrow checking
261-
// with `&mut Context<'_>` which is used in codegen.
262-
#[cfg(debug_assertions)]
263-
{
264-
if let ty::Adt(resume_ty_adt, _) = sig.resume_ty.kind() {
265-
let expected_adt =
266-
tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, None));
267-
assert_eq!(*resume_ty_adt, expected_adt);
268-
} else {
269-
panic!("expected `ResumeTy`, found `{:?}`", sig.resume_ty);
270-
};
271-
}
272-
let context_mut_ref = Ty::new_task_context(tcx);
273-
274-
(Some(context_mut_ref), ret_ty)
246+
(Some(sig.resume_ty), ret_ty)
275247
}
276248
hir::CoroutineKind::Coroutine(_) => {
277249
// 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

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
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() -> ! {
1010
loop {}
1111
}
1212

13-
fn main() { }
13+
fn main() {}

0 commit comments

Comments
 (0)