2 use crate::hir::def_id::DefId;
4 use crate::infer::outlives::free_region_map::FreeRegionRelations;
5 use crate::infer::{self, InferCtxt, InferOk, TypeVariableOrigin, TypeVariableOriginKind};
6 use crate::traits::{self, PredicateObligation};
7 use crate::ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder, TypeVisitor};
8 use crate::ty::subst::{InternalSubsts, Kind, SubstsRef, UnpackedKind};
9 use crate::ty::{self, GenericParamDefKind, Ty, TyCtxt};
10 use crate::util::nodemap::DefIdMap;
11 use rustc_data_structures::fx::FxHashMap;
13 use syntax::source_map::Span;
15 pub type OpaqueTypeMap<'tcx> = DefIdMap<OpaqueTypeDecl<'tcx>>;
17 /// Information about the opaque, abstract types whose values we
18 /// are inferring in this function (these are the `impl Trait` that
19 /// appear in the return type).
20 #[derive(Copy, Clone, Debug)]
21 pub struct OpaqueTypeDecl<'tcx> {
22 /// The substitutions that we apply to the abstract that this
23 /// `impl Trait` desugars to. e.g., if:
25 /// fn foo<'a, 'b, T>() -> impl Trait<'a>
27 /// winds up desugared to:
29 /// abstract type Foo<'x, X>: Trait<'x>
30 /// fn foo<'a, 'b, T>() -> Foo<'a, T>
32 /// then `substs` would be `['a, T]`.
33 pub substs: SubstsRef<'tcx>,
35 /// The type variable that represents the value of the abstract type
36 /// that we require. In other words, after we compile this function,
37 /// we will be created a constraint like:
41 /// where `?C` is the value of this type variable. =) It may
42 /// naturally refer to the type and lifetime parameters in scope
43 /// in this function, though ultimately it should only reference
44 /// those that are arguments to `Foo` in the constraint above. (In
45 /// other words, `?C` should not include `'b`, even though it's a
46 /// lifetime parameter on `foo`.)
47 pub concrete_ty: Ty<'tcx>,
49 /// Returns `true` if the `impl Trait` bounds include region bounds.
50 /// For example, this would be true for:
52 /// fn foo<'a, 'b, 'c>() -> impl Trait<'c> + 'a + 'b
56 /// fn foo<'c>() -> impl Trait<'c>
58 /// unless `Trait` was declared like:
60 /// trait Trait<'c>: 'c
62 /// in which case it would be true.
64 /// This is used during regionck to decide whether we need to
65 /// impose any additional constraints to ensure that region
66 /// variables in `concrete_ty` wind up being constrained to
67 /// something from `substs` (or, at minimum, things that outlive
68 /// the fn body). (Ultimately, writeback is responsible for this
70 pub has_required_region_bounds: bool,
72 /// The origin of the existential type
73 pub origin: hir::ExistTyOrigin,
76 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
77 /// Replaces all opaque types in `value` with fresh inference variables
78 /// and creates appropriate obligations. For example, given the input:
80 /// impl Iterator<Item = impl Debug>
82 /// this method would create two type variables, `?0` and `?1`. It would
83 /// return the type `?0` but also the obligations:
85 /// ?0: Iterator<Item = ?1>
88 /// Moreover, it returns a `OpaqueTypeMap` that would map `?0` to
89 /// info about the `impl Iterator<..>` type and `?1` to info about
90 /// the `impl Debug` type.
94 /// - `parent_def_id` -- the `DefId` of the function in which the opaque type
96 /// - `body_id` -- the body-id with which the resulting obligations should
98 /// - `param_env` -- the in-scope parameter environment to be used for
100 /// - `value` -- the value within which we are instantiating opaque types
101 pub fn instantiate_opaque_types<T: TypeFoldable<'tcx>>(
103 parent_def_id: DefId,
105 param_env: ty::ParamEnv<'tcx>,
107 ) -> InferOk<'tcx, (T, OpaqueTypeMap<'tcx>)> {
109 "instantiate_opaque_types(value={:?}, parent_def_id={:?}, body_id={:?}, \
111 value, parent_def_id, body_id, param_env,
113 let mut instantiator = Instantiator {
118 opaque_types: Default::default(),
121 let value = instantiator.instantiate_opaque_types_in_map(value);
122 InferOk { value: (value, instantiator.opaque_types), obligations: instantiator.obligations }
125 /// Given the map `opaque_types` containing the existential `impl
126 /// Trait` types whose underlying, hidden types are being
127 /// inferred, this method adds constraints to the regions
128 /// appearing in those underlying hidden types to ensure that they
129 /// at least do not refer to random scopes within the current
130 /// function. These constraints are not (quite) sufficient to
131 /// guarantee that the regions are actually legal values; that
132 /// final condition is imposed after region inference is done.
136 /// Let's work through an example to explain how it works. Assume
137 /// the current function is as follows:
140 /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
143 /// Here, we have two `impl Trait` types whose values are being
144 /// inferred (the `impl Bar<'a>` and the `impl
145 /// Bar<'b>`). Conceptually, this is sugar for a setup where we
146 /// define underlying abstract types (`Foo1`, `Foo2`) and then, in
147 /// the return type of `foo`, we *reference* those definitions:
150 /// abstract type Foo1<'x>: Bar<'x>;
151 /// abstract type Foo2<'x>: Bar<'x>;
152 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
159 /// As indicating in the comments above, each of those references
160 /// is (in the compiler) basically a substitution (`substs`)
161 /// applied to the type of a suitable `def_id` (which identifies
162 /// `Foo1` or `Foo2`).
164 /// Now, at this point in compilation, what we have done is to
165 /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
166 /// fresh inference variables C1 and C2. We wish to use the values
167 /// of these variables to infer the underlying types of `Foo1` and
168 /// `Foo2`. That is, this gives rise to higher-order (pattern) unification
169 /// constraints like:
172 /// for<'a> (Foo1<'a> = C1)
173 /// for<'b> (Foo1<'b> = C2)
176 /// For these equation to be satisfiable, the types `C1` and `C2`
177 /// can only refer to a limited set of regions. For example, `C1`
178 /// can only refer to `'static` and `'a`, and `C2` can only refer
179 /// to `'static` and `'b`. The job of this function is to impose that
182 /// Up to this point, C1 and C2 are basically just random type
183 /// inference variables, and hence they may contain arbitrary
184 /// regions. In fact, it is fairly likely that they do! Consider
185 /// this possible definition of `foo`:
188 /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
193 /// Here, the values for the concrete types of the two impl
194 /// traits will include inference variables:
201 /// Ordinarily, the subtyping rules would ensure that these are
202 /// sufficiently large. But since `impl Bar<'a>` isn't a specific
203 /// type per se, we don't get such constraints by default. This
204 /// is where this function comes into play. It adds extra
205 /// constraints to ensure that all the regions which appear in the
206 /// inferred type are regions that could validly appear.
208 /// This is actually a bit of a tricky constraint in general. We
209 /// want to say that each variable (e.g., `'0`) can only take on
210 /// values that were supplied as arguments to the abstract type
211 /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
212 /// scope. We don't have a constraint quite of this kind in the current
217 /// We generally prefer to make us our `<=` constraints, since
218 /// they integrate best into the region solve. To do that, we find
219 /// the "minimum" of all the arguments that appear in the substs:
220 /// that is, some region which is less than all the others. In the
221 /// case of `Foo1<'a>`, that would be `'a` (it's the only choice,
222 /// after all). Then we apply that as a least bound to the
223 /// variables (e.g., `'a <= '0`).
225 /// In some cases, there is no minimum. Consider this example:
228 /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
231 /// Here we would report a more complex "in constraint", like `'r
232 /// in ['a, 'b, 'static]` (where `'r` is some regon appearing in
233 /// the hidden type).
235 /// # Constrain regions, not the hidden concrete type
237 /// Note that generating constraints on each region `Rc` is *not*
238 /// the same as generating an outlives constraint on `Tc` iself.
239 /// For example, if we had a function like this:
242 /// fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> {
246 /// // Equivalent to:
247 /// existential type FooReturn<'a, T>: Foo<'a>;
248 /// fn foo<'a, T>(..) -> FooReturn<'a, T> { .. }
251 /// then the hidden type `Tc` would be `(&'0 u32, T)` (where `'0`
252 /// is an inference variable). If we generated a constraint that
253 /// `Tc: 'a`, then this would incorrectly require that `T: 'a` --
254 /// but this is not necessary, because the existential type we
255 /// create will be allowed to reference `T`. So instead we just
256 /// generate a constraint that `'0: 'a`.
258 /// # The `free_region_relations` parameter
260 /// The `free_region_relations` argument is used to find the
261 /// "minimum" of the regions supplied to a given abstract type.
262 /// It must be a relation that can answer whether `'a <= 'b`,
263 /// where `'a` and `'b` are regions that appear in the "substs"
264 /// for the abstract type references (the `<'a>` in `Foo1<'a>`).
266 /// Note that we do not impose the constraints based on the
267 /// generic regions from the `Foo1` definition (e.g., `'x`). This
268 /// is because the constraints we are imposing here is basically
269 /// the concern of the one generating the constraining type C1,
270 /// which is the current function. It also means that we can
271 /// take "implied bounds" into account in some cases:
274 /// trait SomeTrait<'a, 'b> { }
275 /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. }
278 /// Here, the fact that `'b: 'a` is known only because of the
279 /// implied bounds from the `&'a &'b u32` parameter, and is not
280 /// "inherent" to the abstract type definition.
284 /// - `opaque_types` -- the map produced by `instantiate_opaque_types`
285 /// - `free_region_relations` -- something that can be used to relate
286 /// the free regions (`'a`) that appear in the impl trait.
287 pub fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(
289 opaque_types: &OpaqueTypeMap<'tcx>,
290 free_region_relations: &FRR,
292 debug!("constrain_opaque_types()");
294 for (&def_id, opaque_defn) in opaque_types {
295 self.constrain_opaque_type(def_id, opaque_defn, free_region_relations);
299 /// See `constrain_opaque_types` for docs
300 pub fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>(
303 opaque_defn: &OpaqueTypeDecl<'tcx>,
304 free_region_relations: &FRR,
306 debug!("constrain_opaque_type()");
307 debug!("constrain_opaque_type: def_id={:?}", def_id);
308 debug!("constrain_opaque_type: opaque_defn={:#?}", opaque_defn);
312 let concrete_ty = self.resolve_vars_if_possible(&opaque_defn.concrete_ty);
314 debug!("constrain_opaque_type: concrete_ty={:?}", concrete_ty);
316 let abstract_type_generics = tcx.generics_of(def_id);
318 let span = tcx.def_span(def_id);
320 // If there are required region bounds, we can use them.
321 if opaque_defn.has_required_region_bounds {
322 let predicates_of = tcx.predicates_of(def_id);
323 debug!("constrain_opaque_type: predicates: {:#?}", predicates_of,);
324 let bounds = predicates_of.instantiate(tcx, opaque_defn.substs);
325 debug!("constrain_opaque_type: bounds={:#?}", bounds);
326 let opaque_type = tcx.mk_opaque(def_id, opaque_defn.substs);
328 let required_region_bounds = tcx.required_region_bounds(opaque_type, bounds.predicates);
329 debug_assert!(!required_region_bounds.is_empty());
331 for required_region in required_region_bounds {
332 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
334 op: |r| self.sub_regions(infer::CallReturn(span), required_region, r),
340 // There were no `required_region_bounds`,
341 // so we have to search for a `least_region`.
342 // Go through all the regions used as arguments to the
343 // abstract type. These are the parameters to the abstract
344 // type; so in our example above, `substs` would contain
345 // `['a]` for the first impl trait and `'b` for the
347 let mut least_region = None;
348 for param in &abstract_type_generics.params {
350 GenericParamDefKind::Lifetime => {}
354 // Get the value supplied for this region from the substs.
355 let subst_arg = opaque_defn.substs.region_at(param.index as usize);
357 // Compute the least upper bound of it with the other regions.
358 debug!("constrain_opaque_types: least_region={:?}", least_region);
359 debug!("constrain_opaque_types: subst_arg={:?}", subst_arg);
361 None => least_region = Some(subst_arg),
363 if free_region_relations.sub_free_regions(lr, subst_arg) {
364 // keep the current least region
365 } else if free_region_relations.sub_free_regions(subst_arg, lr) {
366 // switch to `subst_arg`
367 least_region = Some(subst_arg);
369 // There are two regions (`lr` and
370 // `subst_arg`) which are not relatable. We
371 // can't find a best choice. Therefore,
372 // instead of creating a single bound like
373 // `'r: 'a` (which is our preferred choice),
374 // we will create a "in bound" like `'r in
375 // ['a, 'b, 'c]`, where `'a..'c` are the
376 // regions that appear in the impl trait.
377 return self.generate_in_constraint(
380 abstract_type_generics,
388 let least_region = least_region.unwrap_or(tcx.lifetimes.re_static);
389 debug!("constrain_opaque_types: least_region={:?}", least_region);
391 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
393 op: |r| self.sub_regions(infer::CallReturn(span), least_region, r),
397 /// As a fallback, we sometimes generate an "in constraint". For
398 /// case like `impl Foo<'a, 'b>`, where `'a` and `'b` cannot be
399 /// related, we would generate a constraint `'r in ['a, 'b,
400 /// 'static]` for each region `'r` that appears in the hidden type
401 /// (i.e., it must be equal to `'a`, `'b`, or `'static`).
402 fn generate_in_constraint(
405 concrete_ty: Ty<'tcx>,
406 abstract_type_generics: &ty::Generics,
407 opaque_defn: &OpaqueTypeDecl<'tcx>,
409 let in_regions: Rc<Vec<ty::Region<'tcx>>> = Rc::new(
410 abstract_type_generics
413 .filter(|param| match param.kind {
414 GenericParamDefKind::Lifetime => true,
415 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => false,
417 .map(|param| opaque_defn.substs.region_at(param.index as usize))
418 .chain(std::iter::once(self.tcx.lifetimes.re_static))
422 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
424 op: |r| self.pick_constraint(infer::CallReturn(span), r, &in_regions),
428 /// Given the fully resolved, instantiated type for an opaque
429 /// type, i.e., the value of an inference variable like C1 or C2
430 /// (*), computes the "definition type" for an abstract type
431 /// definition -- that is, the inferred value of `Foo1<'x>` or
432 /// `Foo2<'x>` that we would conceptually use in its definition:
434 /// abstract type Foo1<'x>: Bar<'x> = AAA; <-- this type AAA
435 /// abstract type Foo2<'x>: Bar<'x> = BBB; <-- or this type BBB
436 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
438 /// Note that these values are defined in terms of a distinct set of
439 /// generic parameters (`'x` instead of `'a`) from C1 or C2. The main
440 /// purpose of this function is to do that translation.
442 /// (*) C1 and C2 were introduced in the comments on
443 /// `constrain_opaque_types`. Read that comment for more context.
447 /// - `def_id`, the `impl Trait` type
449 /// - `opaque_defn`, the opaque definition created in `instantiate_opaque_types`
450 /// - `instantiated_ty`, the inferred type C1 -- fully resolved, lifted version of
451 /// `opaque_defn.concrete_ty`
452 pub fn infer_opaque_definition_from_instantiation(
455 opaque_defn: &OpaqueTypeDecl<'tcx>,
456 instantiated_ty: Ty<'tcx>,
459 "infer_opaque_definition_from_instantiation(def_id={:?}, instantiated_ty={:?})",
460 def_id, instantiated_ty
463 let gcx = self.tcx.global_tcx();
465 // Use substs to build up a reverse map from regions to their
466 // identity mappings. This is necessary because of `impl
467 // Trait` lifetimes are computed by replacing existing
468 // lifetimes with 'static and remapping only those used in the
469 // `impl Trait` return type, resulting in the parameters
471 let id_substs = InternalSubsts::identity_for_item(gcx, def_id);
472 let map: FxHashMap<Kind<'tcx>, Kind<'tcx>> = opaque_defn
476 .map(|(index, subst)| (*subst, id_substs[index]))
479 // Convert the type from the function into a type valid outside
480 // the function, by replacing invalid regions with 'static,
481 // after producing an error for each of them.
482 let definition_ty = instantiated_ty.fold_with(&mut ReverseMapper::new(
484 self.is_tainted_by_errors(),
489 debug!("infer_opaque_definition_from_instantiation: definition_ty={:?}", definition_ty);
495 // Visitor that requires that (almost) all regions in the type visited outlive
496 // `least_region`. We cannot use `push_outlives_components` because regions in
497 // closure signatures are not included in their outlives components. We need to
498 // ensure all regions outlive the given bound so that we don't end up with,
499 // say, `ReScope` appearing in a return type and causing ICEs when other
500 // functions end up with region constraints involving regions from other
503 // We also cannot use `for_each_free_region` because for closures it includes
504 // the regions parameters from the enclosing item.
506 // We ignore any type parameters because impl trait values are assumed to
507 // capture all the in-scope type parameters.
508 struct ConstrainOpaqueTypeRegionVisitor<'tcx, OP>
510 OP: FnMut(ty::Region<'tcx>),
516 impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<'tcx, OP>
518 OP: FnMut(ty::Region<'tcx>),
520 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool {
521 t.skip_binder().visit_with(self);
522 false // keep visiting
525 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
527 // ignore bound regions, keep visiting
528 ty::ReLateBound(_, _) => false,
536 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
537 // We're only interested in types involving regions
538 if !ty.flags.intersects(ty::TypeFlags::HAS_FREE_REGIONS) {
539 return false; // keep visiting
543 ty::Closure(def_id, ref substs) => {
544 // Skip lifetime parameters of the enclosing item(s)
546 for upvar_ty in substs.upvar_tys(def_id, self.tcx) {
547 upvar_ty.visit_with(self);
550 substs.closure_sig_ty(def_id, self.tcx).visit_with(self);
553 ty::Generator(def_id, ref substs, _) => {
554 // Skip lifetime parameters of the enclosing item(s)
555 // Also skip the witness type, because that has no free regions.
557 for upvar_ty in substs.upvar_tys(def_id, self.tcx) {
558 upvar_ty.visit_with(self);
561 substs.return_ty(def_id, self.tcx).visit_with(self);
562 substs.yield_ty(def_id, self.tcx).visit_with(self);
565 ty.super_visit_with(self);
573 struct ReverseMapper<'tcx> {
576 /// If errors have already been reported in this fn, we suppress
577 /// our own errors because they are sometimes derivative.
578 tainted_by_errors: bool,
580 opaque_type_def_id: DefId,
581 map: FxHashMap<Kind<'tcx>, Kind<'tcx>>,
582 map_missing_regions_to_empty: bool,
584 /// initially `Some`, set to `None` once error has been reported
585 hidden_ty: Option<Ty<'tcx>>,
588 impl ReverseMapper<'tcx> {
591 tainted_by_errors: bool,
592 opaque_type_def_id: DefId,
593 map: FxHashMap<Kind<'tcx>, Kind<'tcx>>,
601 map_missing_regions_to_empty: false,
602 hidden_ty: Some(hidden_ty),
606 fn fold_kind_mapping_missing_regions_to_empty(&mut self, kind: Kind<'tcx>) -> Kind<'tcx> {
607 assert!(!self.map_missing_regions_to_empty);
608 self.map_missing_regions_to_empty = true;
609 let kind = kind.fold_with(self);
610 self.map_missing_regions_to_empty = false;
614 fn fold_kind_normally(&mut self, kind: Kind<'tcx>) -> Kind<'tcx> {
615 assert!(!self.map_missing_regions_to_empty);
620 impl TypeFolder<'tcx> for ReverseMapper<'tcx> {
621 fn tcx(&self) -> TyCtxt<'tcx> {
625 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
627 // ignore bound regions that appear in the type (e.g., this
628 // would ignore `'r` in a type like `for<'r> fn(&'r u32)`.
629 ty::ReLateBound(..) |
631 // ignore `'static`, as that can appear anywhere
632 ty::ReStatic => return r,
637 match self.map.get(&r.into()).map(|k| k.unpack()) {
638 Some(UnpackedKind::Lifetime(r1)) => r1,
639 Some(u) => panic!("region mapped to unexpected kind: {:?}", u),
641 if !self.map_missing_regions_to_empty && !self.tainted_by_errors {
642 if let Some(hidden_ty) = self.hidden_ty.take() {
643 let span = self.tcx.def_span(self.opaque_type_def_id);
644 let mut err = struct_span_err!(
648 "hidden type for `impl Trait` captures lifetime that \
649 does not appear in bounds",
652 // Explain the region we are capturing.
654 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic | ty::ReEmpty => {
655 // Assuming regionck succeeded (*), we
656 // ought to always be capturing *some* region
657 // from the fn header, and hence it ought to
658 // be free. So under normal circumstances, we will
659 // go down this path which gives a decent human readable
662 // (*) if not, the `tainted_by_errors`
663 // flag would be set to true in any
664 // case, so we wouldn't be here at
666 self.tcx.note_and_explain_free_region(
668 &format!("hidden type `{}` captures ", hidden_ty),
674 // This case should not happen: it indicates that regionck
675 // failed to enforce an "in constraint".
676 err.note(&format!("hidden type `{}` captures `{:?}`", hidden_ty, r));
677 err.note(&format!("this is likely a bug in the compiler, please file an issue on github"));
684 self.tcx.lifetimes.re_empty
689 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
691 ty::Closure(def_id, substs) => {
692 // I am a horrible monster and I pray for death. When
693 // we encounter a closure here, it is always a closure
694 // from within the function that we are currently
695 // type-checking -- one that is now being encapsulated
696 // in an existential abstract type. Ideally, we would
697 // go through the types/lifetimes that it references
698 // and treat them just like we would any other type,
699 // which means we would error out if we find any
700 // reference to a type/region that is not in the
703 // **However,** in the case of closures, there is a
704 // somewhat subtle (read: hacky) consideration. The
705 // problem is that our closure types currently include
706 // all the lifetime parameters declared on the
707 // enclosing function, even if they are unused by the
708 // closure itself. We can't readily filter them out,
709 // so here we replace those values with `'empty`. This
710 // can't really make a difference to the rest of the
711 // compiler; those regions are ignored for the
712 // outlives relation, and hence don't affect trait
713 // selection or auto traits, and they are erased
716 let generics = self.tcx.generics_of(def_id);
718 self.tcx.mk_substs(substs.substs.iter().enumerate().map(|(index, &kind)| {
719 if index < generics.parent_count {
720 // Accommodate missing regions in the parent kinds...
721 self.fold_kind_mapping_missing_regions_to_empty(kind)
723 // ...but not elsewhere.
724 self.fold_kind_normally(kind)
728 self.tcx.mk_closure(def_id, ty::ClosureSubsts { substs })
731 ty::Generator(def_id, substs, movability) => {
732 let generics = self.tcx.generics_of(def_id);
734 self.tcx.mk_substs(substs.substs.iter().enumerate().map(|(index, &kind)| {
735 if index < generics.parent_count {
736 // Accommodate missing regions in the parent kinds...
737 self.fold_kind_mapping_missing_regions_to_empty(kind)
739 // ...but not elsewhere.
740 self.fold_kind_normally(kind)
744 self.tcx.mk_generator(def_id, ty::GeneratorSubsts { substs }, movability)
747 _ => ty.super_fold_with(self),
752 struct Instantiator<'a, 'tcx> {
753 infcx: &'a InferCtxt<'a, 'tcx>,
754 parent_def_id: DefId,
756 param_env: ty::ParamEnv<'tcx>,
757 opaque_types: OpaqueTypeMap<'tcx>,
758 obligations: Vec<PredicateObligation<'tcx>>,
761 impl<'a, 'tcx> Instantiator<'a, 'tcx> {
762 fn instantiate_opaque_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
763 debug!("instantiate_opaque_types_in_map(value={:?})", value);
764 let tcx = self.infcx.tcx;
765 value.fold_with(&mut BottomUpFolder {
768 if let ty::Opaque(def_id, substs) = ty.sty {
769 // Check that this is `impl Trait` type is
770 // declared by `parent_def_id` -- i.e., one whose
771 // value we are inferring. At present, this is
772 // always true during the first phase of
773 // type-check, but not always true later on during
774 // NLL. Once we support named abstract types more fully,
775 // this same scenario will be able to arise during all phases.
777 // Here is an example using `abstract type` that indicates
778 // the distinction we are checking for:
782 // pub abstract type Foo: Iterator;
783 // pub fn make_foo() -> Foo { .. }
787 // fn foo() -> a::Foo { a::make_foo() }
791 // Here, the return type of `foo` references a
792 // `Opaque` indeed, but not one whose value is
793 // presently being inferred. You can get into a
794 // similar situation with closure return types
798 // fn foo() -> impl Iterator { .. }
800 // let x = || foo(); // returns the Opaque assoc with `foo`
803 if let Some(opaque_hir_id) = tcx.hir().as_local_hir_id(def_id) {
804 let parent_def_id = self.parent_def_id;
805 let def_scope_default = || {
806 let opaque_parent_hir_id = tcx.hir().get_parent_item(opaque_hir_id);
808 == tcx.hir().local_def_id_from_hir_id(opaque_parent_hir_id)
810 let (in_definition_scope, origin) = match tcx.hir().find(opaque_hir_id) {
811 Some(Node::Item(item)) => match item.node {
812 // Anonymous `impl Trait`
813 hir::ItemKind::Existential(hir::ExistTy {
814 impl_trait_fn: Some(parent),
817 }) => (parent == self.parent_def_id, origin),
818 // Named `existential type`
819 hir::ItemKind::Existential(hir::ExistTy {
824 may_define_existential_type(
831 _ => (def_scope_default(), hir::ExistTyOrigin::ExistentialType),
833 Some(Node::ImplItem(item)) => match item.node {
834 hir::ImplItemKind::Existential(_) => (
835 may_define_existential_type(
840 hir::ExistTyOrigin::ExistentialType,
842 _ => (def_scope_default(), hir::ExistTyOrigin::ExistentialType),
845 "expected (impl) item, found {}",
846 tcx.hir().node_to_string(opaque_hir_id),
849 if in_definition_scope {
850 return self.fold_opaque_ty(ty, def_id, substs, origin);
854 "instantiate_opaque_types_in_map: \
855 encountered opaque outside its definition scope \
873 substs: SubstsRef<'tcx>,
874 origin: hir::ExistTyOrigin,
876 let infcx = self.infcx;
879 debug!("instantiate_opaque_types: Opaque(def_id={:?}, substs={:?})", def_id, substs);
881 // Use the same type variable if the exact same opaque type appears more
882 // than once in the return type (e.g., if it's passed to a type alias).
883 if let Some(opaque_defn) = self.opaque_types.get(&def_id) {
884 return opaque_defn.concrete_ty;
886 let span = tcx.def_span(def_id);
888 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
890 let predicates_of = tcx.predicates_of(def_id);
891 debug!("instantiate_opaque_types: predicates={:#?}", predicates_of,);
892 let bounds = predicates_of.instantiate(tcx, substs);
893 debug!("instantiate_opaque_types: bounds={:?}", bounds);
895 let required_region_bounds = tcx.required_region_bounds(ty, bounds.predicates.clone());
896 debug!("instantiate_opaque_types: required_region_bounds={:?}", required_region_bounds);
898 // Make sure that we are in fact defining the *entire* type
899 // (e.g., `existential type Foo<T: Bound>: Bar;` needs to be
900 // defined by a function like `fn foo<T: Bound>() -> Foo<T>`).
901 debug!("instantiate_opaque_types: param_env={:#?}", self.param_env,);
902 debug!("instantiate_opaque_types: generics={:#?}", tcx.generics_of(def_id),);
904 self.opaque_types.insert(
909 has_required_region_bounds: !required_region_bounds.is_empty(),
913 debug!("instantiate_opaque_types: ty_var={:?}", ty_var);
915 self.obligations.reserve(bounds.predicates.len());
916 for predicate in bounds.predicates {
917 // Change the predicate to refer to the type variable,
918 // which will be the concrete type instead of the opaque type.
919 // This also instantiates nested instances of `impl Trait`.
920 let predicate = self.instantiate_opaque_types_in_map(&predicate);
922 let cause = traits::ObligationCause::new(span, self.body_id, traits::SizedReturnType);
924 // Require that the predicate holds for the concrete type.
925 debug!("instantiate_opaque_types: predicate={:?}", predicate);
926 self.obligations.push(traits::Obligation::new(cause, self.param_env, predicate));
933 /// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`.
939 /// pub existential type Baz;
941 /// fn f1() -> Baz { .. }
944 /// fn f2() -> bar::Baz { .. }
948 /// Here, `def_id` is the `DefId` of the defining use of the existential type (e.g., `f1` or `f2`),
949 /// and `opaque_hir_id` is the `HirId` of the definition of the existential type `Baz`.
950 /// For the above example, this function returns `true` for `f1` and `false` for `f2`.
951 pub fn may_define_existential_type(
954 opaque_hir_id: hir::HirId,
956 let mut hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
958 "may_define_existential_type(def={:?}, opaque_node={:?})",
959 tcx.hir().get(hir_id),
960 tcx.hir().get(opaque_hir_id)
963 // Named existential types can be defined by any siblings or children of siblings.
964 let scope = tcx.hir().get_defining_scope(opaque_hir_id).expect("could not get defining scope");
965 // We walk up the node tree until we hit the root or the scope of the opaque type.
966 while hir_id != scope && hir_id != hir::CRATE_HIR_ID {
967 hir_id = tcx.hir().get_parent_item(hir_id);
969 // Syntactically, we are allowed to define the concrete type if: