Skip to content

Commit b684ee7

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 1ddedba commit b684ee7

File tree

14 files changed

+76
-199
lines changed

14 files changed

+76
-199
lines changed

compiler/rustc_ast_lowering/src/expr.rs

+29-28
Original file line numberDiff line numberDiff line change
@@ -632,17 +632,28 @@ impl<'hir> LoweringContext<'_, 'hir> {
632632
// whereas a generator does not.
633633
let (inputs, params, task_context): (&[_], &[_], _) = match desugaring_kind {
634634
hir::CoroutineDesugaring::Async | hir::CoroutineDesugaring::AsyncGen => {
635-
// Resume argument type: `ResumeTy`
636-
let unstable_span = self.mark_span_with_reason(
637-
DesugaringKind::Async,
638-
self.lower_span(span),
639-
Some(self.allow_gen_future.clone()),
640-
);
641-
let resume_ty = self.make_lang_item_qpath(hir::LangItem::ResumeTy, unstable_span);
635+
// Resume argument type: `&mut Context<'_>`.
636+
let context_lifetime_ident = Ident::with_dummy_span(kw::UnderscoreLifetime);
637+
let context_lifetime = self.arena.alloc(hir::Lifetime {
638+
hir_id: self.next_id(),
639+
ident: context_lifetime_ident,
640+
res: hir::LifetimeName::Infer,
641+
});
642+
let context_path =
643+
hir::QPath::LangItem(hir::LangItem::Context, self.lower_span(span));
644+
let context_ty = hir::MutTy {
645+
ty: self.arena.alloc(hir::Ty {
646+
hir_id: self.next_id(),
647+
kind: hir::TyKind::Path(context_path),
648+
span: self.lower_span(span),
649+
}),
650+
mutbl: hir::Mutability::Mut,
651+
};
652+
642653
let input_ty = hir::Ty {
643654
hir_id: self.next_id(),
644-
kind: hir::TyKind::Path(resume_ty),
645-
span: unstable_span,
655+
kind: hir::TyKind::Ref(context_lifetime, context_ty),
656+
span: self.lower_span(span),
646657
};
647658
let inputs = arena_vec![self; input_ty];
648659

@@ -744,7 +755,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
744755
/// mut __awaitee => loop {
745756
/// match unsafe { ::std::future::Future::poll(
746757
/// <::std::pin::Pin>::new_unchecked(&mut __awaitee),
747-
/// ::std::future::get_context(task_context),
758+
/// task_context,
748759
/// ) } {
749760
/// ::std::task::Poll::Ready(result) => break result,
750761
/// ::std::task::Poll::Pending => {}
@@ -803,26 +814,21 @@ impl<'hir> LoweringContext<'_, 'hir> {
803814
FutureKind::AsyncIterator => Some(self.allow_for_await.clone()),
804815
};
805816
let span = self.mark_span_with_reason(DesugaringKind::Await, await_kw_span, features);
806-
let gen_future_span = self.mark_span_with_reason(
807-
DesugaringKind::Await,
808-
full_span,
809-
Some(self.allow_gen_future.clone()),
810-
);
811817
let expr_hir_id = expr.hir_id;
812818

813819
// Note that the name of this binding must not be changed to something else because
814820
// debuggers and debugger extensions expect it to be called `__awaitee`. They use
815821
// this name to identify what is being awaited by a suspended async functions.
816822
let awaitee_ident = Ident::with_dummy_span(sym::__awaitee);
817823
let (awaitee_pat, awaitee_pat_hid) =
818-
self.pat_ident_binding_mode(gen_future_span, awaitee_ident, hir::BindingMode::MUT);
824+
self.pat_ident_binding_mode(full_span, awaitee_ident, hir::BindingMode::MUT);
819825

820826
let task_context_ident = Ident::with_dummy_span(sym::_task_context);
821827

822828
// unsafe {
823829
// ::std::future::Future::poll(
824830
// ::std::pin::Pin::new_unchecked(&mut __awaitee),
825-
// ::std::future::get_context(task_context),
831+
// task_context,
826832
// )
827833
// }
828834
let poll_expr = {
@@ -840,21 +846,16 @@ impl<'hir> LoweringContext<'_, 'hir> {
840846
hir::LangItem::PinNewUnchecked,
841847
arena_vec![self; ref_mut_awaitee],
842848
);
843-
let get_context = self.expr_call_lang_item_fn_mut(
844-
gen_future_span,
845-
hir::LangItem::GetContext,
846-
arena_vec![self; task_context],
847-
);
848849
let call = match await_kind {
849850
FutureKind::Future => self.expr_call_lang_item_fn(
850851
span,
851852
hir::LangItem::FuturePoll,
852-
arena_vec![self; new_unchecked, get_context],
853+
arena_vec![self; new_unchecked, task_context],
853854
),
854855
FutureKind::AsyncIterator => self.expr_call_lang_item_fn(
855856
span,
856857
hir::LangItem::AsyncIteratorPollNext,
857-
arena_vec![self; new_unchecked, get_context],
858+
arena_vec![self; new_unchecked, task_context],
858859
),
859860
};
860861
self.arena.alloc(self.expr_unsafe(call))
@@ -865,14 +866,14 @@ impl<'hir> LoweringContext<'_, 'hir> {
865866
let loop_hir_id = self.lower_node_id(loop_node_id);
866867
let ready_arm = {
867868
let x_ident = Ident::with_dummy_span(sym::result);
868-
let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident);
869-
let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
870-
let ready_field = self.single_pat_field(gen_future_span, x_pat);
869+
let (x_pat, x_pat_hid) = self.pat_ident(full_span, x_ident);
870+
let x_expr = self.expr_ident(full_span, x_ident, x_pat_hid);
871+
let ready_field = self.single_pat_field(full_span, x_pat);
871872
let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field);
872873
let break_x = self.with_loop_scope(loop_node_id, move |this| {
873874
let expr_break =
874875
hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
875-
this.arena.alloc(this.expr(gen_future_span, expr_break))
876+
this.arena.alloc(this.expr(full_span, expr_break))
876877
});
877878
self.arm(ready_pat, break_x)
878879
};

