Skip to content

Commit eabfa73

Browse files
Bless tests, add comments
1 parent 2ae8188 commit eabfa73

31 files changed

+231
-116
lines changed

compiler/rustc_borrowck/src/type_check/input_output.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,9 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
4747
user_provided_sig,
4848
);
4949

50-
// FIXME(async_closures): We must apply the same transformation to our
51-
// signature here as we do during closure checking.
50+
// FIXME(async_closures): It's kind of wacky that we must apply this
51+
// transofmration here, since we do the same thing in HIR typeck.
52+
// Maybe we could just fix up the canonicalized signature during HIR typeck?
5253
if let DefiningTy::CoroutineClosure(_, args) =
5354
self.borrowck_context.universal_regions.defining_ty
5455
{

compiler/rustc_borrowck/src/universal_regions.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,10 @@ pub enum DefiningTy<'tcx> {
9898
Coroutine(DefId, GenericArgsRef<'tcx>),
9999

100100
/// The MIR is a special kind of closure that returns coroutines.
101-
/// TODO: describe how to make the sig...
101+
///
102+
/// See the documentation on `CoroutineClosureSignature` for details
103+
/// on how to construct the callable signature of the coroutine from
104+
/// its args.
102105
CoroutineClosure(DefId, GenericArgsRef<'tcx>),
103106

104107
/// The MIR is a fn item with the given `DefId` and args. The signature

compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
333333
continue;
334334
}
335335

336-
// For this check, we do *not* want to treat async coroutine closures (async blocks)
336+
// For this check, we do *not* want to treat async coroutine-closures (async blocks)
337337
// as proper closures. Doing so would regress type inference when feeding
338338
// the return value of an argument-position async block to an argument-position
339339
// closure wrapped in a block.

compiler/rustc_middle/src/mir/mod.rs

+10-2
Original file line numberDiff line numberDiff line change
@@ -260,8 +260,16 @@ pub struct CoroutineInfo<'tcx> {
260260
/// Coroutine drop glue. This field is populated after the state transform pass.
261261
pub coroutine_drop: Option<Body<'tcx>>,
262262

263-
/// The body of the coroutine, modified to take its upvars by move.
264-
/// TODO:
263+
/// The body of the coroutine, modified to take its upvars by move rather than by ref.
264+
///
265+
/// This is used by coroutine-closures, which must return a different flavor of coroutine
266+
/// when called using `AsyncFnOnce::call_once`. It is produced by the `ByMoveBody` which
267+
/// is run right after building the initial MIR, and will only be populated for coroutines
268+
/// which come out of the async closure desugaring.
269+
///
270+
/// This body should be processed in lockstep with the containing body -- any optimization
271+
/// passes, etc, should be applied to this body as well. This is done automatically if
272+
/// using `run_passes`.
265273
pub by_move_body: Option<Body<'tcx>>,
266274

267275
/// The layout of a coroutine. This field is populated after the state transform pass.

compiler/rustc_middle/src/query/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -756,7 +756,7 @@ rustc_queries! {
756756
}
757757

758758
query coroutine_for_closure(def_id: DefId) -> DefId {
759-
desc { |_tcx| "TODO" }
759+
desc { |_tcx| "Given a coroutine-closure def id, return the def id of the coroutine returned by it" }
760760
separate_provide_extern
761761
}
762762

compiler/rustc_middle/src/traits/select.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,9 @@ pub enum SelectionCandidate<'tcx> {
138138
/// generated for an `async ||` expression.
139139
AsyncClosureCandidate,
140140

141-
// TODO:
141+
/// Implementation of the the `AsyncFnKindHelper` helper trait, which
142+
/// is used internally to delay computation for async closures until after
143+
/// upvar analysis is performed in HIR typeck.
142144
AsyncFnKindHelperCandidate,
143145

144146
/// Implementation of a `Coroutine` trait by one of the anonymous types

compiler/rustc_middle/src/ty/instance.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,10 @@ pub enum InstanceDef<'tcx> {
101101
target_kind: ty::ClosureKind,
102102
},
103103

104-
/// TODO:
104+
/// `<[coroutine] as Future>::poll`, but for coroutines produced when `AsyncFnOnce`
105+
/// is called on a coroutine-closure whose closure kind is not `FnOnce`. This
106+
/// will select the body that is produced by the `ByMoveBody` transform, and thus
107+
/// take and use all of its upvars by-move rather than by-ref.
105108
CoroutineByMoveShim { coroutine_def_id: DefId },
106109

107110
/// Compiler-generated accessor for thread locals which returns a reference to the thread local

compiler/rustc_middle/src/ty/print/pretty.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -877,7 +877,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
877877
ty::CoroutineClosure(did, args) => {
878878
p!(write("{{"));
879879
if !self.should_print_verbose() {
880-
p!(write("coroutine closure"));
880+
p!(write("coroutine-closure"));
881881
// FIXME(eddyb) should use `def_span`.
882882
if let Some(did) = did.as_local() {
883883
if self.tcx().sess.opts.unstable_opts.span_free_formats {

compiler/rustc_middle/src/ty/sty.rs

+34-2
Original file line numberDiff line numberDiff line change
@@ -352,11 +352,31 @@ pub struct CoroutineClosureArgs<'tcx> {
352352
}
353353

354354
pub struct CoroutineClosureArgsParts<'tcx> {
355+
/// This is the args of the typeck root.
355356
pub parent_args: &'tcx [GenericArg<'tcx>],
357+
/// Represents the maximum calling capability of the closure.
356358
pub closure_kind_ty: Ty<'tcx>,
359+
/// Represents all of the relevant parts of the coroutine returned by this
360+
/// coroutine-closure. This signature parts type will have the general
361+
/// shape of `fn(tupled_inputs, resume_ty) -> (return_ty, yield_ty)`, where
362+
/// `resume_ty`, `return_ty`, and `yield_ty` are the respective types for the
363+
/// coroutine returned by the coroutine-closure.
364+
///
365+
/// Use `coroutine_closure_sig` to break up this type rather than using it
366+
/// yourself.
357367
pub signature_parts_ty: Ty<'tcx>,
368+
/// The upvars captured by the closure. Remains an inference variable
369+
/// until the upvar analysis, which happens late in HIR typeck.
358370
pub tupled_upvars_ty: Ty<'tcx>,
371+
/// a function pointer that has the shape `for<'env> fn() -> (&'env T, ...)`.
372+
/// This allows us to represent the binder of the self-captures of the closure.
373+
///
374+
/// For example, if the coroutine returned by the closure borrows `String`
375+
/// from the closure's upvars, this will be `for<'env> fn() -> (&'env String,)`,
376+
/// while the `tupled_upvars_ty`, representing the by-move version of the same
377+
/// captures, will be `(String,)`.
359378
pub coroutine_captures_by_ref_ty: Ty<'tcx>,
379+
/// Witness type returned by the generator produced by this coroutine-closure.
360380
pub coroutine_witness_ty: Ty<'tcx>,
361381
}
362382

@@ -572,15 +592,27 @@ pub struct CoroutineArgs<'tcx> {
572592
pub struct CoroutineArgsParts<'tcx> {
573593
/// This is the args of the typeck root.
574594
pub parent_args: &'tcx [GenericArg<'tcx>],
575-
// TODO: why
595+
596+
/// The coroutines returned by a coroutine-closure's `AsyncFnOnce`/`AsyncFnMut`
597+
/// implementations must be distinguished since the former takes the closure's
598+
/// upvars by move, and the latter takes the closure's upvars by ref.
599+
///
600+
/// This field distinguishes these fields so that codegen can select the right
601+
/// body for the coroutine. This has the same type representation as the closure
602+
/// kind: `i8`/`i16`/`i32`.
603+
///
604+
/// For regular coroutines, this field will always just be `()`.
576605
pub kind_ty: Ty<'tcx>,
606+
577607
pub resume_ty: Ty<'tcx>,
578608
pub yield_ty: Ty<'tcx>,
579609
pub return_ty: Ty<'tcx>,
610+
580611
/// The interior type of the coroutine.
581612
/// Represents all types that are stored in locals
582613
/// in the coroutine's body.
583614
pub witness: Ty<'tcx>,
615+
584616
/// The upvars captured by the closure. Remains an inference variable
585617
/// until the upvar analysis, which happens late in HIR typeck.
586618
pub tupled_upvars_ty: Ty<'tcx>,
@@ -632,7 +664,7 @@ impl<'tcx> CoroutineArgs<'tcx> {
632664
self.split().parent_args
633665
}
634666

635-
// TODO:
667+
// Returns the kind of the coroutine. See docs on the `kind_ty` field.
636668
pub fn kind_ty(self) -> Ty<'tcx> {
637669
self.split().kind_ty
638670
}

