rustc_type_ir/ty_kind/closure.rs
1use std::ops::ControlFlow;
2
3use derive_where::derive_where;
4use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic};
5
6use crate::data_structures::DelayedMap;
7use crate::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable, shift_region};
8use crate::inherent::*;
9use crate::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor};
10use crate::{self as ty, Interner};
11
12/// A closure can be modeled as a struct that looks like:
13/// ```ignore (illustrative)
14/// struct Closure<'l0...'li, T0...Tj, CK, CS, U>(...U);
15/// ```
16/// where:
17///
18/// - 'l0...'li and T0...Tj are the generic parameters
19/// in scope on the function that defined the closure,
20/// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
21/// is rather hackily encoded via a scalar type. See
22/// `Ty::to_opt_closure_kind` for details.
23/// - CS represents the *closure signature*, representing as a `fn()`
24/// type. For example, `fn(u32, u32) -> u32` would mean that the closure
25/// implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
26/// specified above.
27/// - U is a type parameter representing the types of its upvars, tupled up
28/// (borrowed, if appropriate; that is, if a U field represents a by-ref upvar,
29/// and the up-var has the type `Foo`, then that field of U will be `&Foo`).
30///
31/// So, for example, given this function:
32/// ```ignore (illustrative)
33/// fn foo<'a, T>(data: &'a mut T) {
34/// do(|| data.count += 1)
35/// }
36/// ```
37/// the type of the closure would be something like:
38/// ```ignore (illustrative)
39/// struct Closure<'a, T, U>(...U);
40/// ```
41/// Note that the type of the upvar is not specified in the struct.
42/// You may wonder how the impl would then be able to use the upvar,
43/// if it doesn't know it's type? The answer is that the impl is
44/// (conceptually) not fully generic over Closure but rather tied to
45/// instances with the expected upvar types:
46/// ```ignore (illustrative)
47/// impl<'b, 'a, T> FnMut() for Closure<'a, T, (&'b mut &'a mut T,)> {
48/// ...
49/// }
50/// ```
51/// You can see that the *impl* fully specified the type of the upvar
52/// and thus knows full well that `data` has type `&'b mut &'a mut T`.
53/// (Here, I am assuming that `data` is mut-borrowed.)
54///
55/// Now, the last question you may ask is: Why include the upvar types
56/// in an extra type parameter? The reason for this design is that the
57/// upvar types can reference lifetimes that are internal to the
58/// creating function. In my example above, for example, the lifetime
59/// `'b` represents the scope of the closure itself; this is some
60/// subset of `foo`, probably just the scope of the call to the to
61/// `do()`. If we just had the lifetime/type parameters from the
62/// enclosing function, we couldn't name this lifetime `'b`. Note that
63/// there can also be lifetimes in the types of the upvars themselves,
64/// if one of them happens to be a reference to something that the
65/// creating fn owns.
66///
67/// OK, you say, so why not create a more minimal set of parameters
68/// that just includes the extra lifetime parameters? The answer is
69/// primarily that it would be hard --- we don't know at the time when
70/// we create the closure type what the full types of the upvars are,
71/// nor do we know which are borrowed and which are not. In this
72/// design, we can just supply a fresh type parameter and figure that
73/// out later.
74///
75/// All right, you say, but why include the type parameters from the
76/// original function then? The answer is that codegen may need them
77/// when monomorphizing, and they may not appear in the upvars. A
78/// closure could capture no variables but still make use of some
79/// in-scope type parameter with a bound (e.g., if our example above
80/// had an extra `U: Default`, and the closure called `U::default()`).
81///
82/// There is another reason. This design (implicitly) prohibits
83/// closures from capturing themselves (except via a trait
84/// object). This simplifies closure inference considerably, since it
85/// means that when we infer the kind of a closure or its upvars, we
86/// don't have to handle cycles where the decisions we make for
87/// closure C wind up influencing the decisions we ought to make for
88/// closure C (which would then require fixed point iteration to
89/// handle). Plus it fixes an ICE. :P
90///
91/// ## Coroutines
92///
93/// Coroutines are handled similarly in `CoroutineArgs`. The set of
94/// type parameters is similar, but `CK` and `CS` are replaced by the
95/// following type parameters:
96///
97/// * `GS`: The coroutine's "resume type", which is the type of the
98/// argument passed to `resume`, and the type of `yield` expressions
99/// inside the coroutine.
100/// * `GY`: The "yield type", which is the type of values passed to
101/// `yield` inside the coroutine.
102/// * `GR`: The "return type", which is the type of value returned upon
103/// completion of the coroutine.
104#[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)]
105#[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)]
106pub struct ClosureArgs<I: Interner> {
107 /// Lifetime and type parameters from the enclosing function,
108 /// concatenated with a tuple containing the types of the upvars.
109 ///
110 /// These are separated out because codegen wants to pass them around
111 /// when monomorphizing.
112 pub args: I::GenericArgs,
113}
114
115/// Struct returned by `split()`.
116pub struct ClosureArgsParts<I: Interner> {
117 /// This is the args of the typeck root.
118 pub parent_args: I::GenericArgsSlice,
119 /// Represents the maximum calling capability of the closure.
120 pub closure_kind_ty: I::Ty,
121 /// Captures the closure's signature. This closure signature is "tupled", and
122 /// thus has a peculiar signature of `extern "rust-call" fn((Args, ...)) -> Ty`.
123 pub closure_sig_as_fn_ptr_ty: I::Ty,
124 /// The upvars captured by the closure. Remains an inference variable
125 /// until the upvar analysis, which happens late in HIR typeck.
126 pub tupled_upvars_ty: I::Ty,
127}
128
129impl<I: Interner> ClosureArgs<I> {
130 /// Construct `ClosureArgs` from `ClosureArgsParts`, containing `Args`
131 /// for the closure parent, alongside additional closure-specific components.
132 pub fn new(cx: I, parts: ClosureArgsParts<I>) -> ClosureArgs<I> {
133 ClosureArgs {
134 args: cx.mk_args_from_iter(parts.parent_args.iter().chain([
135 parts.closure_kind_ty.into(),
136 parts.closure_sig_as_fn_ptr_ty.into(),
137 parts.tupled_upvars_ty.into(),
138 ])),
139 }
140 }
141
142 /// Divides the closure args into their respective components.
143 /// The ordering assumed here must match that used by `ClosureArgs::new` above.
144 fn split(self) -> ClosureArgsParts<I> {
145 self.args.split_closure_args()
146 }
147
148 /// Returns the generic parameters of the closure's parent.
149 pub fn parent_args(self) -> I::GenericArgsSlice {
150 self.split().parent_args
151 }
152
153 /// Returns an iterator over the list of types of captured paths by the closure.
154 /// In case there was a type error in figuring out the types of the captured path, an
155 /// empty iterator is returned.
156 #[inline]
157 pub fn upvar_tys(self) -> I::Tys {
158 match self.tupled_upvars_ty().kind() {
159 ty::Error(_) => Default::default(),
160 ty::Tuple(tys) => tys,
161 ty::Infer(_) => panic!("upvar_tys called before capture types are inferred"),
162 ty => panic!("Unexpected representation of upvar types tuple {:?}", ty),
163 }
164 }
165
166 /// Returns the tuple type representing the upvars for this closure.
167 #[inline]
168 pub fn tupled_upvars_ty(self) -> I::Ty {
169 self.split().tupled_upvars_ty
170 }
171
172 /// Returns the closure kind for this closure; may return a type
173 /// variable during inference. To get the closure kind during
174 /// inference, use `infcx.closure_kind(args)`.
175 pub fn kind_ty(self) -> I::Ty {
176 self.split().closure_kind_ty
177 }
178
179 /// Returns the `fn` pointer type representing the closure signature for this
180 /// closure.
181 // FIXME(eddyb) this should be unnecessary, as the shallowly resolved
182 // type is known at the time of the creation of `ClosureArgs`,
183 // see `rustc_hir_analysis::check::closure`.
184 pub fn sig_as_fn_ptr_ty(self) -> I::Ty {
185 self.split().closure_sig_as_fn_ptr_ty
186 }
187
188 /// Returns the closure kind for this closure; only usable outside
189 /// of an inference context, because in that context we know that
190 /// there are no type variables.
191 ///
192 /// If you have an inference context, use `infcx.closure_kind()`.
193 pub fn kind(self) -> ty::ClosureKind {
194 self.kind_ty().to_opt_closure_kind().unwrap()
195 }
196
197 /// Extracts the signature from the closure.
198 pub fn sig(self) -> ty::Binder<I, ty::FnSig<I>> {
199 match self.sig_as_fn_ptr_ty().kind() {
200 ty::FnPtr(sig_tys, hdr) => sig_tys.with(hdr),
201 ty => panic!("closure_sig_as_fn_ptr_ty is not a fn-ptr: {ty:?}"),
202 }
203 }
204}
205
206#[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)]
207#[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)]
208pub struct CoroutineClosureArgs<I: Interner> {
209 pub args: I::GenericArgs,
210}
211
212/// See docs for explanation of how each argument is used.
213///
214/// See [`CoroutineClosureSignature`] for how these arguments are put together
215/// to make a callable [`ty::FnSig`] suitable for typeck and borrowck.
216pub struct CoroutineClosureArgsParts<I: Interner> {
217 /// This is the args of the typeck root.
218 pub parent_args: I::GenericArgsSlice,
219 /// Represents the maximum calling capability of the closure.
220 pub closure_kind_ty: I::Ty,
221 /// Represents all of the relevant parts of the coroutine returned by this
222 /// coroutine-closure. This signature parts type will have the general
223 /// shape of `fn(tupled_inputs, resume_ty) -> (return_ty, yield_ty)`, where
224 /// `resume_ty`, `return_ty`, and `yield_ty` are the respective types for the
225 /// coroutine returned by the coroutine-closure.
226 ///
227 /// Use `coroutine_closure_sig` to break up this type rather than using it
228 /// yourself.
229 pub signature_parts_ty: I::Ty,
230 /// The upvars captured by the closure. Remains an inference variable
231 /// until the upvar analysis, which happens late in HIR typeck.
232 pub tupled_upvars_ty: I::Ty,
233 /// a function pointer that has the shape `for<'env> fn() -> (&'env T, ...)`.
234 /// This allows us to represent the binder of the self-captures of the closure.
235 ///
236 /// For example, if the coroutine returned by the closure borrows `String`
237 /// from the closure's upvars, this will be `for<'env> fn() -> (&'env String,)`,
238 /// while the `tupled_upvars_ty`, representing the by-move version of the same
239 /// captures, will be `(String,)`.
240 pub coroutine_captures_by_ref_ty: I::Ty,
241}
242
243impl<I: Interner> CoroutineClosureArgs<I> {
244 pub fn new(cx: I, parts: CoroutineClosureArgsParts<I>) -> CoroutineClosureArgs<I> {
245 CoroutineClosureArgs {
246 args: cx.mk_args_from_iter(parts.parent_args.iter().chain([
247 parts.closure_kind_ty.into(),
248 parts.signature_parts_ty.into(),
249 parts.tupled_upvars_ty.into(),
250 parts.coroutine_captures_by_ref_ty.into(),
251 ])),
252 }
253 }
254
255 fn split(self) -> CoroutineClosureArgsParts<I> {
256 self.args.split_coroutine_closure_args()
257 }
258
259 pub fn parent_args(self) -> I::GenericArgsSlice {
260 self.split().parent_args
261 }
262
263 #[inline]
264 pub fn upvar_tys(self) -> I::Tys {
265 match self.tupled_upvars_ty().kind() {
266 ty::Error(_) => Default::default(),
267 ty::Tuple(..) => self.tupled_upvars_ty().tuple_fields(),
268 ty::Infer(_) => panic!("upvar_tys called before capture types are inferred"),
269 ty => panic!("Unexpected representation of upvar types tuple {:?}", ty),
270 }
271 }
272
273 #[inline]
274 pub fn tupled_upvars_ty(self) -> I::Ty {
275 self.split().tupled_upvars_ty
276 }
277
278 pub fn kind_ty(self) -> I::Ty {
279 self.split().closure_kind_ty
280 }
281
282 pub fn kind(self) -> ty::ClosureKind {
283 self.kind_ty().to_opt_closure_kind().unwrap()
284 }
285
286 pub fn signature_parts_ty(self) -> I::Ty {
287 self.split().signature_parts_ty
288 }
289
290 pub fn coroutine_closure_sig(self) -> ty::Binder<I, CoroutineClosureSignature<I>> {
291 let ty::FnPtr(sig_tys, hdr) = self.signature_parts_ty().kind() else { panic!() };
292 sig_tys.map_bound(|sig_tys| {
293 let [resume_ty, tupled_inputs_ty] = *sig_tys.inputs().as_slice() else {
294 panic!();
295 };
296 let [yield_ty, return_ty] = *sig_tys.output().tuple_fields().as_slice() else {
297 panic!()
298 };
299 CoroutineClosureSignature {
300 tupled_inputs_ty,
301 resume_ty,
302 yield_ty,
303 return_ty,
304 c_variadic: hdr.c_variadic,
305 safety: hdr.safety,
306 abi: hdr.abi,
307 }
308 })
309 }
310
311 pub fn coroutine_captures_by_ref_ty(self) -> I::Ty {
312 self.split().coroutine_captures_by_ref_ty
313 }
314
315 pub fn has_self_borrows(&self) -> bool {
316 match self.coroutine_captures_by_ref_ty().kind() {
317 ty::FnPtr(sig_tys, _) => sig_tys
318 .skip_binder()
319 .visit_with(&mut HasRegionsBoundAt { binder: ty::INNERMOST })
320 .is_break(),
321 ty::Error(_) => true,
322 _ => panic!(),
323 }
324 }
325}
326
327/// Unlike `has_escaping_bound_vars` or `outermost_exclusive_binder`, this will
328/// detect only regions bound *at* the debruijn index.
329struct HasRegionsBoundAt {
330 binder: ty::DebruijnIndex,
331}
332// FIXME: Could be optimized to not walk into components with no escaping bound vars.
333impl<I: Interner> TypeVisitor<I> for HasRegionsBoundAt {
334 type Result = ControlFlow<()>;
335 fn visit_binder<T: TypeVisitable<I>>(&mut self, t: &ty::Binder<I, T>) -> Self::Result {
336 self.binder.shift_in(1);
337 t.super_visit_with(self)?;
338 self.binder.shift_out(1);
339 ControlFlow::Continue(())
340 }
341
342 fn visit_region(&mut self, r: I::Region) -> Self::Result {
343 if matches!(r.kind(), ty::ReBound(binder, _) if self.binder == binder) {
344 ControlFlow::Break(())
345 } else {
346 ControlFlow::Continue(())
347 }
348 }
349}
350
351#[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)]
352#[derive(TypeVisitable_Generic, TypeFoldable_Generic)]
353pub struct CoroutineClosureSignature<I: Interner> {
354 pub tupled_inputs_ty: I::Ty,
355 pub resume_ty: I::Ty,
356 pub yield_ty: I::Ty,
357 pub return_ty: I::Ty,
358
359 // Like the `fn_sig_as_fn_ptr_ty` of a regular closure, these types
360 // never actually differ. But we save them rather than recreating them
361 // from scratch just for good measure.
362 /// Always false
363 pub c_variadic: bool,
364 /// Always `Normal` (safe)
365 #[type_visitable(ignore)]
366 #[type_foldable(identity)]
367 pub safety: I::Safety,
368 /// Always `RustCall`
369 #[type_visitable(ignore)]
370 #[type_foldable(identity)]
371 pub abi: I::Abi,
372}
373
374impl<I: Interner> CoroutineClosureSignature<I> {
375 /// Construct a coroutine from the closure signature. Since a coroutine signature
376 /// is agnostic to the type of generator that is returned (by-ref/by-move),
377 /// the caller must specify what "flavor" of generator that they'd like to
378 /// create. Additionally, they must manually compute the upvars of the closure.
379 ///
380 /// This helper is not really meant to be used directly except for early on
381 /// during typeck, when we want to put inference vars into the kind and upvars tys.
382 /// When the kind and upvars are known, use the other helper functions.
383 pub fn to_coroutine(
384 self,
385 cx: I,
386 parent_args: I::GenericArgsSlice,
387 coroutine_kind_ty: I::Ty,
388 coroutine_def_id: I::DefId,
389 tupled_upvars_ty: I::Ty,
390 ) -> I::Ty {
391 let coroutine_args = ty::CoroutineArgs::new(
392 cx,
393 ty::CoroutineArgsParts {
394 parent_args,
395 kind_ty: coroutine_kind_ty,
396 resume_ty: self.resume_ty,
397 yield_ty: self.yield_ty,
398 return_ty: self.return_ty,
399 tupled_upvars_ty,
400 },
401 );
402
403 Ty::new_coroutine(cx, coroutine_def_id, coroutine_args.args)
404 }
405
406 /// Given known upvars and a [`ClosureKind`](ty::ClosureKind), compute the coroutine
407 /// returned by that corresponding async fn trait.
408 ///
409 /// This function expects the upvars to have been computed already, and doesn't check
410 /// that the `ClosureKind` is actually supported by the coroutine-closure.
411 pub fn to_coroutine_given_kind_and_upvars(
412 self,
413 cx: I,
414 parent_args: I::GenericArgsSlice,
415 coroutine_def_id: I::DefId,
416 goal_kind: ty::ClosureKind,
417 env_region: I::Region,
418 closure_tupled_upvars_ty: I::Ty,
419 coroutine_captures_by_ref_ty: I::Ty,
420 ) -> I::Ty {
421 let tupled_upvars_ty = Self::tupled_upvars_by_closure_kind(
422 cx,
423 goal_kind,
424 self.tupled_inputs_ty,
425 closure_tupled_upvars_ty,
426 coroutine_captures_by_ref_ty,
427 env_region,
428 );
429
430 self.to_coroutine(
431 cx,
432 parent_args,
433 Ty::from_coroutine_closure_kind(cx, goal_kind),
434 coroutine_def_id,
435 tupled_upvars_ty,
436 )
437 }
438
439 /// Compute the tupled upvars that a coroutine-closure's output coroutine
440 /// would return for the given `ClosureKind`.
441 ///
442 /// When `ClosureKind` is `FnMut`/`Fn`, then this will use the "captures by ref"
443 /// to return a set of upvars which are borrowed with the given `env_region`.
444 ///
445 /// This ensures that the `AsyncFn::call` will return a coroutine whose upvars'
446 /// lifetimes are related to the lifetime of the borrow on the closure made for
447 /// the call. This allows borrowck to enforce the self-borrows correctly.
448 pub fn tupled_upvars_by_closure_kind(
449 cx: I,
450 kind: ty::ClosureKind,
451 tupled_inputs_ty: I::Ty,
452 closure_tupled_upvars_ty: I::Ty,
453 coroutine_captures_by_ref_ty: I::Ty,
454 env_region: I::Region,
455 ) -> I::Ty {
456 match kind {
457 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
458 let ty::FnPtr(sig_tys, _) = coroutine_captures_by_ref_ty.kind() else {
459 panic!();
460 };
461 let coroutine_captures_by_ref_ty =
462 sig_tys.output().skip_binder().fold_with(&mut FoldEscapingRegions {
463 interner: cx,
464 region: env_region,
465 debruijn: ty::INNERMOST,
466 cache: Default::default(),
467 });
468 Ty::new_tup_from_iter(
469 cx,
470 tupled_inputs_ty
471 .tuple_fields()
472 .iter()
473 .chain(coroutine_captures_by_ref_ty.tuple_fields().iter()),
474 )
475 }
476 ty::ClosureKind::FnOnce => Ty::new_tup_from_iter(
477 cx,
478 tupled_inputs_ty
479 .tuple_fields()
480 .iter()
481 .chain(closure_tupled_upvars_ty.tuple_fields().iter()),
482 ),
483 }
484 }
485}
486
487/// Instantiates a `for<'env> ...` binder with a specific region.
488// FIXME(async_closures): Get rid of this in favor of `BoundVarReplacerDelegate`
489// when that is uplifted.
490struct FoldEscapingRegions<I: Interner> {
491 interner: I,
492 debruijn: ty::DebruijnIndex,
493 region: I::Region,
494
495 // Depends on `debruijn` because we may have types with regions of different
496 // debruijn depths depending on the binders we've entered.
497 cache: DelayedMap<(ty::DebruijnIndex, I::Ty), I::Ty>,
498}
499
500impl<I: Interner> TypeFolder<I> for FoldEscapingRegions<I> {
501 fn cx(&self) -> I {
502 self.interner
503 }
504
505 fn fold_ty(&mut self, t: I::Ty) -> I::Ty {
506 if !t.has_vars_bound_at_or_above(self.debruijn) {
507 t
508 } else if let Some(&t) = self.cache.get(&(self.debruijn, t)) {
509 t
510 } else {
511 let res = t.super_fold_with(self);
512 assert!(self.cache.insert((self.debruijn, t), res));
513 res
514 }
515 }
516
517 fn fold_binder<T>(&mut self, t: ty::Binder<I, T>) -> ty::Binder<I, T>
518 where
519 T: TypeFoldable<I>,
520 {
521 self.debruijn.shift_in(1);
522 let result = t.super_fold_with(self);
523 self.debruijn.shift_out(1);
524 result
525 }
526
527 fn fold_region(&mut self, r: <I as Interner>::Region) -> <I as Interner>::Region {
528 if let ty::ReBound(debruijn, _) = r.kind() {
529 assert!(
530 debruijn <= self.debruijn,
531 "cannot instantiate binder with escaping bound vars"
532 );
533 if self.debruijn == debruijn {
534 shift_region(self.interner, self.region, self.debruijn.as_u32())
535 } else {
536 r
537 }
538 } else {
539 r
540 }
541 }
542}
543
544#[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)]
545#[derive(TypeVisitable_Generic, TypeFoldable_Generic)]
546pub struct GenSig<I: Interner> {
547 pub resume_ty: I::Ty,
548 pub yield_ty: I::Ty,
549 pub return_ty: I::Ty,
550}
551
552/// Similar to `ClosureArgs`; see the above documentation for more.
553#[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)]
554#[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)]
555pub struct CoroutineArgs<I: Interner> {
556 pub args: I::GenericArgs,
557}
558
559pub struct CoroutineArgsParts<I: Interner> {
560 /// This is the args of the typeck root.
561 pub parent_args: I::GenericArgsSlice,
562
563 /// The coroutines returned by a coroutine-closure's `AsyncFnOnce`/`AsyncFnMut`
564 /// implementations must be distinguished since the former takes the closure's
565 /// upvars by move, and the latter takes the closure's upvars by ref.
566 ///
567 /// This field distinguishes these fields so that codegen can select the right
568 /// body for the coroutine. This has the same type representation as the closure
569 /// kind: `i8`/`i16`/`i32`.
570 ///
571 /// For regular coroutines, this field will always just be `()`.
572 pub kind_ty: I::Ty,
573
574 pub resume_ty: I::Ty,
575 pub yield_ty: I::Ty,
576 pub return_ty: I::Ty,
577
578 /// The upvars captured by the closure. Remains an inference variable
579 /// until the upvar analysis, which happens late in HIR typeck.
580 pub tupled_upvars_ty: I::Ty,
581}
582
583impl<I: Interner> CoroutineArgs<I> {
584 /// Construct `CoroutineArgs` from `CoroutineArgsParts`, containing `Args`
585 /// for the coroutine parent, alongside additional coroutine-specific components.
586 pub fn new(cx: I, parts: CoroutineArgsParts<I>) -> CoroutineArgs<I> {
587 CoroutineArgs {
588 args: cx.mk_args_from_iter(parts.parent_args.iter().chain([
589 parts.kind_ty.into(),
590 parts.resume_ty.into(),
591 parts.yield_ty.into(),
592 parts.return_ty.into(),
593 parts.tupled_upvars_ty.into(),
594 ])),
595 }
596 }
597
598 /// Divides the coroutine args into their respective components.
599 /// The ordering assumed here must match that used by `CoroutineArgs::new` above.
600 fn split(self) -> CoroutineArgsParts<I> {
601 self.args.split_coroutine_args()
602 }
603
604 /// Returns the generic parameters of the coroutine's parent.
605 pub fn parent_args(self) -> I::GenericArgsSlice {
606 self.split().parent_args
607 }
608
609 // Returns the kind of the coroutine. See docs on the `kind_ty` field.
610 pub fn kind_ty(self) -> I::Ty {
611 self.split().kind_ty
612 }
613
614 /// Returns an iterator over the list of types of captured paths by the coroutine.
615 /// In case there was a type error in figuring out the types of the captured path, an
616 /// empty iterator is returned.
617 #[inline]
618 pub fn upvar_tys(self) -> I::Tys {
619 match self.tupled_upvars_ty().kind() {
620 ty::Error(_) => Default::default(),
621 ty::Tuple(tys) => tys,
622 ty::Infer(_) => panic!("upvar_tys called before capture types are inferred"),
623 ty => panic!("Unexpected representation of upvar types tuple {:?}", ty),
624 }
625 }
626
627 /// Returns the tuple type representing the upvars for this coroutine.
628 #[inline]
629 pub fn tupled_upvars_ty(self) -> I::Ty {
630 self.split().tupled_upvars_ty
631 }
632
633 /// Returns the type representing the resume type of the coroutine.
634 pub fn resume_ty(self) -> I::Ty {
635 self.split().resume_ty
636 }
637
638 /// Returns the type representing the yield type of the coroutine.
639 pub fn yield_ty(self) -> I::Ty {
640 self.split().yield_ty
641 }
642
643 /// Returns the type representing the return type of the coroutine.
644 pub fn return_ty(self) -> I::Ty {
645 self.split().return_ty
646 }
647
648 /// Returns the "coroutine signature", which consists of its resume, yield
649 /// and return types.
650 pub fn sig(self) -> GenSig<I> {
651 let parts = self.split();
652 GenSig { resume_ty: parts.resume_ty, yield_ty: parts.yield_ty, return_ty: parts.return_ty }
653 }
654}