compiler/rustc_hir/src/lang_items.rs

-5
Original file line numberDiff line numberDiff line change
@@ -369,11 +369,6 @@ language_item_table! {
369369
AsyncGenPending, sym::AsyncGenPending, async_gen_pending, Target::AssocConst, GenericRequirement::Exact(1);
370370
AsyncGenFinished, sym::AsyncGenFinished, async_gen_finished, Target::AssocConst, GenericRequirement::Exact(1);
371371

372-
// FIXME(swatinem): the following lang items are used for async lowering and
373-
// should become obsolete eventually.
374-
ResumeTy, sym::ResumeTy, resume_ty, Target::Struct, GenericRequirement::None;
375-
GetContext, sym::get_context, get_context_fn, Target::Fn, GenericRequirement::None;
376-
377372
Context, sym::Context, context, Target::Struct, GenericRequirement::None;
378373
FuturePoll, sym::poll, future_poll_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
379374

compiler/rustc_middle/src/ty/sty.rs

-9
Original file line numberDiff line numberDiff line change
@@ -781,15 +781,6 @@ impl<'tcx> Ty<'tcx> {
781781
let def_id = tcx.require_lang_item(LangItem::MaybeUninit, None);
782782
Ty::new_generic_adt(tcx, def_id, ty)
783783
}
784-
785-
/// Creates a `&mut Context<'_>` [`Ty`] with erased lifetimes.
786-
pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
787-
let context_did = tcx.require_lang_item(LangItem::Context, None);
788-
let context_adt_ref = tcx.adt_def(context_did);
789-
let context_args = tcx.mk_args(&[tcx.lifetimes.re_erased.into()]);
790-
let context_ty = Ty::new_adt(tcx, context_adt_ref, context_args);
791-
Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty)
792-
}
793784
}
794785

795786
impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> {

compiler/rustc_mir_transform/src/coroutine.rs

+1-107
Original file line numberDiff line numberDiff line change
@@ -607,112 +607,14 @@ fn replace_local<'tcx>(
607607
new_local
608608
}
609609

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

1683-
// Replace all occurrences of `ResumeTy` with `&mut Context<'_>` within async bodies.
1684-
if matches!(
1685-
coroutine_kind,
1686-
CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _)
1687-
) {
1688-
transform_async_context(tcx, body);
1689-
}
1690-
16911585
// We also replace the resume argument and insert an `Assign`.
16921586
// This is needed because the resume argument `_2` might be live across a `yield`, in which
16931587
// 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
@@ -297,7 +297,6 @@ symbols! {
297297
Relaxed,
298298
Release,
299299
Result,
300-
ResumeTy,
301300
Return,
302301
Right,
303302
Rust,
@@ -952,7 +951,6 @@ symbols! {
952951
generic_const_exprs,
953952
generic_const_items,
954953
generic_param_attrs,
955-
get_context,
956954
global_alloc_ty,
957955
global_allocator,
958956
global_asm,

compiler/rustc_ty_utils/src/abi.rs

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

237-
// We have to replace the `ResumeTy` that is used for type and borrow checking
238-
// with `&mut Context<'_>` which is used in codegen.
239-
#[cfg(debug_assertions)]
240-
{
241-
if let ty::Adt(resume_ty_adt, _) = sig.resume_ty.kind() {
242-
let expected_adt =
243-
tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, None));
244-
assert_eq!(*resume_ty_adt, expected_adt);
245-
} else {
246-
panic!("expected `ResumeTy`, found `{:?}`", sig.resume_ty);
247-
};
248-
}
249-
let context_mut_ref = Ty::new_task_context(tcx);
250-
251-
(Some(context_mut_ref), ret_ty)
237+
(Some(sig.resume_ty), ret_ty)
252238
}
253239
hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _) => {
254240
// The signature should be `Iterator::next(_) -> Option<Yield>`
@@ -270,21 +256,7 @@ fn fn_sig_for_fn_abi<'tcx>(
270256
// Yield type is already `Poll<Option<yield_ty>>`
271257
let ret_ty = sig.yield_ty;
272258

273-
// We have to replace the `ResumeTy` that is used for type and borrow checking
274-
// with `&mut Context<'_>` which is used in codegen.
275-
#[cfg(debug_assertions)]
276-
{
277-
if let ty::Adt(resume_ty_adt, _) = sig.resume_ty.kind() {
278-
let expected_adt =
279-
tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, None));
280-
assert_eq!(*resume_ty_adt, expected_adt);
281-
} else {
282-
panic!("expected `ResumeTy`, found `{:?}`", sig.resume_ty);
283-
};
284-
}
285-
let context_mut_ref = Ty::new_task_context(tcx);
286-
287-
(Some(context_mut_ref), ret_ty)
259+
(Some(sig.resume_ty), ret_ty)
288260
}
289261
hir::CoroutineKind::Coroutine(_) => {
290262
// 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 self::join::join;
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() {}
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)