compiler/rustc_mir_transform/src/const_prop_lint.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -607,7 +607,8 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
607607
AggregateKind::Array(_)
608608
| AggregateKind::Tuple
609609
| AggregateKind::Closure(_, _)
610-
| AggregateKind::Coroutine(_, _) => VariantIdx::new(0),
610+
| AggregateKind::Coroutine(_, _)
611+
| AggregateKind::CoroutineClosure(_, _) => VariantIdx::new(0),
611612
},
612613
},
613614

compiler/rustc_smir/src/rustc_smir/convert/mir.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -539,7 +539,7 @@ impl<'tcx> Stable<'tcx> for mir::AggregateKind<'tcx> {
539539
)
540540
}
541541
mir::AggregateKind::CoroutineClosure(..) => {
542-
todo!("FIXME(async_closure): Lower these to SMIR")
542+
todo!("FIXME(async_closures): Lower these to SMIR")
543543
}
544544
}
545545
}

compiler/rustc_smir/src/rustc_smir/convert/ty.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -384,7 +384,7 @@ impl<'tcx> Stable<'tcx> for ty::TyKind<'tcx> {
384384
tables.closure_def(*def_id),
385385
generic_args.stable(tables),
386386
)),
387-
ty::CoroutineClosure(..) => todo!("/* TODO */"),
387+
ty::CoroutineClosure(..) => todo!("FIXME(async_closures): Lower these to SMIR"),
388388
ty::Coroutine(def_id, generic_args) => TyKind::RigidTy(RigidTy::Coroutine(
389389
tables.coroutine_def(*def_id),
390390
generic_args.stable(tables),

compiler/rustc_span/src/symbol.rs

+1
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,7 @@ symbols! {
331331
TyCtxt,
332332
TyKind,
333333
Unknown,
334+
Upvars,
334335
Vec,
335336
VecDeque,
336337
Wrapper,

compiler/rustc_trait_selection/src/solve/assembly/mod.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,9 @@ pub(super) trait GoalKind<'tcx>:
190190
kind: ty::ClosureKind,
191191
) -> QueryResult<'tcx>;
192192

193-
/// TODO:
193+
/// Compute the built-in logic of the `AsyncFnKindHelper` helper trait, which
194+
/// is used internally to delay computation for async closures until after
195+
/// upvar analysis is performed in HIR typeck.
194196
fn consider_builtin_async_fn_kind_helper_candidate(
195197
ecx: &mut EvalCtxt<'_, 'tcx>,
196198
goal: Goal<'tcx, Self>,

compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs

+7-6
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use rustc_middle::traits::solve::Goal;
88
use rustc_middle::ty::{
99
self, ToPredicate, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt,
1010
};
11+
use rustc_span::sym;
1112

1213
use crate::solve::EvalCtxt;
1314

@@ -274,7 +275,7 @@ pub(in crate::solve) fn extract_tupled_inputs_and_output_from_callable<'tcx>(
274275
Ok(Some(closure_args.sig().map_bound(|sig| (sig.inputs()[0], sig.output()))))
275276
}
276277

277-
// Coroutine closures don't implement `Fn` traits the normal way.
278+
// Coroutine-closures don't implement `Fn` traits the normal way.
278279
ty::CoroutineClosure(..) => Err(NoSolution),
279280

280281
ty::Bool
@@ -341,11 +342,11 @@ pub(in crate::solve) fn extract_tupled_inputs_and_output_from_async_callable<'tc
341342
vec![],
342343
))
343344
} else {
344-
let helper_trait_def_id = tcx.require_lang_item(LangItem::AsyncFnKindHelper, None);
345-
// FIXME(async_closures): Make this into a lang item.
345+
let async_fn_kind_trait_def_id =
346+
tcx.require_lang_item(LangItem::AsyncFnKindHelper, None);
346347
let upvars_projection_def_id = tcx
347-
.associated_items(helper_trait_def_id)
348-
.in_definition_order()
348+
.associated_items(async_fn_kind_trait_def_id)
349+
.filter_by_name_unhygienic(sym::Upvars)
349350
.next()
350351
.unwrap()
351352
.def_id;
@@ -375,7 +376,7 @@ pub(in crate::solve) fn extract_tupled_inputs_and_output_from_async_callable<'tc
375376
vec![
376377
ty::TraitRef::new(
377378
tcx,
378-
helper_trait_def_id,
379+
async_fn_kind_trait_def_id,
379380
[kind_ty, Ty::from_closure_kind(tcx, goal_kind)],
380381
)
381382
.to_predicate(tcx),

compiler/rustc_trait_selection/src/traits/project.rs

+9-5
Original file line numberDiff line numberDiff line change
@@ -2461,12 +2461,13 @@ fn confirm_async_closure_candidate<'cx, 'tcx>(
24612461
let goal_kind =
24622462
tcx.async_fn_trait_kind_from_def_id(obligation.predicate.trait_def_id(tcx)).unwrap();
24632463

2464-
let helper_trait_def_id = tcx.require_lang_item(LangItem::AsyncFnKindHelper, None);
2464+
let async_fn_kind_helper_trait_def_id =
2465+
tcx.require_lang_item(LangItem::AsyncFnKindHelper, None);
24652466
nested.push(obligation.with(
24662467
tcx,
24672468
ty::TraitRef::new(
24682469
tcx,
2469-
helper_trait_def_id,
2470+
async_fn_kind_helper_trait_def_id,
24702471
[kind_ty, Ty::from_closure_kind(tcx, goal_kind)],
24712472
),
24722473
));
@@ -2476,9 +2477,12 @@ fn confirm_async_closure_candidate<'cx, 'tcx>(
24762477
ty::ClosureKind::FnOnce => tcx.lifetimes.re_static,
24772478
};
24782479

2479-
// FIXME(async_closures): Make this into a lang item.
2480-
let upvars_projection_def_id =
2481-
tcx.associated_items(helper_trait_def_id).in_definition_order().next().unwrap().def_id;
2480+
let upvars_projection_def_id = tcx
2481+
.associated_items(async_fn_kind_helper_trait_def_id)
2482+
.filter_by_name_unhygienic(sym::Upvars)
2483+
.next()
2484+
.unwrap()
2485+
.def_id;
24822486

24832487
// FIXME(async_closures): Confirmation is kind of a mess here. Ideally,
24842488
// we'd short-circuit when we know that the goal_kind >= closure_kind, and not

compiler/rustc_type_ir/src/ty_kind.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,11 @@ pub enum TyKind<I: Interner> {
202202
/// `ClosureArgs` for more details.
203203
Closure(I::DefId, I::GenericArgs),
204204

205-
/// TODO
205+
/// The anonymous type of a closure. Used to represent the type of `async |a| a`.
206+
///
207+
/// Coroutine-closure args contain both the - potentially substituted - generic
208+
/// parameters of its parent and some synthetic parameters. See the documentation
209+
/// for `CoroutineClosureArgs` for more details.
206210
CoroutineClosure(I::DefId, I::GenericArgs),
207211

208212
/// The anonymous type of a coroutine. Used to represent the type of

library/core/src/ops/async_function.rs

+19-2
Original file line numberDiff line numberDiff line change
@@ -108,9 +108,26 @@ mod impls {
108108
}
109109

110110
mod internal_implementation_detail {
111-
// TODO: needs a detailed explanation
111+
/// A helper trait that is used to enforce that the `ClosureKind` of a goal
112+
/// is within the capabilities of a `CoroutineClosure`, and which allows us
113+
/// to delay the projection of the tupled upvar types until after upvar
114+
/// analysis is complete.
115+
///
116+
/// The `Self` type is expected to be the `kind_ty` of the coroutine-closure,
117+
/// and thus either `?0` or `i8`/`i16`/`i32` (see docs for `ClosureKind`
118+
/// for an explanation of that). The `GoalKind` is also the same type, but
119+
/// representing the kind of the trait that the closure is being called with.
112120
#[cfg_attr(not(bootstrap), lang = "async_fn_kind_helper")]
113121
trait AsyncFnKindHelper<GoalKind> {
114-
type Assoc<'closure_env, Inputs, Upvars, BorrowedUpvarsAsFnPtr>;
122+
// Projects a set of closure inputs (arguments), a region, and a set of upvars
123+
// (by move and by ref) to the upvars that we expect the coroutine to have
124+
// according to the `GoalKind` parameter above.
125+
//
126+
// The `Upvars` parameter should be the upvars of the parent coroutine-closure,
127+
// and the `BorrowedUpvarsAsFnPtr` will be a function pointer that has the shape
128+
// `for<'env> fn() -> (&'env T, ...)`. This allows us to represent the binder
129+
// of the closure's self-capture, and these upvar types will be instantiated with
130+
// the `'closure_env` region provided to the associated type.
131+
type Upvars<'closure_env, Inputs, Upvars, BorrowedUpvarsAsFnPtr>;
115132
}
116133
}

tests/ui/async-await/async-borrowck-escaping-closure-error.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
// edition:2018
2-
// check-pass
32

43
#![feature(async_closure)]
54
fn foo() -> Box<dyn std::future::Future<Output = u32>> {
65
let x = 0u32;
76
Box::new((async || x)())
7+
//~^ ERROR cannot return value referencing local variable `x`
8+
//~| ERROR cannot return value referencing temporary value
89
}
910

1011
fn main() {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
error[E0515]: cannot return value referencing local variable `x`
2+
--> $DIR/async-borrowck-escaping-closure-error.rs:6:5
3+
|
4+
LL | Box::new((async || x)())
5+
| ^^^^^^^^^------------^^^
6+
| | |
7+
| | `x` is borrowed here
8+
| returns a value referencing data owned by the current function
9+
10+
error[E0515]: cannot return value referencing temporary value
11+
--> $DIR/async-borrowck-escaping-closure-error.rs:6:5
12+
|
13+
LL | Box::new((async || x)())
14+
| ^^^^^^^^^------------^^^
15+
| | |
16+
| | temporary value created here
17+
| returns a value referencing data owned by the current function
18+
19+
error: aborting due to 2 previous errors
20+
21+
For more information about this error, try `rustc --explain E0515`.
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
// edition:2021
2+
// check-pass
23

34
#![feature(async_closure)]
45

56
fn main() {
67
let x = async move |x: &str| {
7-
//~^ ERROR lifetime may not live long enough
8-
// This error is proof that the `&str` type is higher-ranked.
9-
// This won't work until async closures are fully impl'd.
108
println!("{x}");
119
};
1210
}

tests/ui/async-await/async-closures/higher-ranked.stderr

-17
This file was deleted.

0 commit comments

Comments
 (0)