1 use rustc_data_structures::fx::FxHashMap;
4 use crate::hir::def_id::DefId;
7 use crate::infer::{self, InferCtxt, InferOk, TypeVariableOrigin, TypeVariableOriginKind};
8 use crate::infer::outlives::free_region_map::FreeRegionRelations;
9 use crate::traits::{self, PredicateObligation};
10 use crate::ty::{self, Ty, TyCtxt, GenericParamDefKind};
11 use crate::ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder, TypeVisitor};
12 use crate::ty::subst::{Kind, InternalSubsts, SubstsRef, UnpackedKind};
13 use crate::util::nodemap::DefIdMap;
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>)> {
108 debug!("instantiate_opaque_types(value={:?}, parent_def_id={:?}, body_id={:?}, \
110 value, parent_def_id, body_id, param_env,
112 let mut instantiator = Instantiator {
117 opaque_types: Default::default(),
120 let value = instantiator.instantiate_opaque_types_in_map(value);
122 value: (value, instantiator.opaque_types),
123 obligations: instantiator.obligations,
127 /// Given the map `opaque_types` containing the existential `impl
128 /// Trait` types whose underlying, hidden types are being
129 /// inferred, this method adds constraints to the regions
130 /// appearing in those underlying hidden types to ensure that they
131 /// at least do not refer to random scopes within the current
132 /// function. These constraints are not (quite) sufficient to
133 /// guarantee that the regions are actually legal values; that
134 /// final condition is imposed after region inference is done.
138 /// Let's work through an example to explain how it works. Assume
139 /// the current function is as follows:
142 /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
145 /// Here, we have two `impl Trait` types whose values are being
146 /// inferred (the `impl Bar<'a>` and the `impl
147 /// Bar<'b>`). Conceptually, this is sugar for a setup where we
148 /// define underlying abstract types (`Foo1`, `Foo2`) and then, in
149 /// the return type of `foo`, we *reference* those definitions:
152 /// abstract type Foo1<'x>: Bar<'x>;
153 /// abstract type Foo2<'x>: Bar<'x>;
154 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
161 /// As indicating in the comments above, each of those references
162 /// is (in the compiler) basically a substitution (`substs`)
163 /// applied to the type of a suitable `def_id` (which identifies
164 /// `Foo1` or `Foo2`).
166 /// Now, at this point in compilation, what we have done is to
167 /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
168 /// fresh inference variables C1 and C2. We wish to use the values
169 /// of these variables to infer the underlying types of `Foo1` and
170 /// `Foo2`. That is, this gives rise to higher-order (pattern) unification
171 /// constraints like:
174 /// for<'a> (Foo1<'a> = C1)
175 /// for<'b> (Foo1<'b> = C2)
178 /// For these equation to be satisfiable, the types `C1` and `C2`
179 /// can only refer to a limited set of regions. For example, `C1`
180 /// can only refer to `'static` and `'a`, and `C2` can only refer
181 /// to `'static` and `'b`. The job of this function is to impose that
184 /// Up to this point, C1 and C2 are basically just random type
185 /// inference variables, and hence they may contain arbitrary
186 /// regions. In fact, it is fairly likely that they do! Consider
187 /// this possible definition of `foo`:
190 /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
195 /// Here, the values for the concrete types of the two impl
196 /// traits will include inference variables:
203 /// Ordinarily, the subtyping rules would ensure that these are
204 /// sufficiently large. But since `impl Bar<'a>` isn't a specific
205 /// type per se, we don't get such constraints by default. This
206 /// is where this function comes into play. It adds extra
207 /// constraints to ensure that all the regions which appear in the
208 /// inferred type are regions that could validly appear.
210 /// This is actually a bit of a tricky constraint in general. We
211 /// want to say that each variable (e.g., `'0`) can only take on
212 /// values that were supplied as arguments to the abstract type
213 /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
214 /// scope. We don't have a constraint quite of this kind in the current
219 /// We make use of the constraint that we *do* have in the `<=`
220 /// relation. To do that, we find the "minimum" of all the
221 /// arguments that appear in the substs: that is, some region
222 /// which is less than all the others. In the case of `Foo1<'a>`,
223 /// that would be `'a` (it's the only choice, after all). Then we
224 /// apply that as a least bound to the variables (e.g., `'a <=
227 /// In some cases, there is no minimum. Consider this example:
230 /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
233 /// Here we would report an error, because `'a` and `'b` have no
234 /// relation to one another.
236 /// # The `free_region_relations` parameter
238 /// The `free_region_relations` argument is used to find the
239 /// "minimum" of the regions supplied to a given abstract type.
240 /// It must be a relation that can answer whether `'a <= 'b`,
241 /// where `'a` and `'b` are regions that appear in the "substs"
242 /// for the abstract type references (the `<'a>` in `Foo1<'a>`).
244 /// Note that we do not impose the constraints based on the
245 /// generic regions from the `Foo1` definition (e.g., `'x`). This
246 /// is because the constraints we are imposing here is basically
247 /// the concern of the one generating the constraining type C1,
248 /// which is the current function. It also means that we can
249 /// take "implied bounds" into account in some cases:
252 /// trait SomeTrait<'a, 'b> { }
253 /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. }
256 /// Here, the fact that `'b: 'a` is known only because of the
257 /// implied bounds from the `&'a &'b u32` parameter, and is not
258 /// "inherent" to the abstract type definition.
262 /// - `opaque_types` -- the map produced by `instantiate_opaque_types`
263 /// - `free_region_relations` -- something that can be used to relate
264 /// the free regions (`'a`) that appear in the impl trait.
265 pub fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(
267 opaque_types: &OpaqueTypeMap<'tcx>,
268 free_region_relations: &FRR,
270 debug!("constrain_opaque_types()");
272 for (&def_id, opaque_defn) in opaque_types {
273 self.constrain_opaque_type(def_id, opaque_defn, free_region_relations);
277 pub fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>(
280 opaque_defn: &OpaqueTypeDecl<'tcx>,
281 free_region_relations: &FRR,
283 debug!("constrain_opaque_type()");
284 debug!("constrain_opaque_type: def_id={:?}", def_id);
285 debug!("constrain_opaque_type: opaque_defn={:#?}", opaque_defn);
289 let concrete_ty = self.resolve_vars_if_possible(&opaque_defn.concrete_ty);
291 debug!("constrain_opaque_type: concrete_ty={:?}", concrete_ty);
293 let abstract_type_generics = tcx.generics_of(def_id);
295 let span = tcx.def_span(def_id);
297 // If there are required region bounds, we can use them.
298 if opaque_defn.has_required_region_bounds {
299 let predicates_of = tcx.predicates_of(def_id);
301 "constrain_opaque_type: predicates: {:#?}",
304 let bounds = predicates_of.instantiate(tcx, opaque_defn.substs);
305 debug!("constrain_opaque_type: bounds={:#?}", bounds);
306 let opaque_type = tcx.mk_opaque(def_id, opaque_defn.substs);
308 let required_region_bounds = tcx.required_region_bounds(
312 debug_assert!(!required_region_bounds.is_empty());
314 for region in required_region_bounds {
315 concrete_ty.visit_with(&mut OpaqueTypeOutlivesVisitor {
317 least_region: region,
324 // There were no `required_region_bounds`,
325 // so we have to search for a `least_region`.
326 // Go through all the regions used as arguments to the
327 // abstract type. These are the parameters to the abstract
328 // type; so in our example above, `substs` would contain
329 // `['a]` for the first impl trait and `'b` for the
331 let mut least_region = None;
332 for param in &abstract_type_generics.params {
334 GenericParamDefKind::Lifetime => {}
337 // Get the value supplied for this region from the substs.
338 let subst_arg = opaque_defn.substs.region_at(param.index as usize);
340 // Compute the least upper bound of it with the other regions.
341 debug!("constrain_opaque_types: least_region={:?}", least_region);
342 debug!("constrain_opaque_types: subst_arg={:?}", subst_arg);
344 None => least_region = Some(subst_arg),
346 if free_region_relations.sub_free_regions(lr, subst_arg) {
347 // keep the current least region
348 } else if free_region_relations.sub_free_regions(subst_arg, lr) {
349 // switch to `subst_arg`
350 least_region = Some(subst_arg);
352 // There are two regions (`lr` and
353 // `subst_arg`) which are not relatable. We can't
354 // find a best choice.
355 let context_name = match opaque_defn.origin {
356 hir::ExistTyOrigin::ExistentialType => "existential type",
357 hir::ExistTyOrigin::ReturnImplTrait => "impl Trait",
358 hir::ExistTyOrigin::AsyncFn => "async fn",
360 let msg = format!("ambiguous lifetime bound in `{}`", context_name);
361 let mut err = self.tcx
363 .struct_span_err(span, &msg);
365 let lr_name = lr.to_string();
366 let subst_arg_name = subst_arg.to_string();
368 let label = match (&*lr_name, &*subst_arg_name) {
369 ("'_", "'_") => "the elided lifetimes here do not outlive one another",
371 label_owned = format!(
372 "neither `{}` nor `{}` outlives the other",
379 err.span_label(span, label);
381 if let hir::ExistTyOrigin::AsyncFn = opaque_defn.origin {
382 err.note("multiple unrelated lifetimes are not allowed in \
384 err.note("if you're using argument-position elided lifetimes, consider \
385 switching to a single named lifetime.");
389 least_region = Some(self.tcx.mk_region(ty::ReEmpty));
396 let least_region = least_region.unwrap_or(tcx.lifetimes.re_static);
397 debug!("constrain_opaque_types: least_region={:?}", least_region);
399 concrete_ty.visit_with(&mut OpaqueTypeOutlivesVisitor {
406 /// Given the fully resolved, instantiated type for an opaque
407 /// type, i.e., the value of an inference variable like C1 or C2
408 /// (*), computes the "definition type" for an abstract type
409 /// definition -- that is, the inferred value of `Foo1<'x>` or
410 /// `Foo2<'x>` that we would conceptually use in its definition:
412 /// abstract type Foo1<'x>: Bar<'x> = AAA; <-- this type AAA
413 /// abstract type Foo2<'x>: Bar<'x> = BBB; <-- or this type BBB
414 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
416 /// Note that these values are defined in terms of a distinct set of
417 /// generic parameters (`'x` instead of `'a`) from C1 or C2. The main
418 /// purpose of this function is to do that translation.
420 /// (*) C1 and C2 were introduced in the comments on
421 /// `constrain_opaque_types`. Read that comment for more context.
425 /// - `def_id`, the `impl Trait` type
426 /// - `opaque_defn`, the opaque definition created in `instantiate_opaque_types`
427 /// - `instantiated_ty`, the inferred type C1 -- fully resolved, lifted version of
428 /// `opaque_defn.concrete_ty`
429 pub fn infer_opaque_definition_from_instantiation(
432 opaque_defn: &OpaqueTypeDecl<'tcx>,
433 instantiated_ty: Ty<'tcx>,
436 "infer_opaque_definition_from_instantiation(def_id={:?}, instantiated_ty={:?})",
437 def_id, instantiated_ty
440 let gcx = self.tcx.global_tcx();
442 // Use substs to build up a reverse map from regions to their
443 // identity mappings. This is necessary because of `impl
444 // Trait` lifetimes are computed by replacing existing
445 // lifetimes with 'static and remapping only those used in the
446 // `impl Trait` return type, resulting in the parameters
448 let id_substs = InternalSubsts::identity_for_item(gcx, def_id);
449 let map: FxHashMap<Kind<'tcx>, Kind<'tcx>> = opaque_defn
453 .map(|(index, subst)| (*subst, id_substs[index]))
456 // Convert the type from the function into a type valid outside
457 // the function, by replacing invalid regions with 'static,
458 // after producing an error for each of them.
460 instantiated_ty.fold_with(&mut ReverseMapper::new(
462 self.is_tainted_by_errors(),
468 "infer_opaque_definition_from_instantiation: definition_ty={:?}",
476 // Visitor that requires that (almost) all regions in the type visited outlive
477 // `least_region`. We cannot use `push_outlives_components` because regions in
478 // closure signatures are not included in their outlives components. We need to
479 // ensure all regions outlive the given bound so that we don't end up with,
480 // say, `ReScope` appearing in a return type and causing ICEs when other
481 // functions end up with region constraints involving regions from other
484 // We also cannot use `for_each_free_region` because for closures it includes
485 // the regions parameters from the enclosing item.
487 // We ignore any type parameters because impl trait values are assumed to
488 // capture all the in-scope type parameters.
489 struct OpaqueTypeOutlivesVisitor<'a, 'tcx> {
490 infcx: &'a InferCtxt<'a, 'tcx>,
491 least_region: ty::Region<'tcx>,
495 impl<'tcx> TypeVisitor<'tcx> for OpaqueTypeOutlivesVisitor<'_, 'tcx> {
496 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool {
497 t.skip_binder().visit_with(self);
498 false // keep visiting
501 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
503 // ignore bound regions, keep visiting
504 ty::ReLateBound(_, _) => false,
506 self.infcx.sub_regions(infer::CallReturn(self.span), self.least_region, r);
512 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
513 // We're only interested in types involving regions
514 if !ty.flags.intersects(ty::TypeFlags::HAS_FREE_REGIONS) {
515 return false; // keep visiting
519 ty::Closure(def_id, ref substs) => {
520 // Skip lifetime parameters of the enclosing item(s)
522 for upvar_ty in substs.upvar_tys(def_id, self.infcx.tcx) {
523 upvar_ty.visit_with(self);
526 substs.closure_sig_ty(def_id, self.infcx.tcx).visit_with(self);
529 ty::Generator(def_id, ref substs, _) => {
530 // Skip lifetime parameters of the enclosing item(s)
531 // Also skip the witness type, because that has no free regions.
533 for upvar_ty in substs.upvar_tys(def_id, self.infcx.tcx) {
534 upvar_ty.visit_with(self);
537 substs.return_ty(def_id, self.infcx.tcx).visit_with(self);
538 substs.yield_ty(def_id, self.infcx.tcx).visit_with(self);
541 ty.super_visit_with(self);
549 struct ReverseMapper<'tcx> {
552 /// If errors have already been reported in this fn, we suppress
553 /// our own errors because they are sometimes derivative.
554 tainted_by_errors: bool,
556 opaque_type_def_id: DefId,
557 map: FxHashMap<Kind<'tcx>, Kind<'tcx>>,
558 map_missing_regions_to_empty: bool,
560 /// initially `Some`, set to `None` once error has been reported
561 hidden_ty: Option<Ty<'tcx>>,
564 impl ReverseMapper<'tcx> {
567 tainted_by_errors: bool,
568 opaque_type_def_id: DefId,
569 map: FxHashMap<Kind<'tcx>, Kind<'tcx>>,
577 map_missing_regions_to_empty: false,
578 hidden_ty: Some(hidden_ty),
582 fn fold_kind_mapping_missing_regions_to_empty(&mut self, kind: Kind<'tcx>) -> Kind<'tcx> {
583 assert!(!self.map_missing_regions_to_empty);
584 self.map_missing_regions_to_empty = true;
585 let kind = kind.fold_with(self);
586 self.map_missing_regions_to_empty = false;
590 fn fold_kind_normally(&mut self, kind: Kind<'tcx>) -> Kind<'tcx> {
591 assert!(!self.map_missing_regions_to_empty);
596 impl TypeFolder<'tcx> for ReverseMapper<'tcx> {
597 fn tcx(&self) -> TyCtxt<'tcx> {
601 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
603 // ignore bound regions that appear in the type (e.g., this
604 // would ignore `'r` in a type like `for<'r> fn(&'r u32)`.
605 ty::ReLateBound(..) |
607 // ignore `'static`, as that can appear anywhere
608 ty::ReStatic => return r,
613 match self.map.get(&r.into()).map(|k| k.unpack()) {
614 Some(UnpackedKind::Lifetime(r1)) => r1,
615 Some(u) => panic!("region mapped to unexpected kind: {:?}", u),
617 if !self.map_missing_regions_to_empty && !self.tainted_by_errors {
618 if let Some(hidden_ty) = self.hidden_ty.take() {
619 let span = self.tcx.def_span(self.opaque_type_def_id);
620 let mut err = struct_span_err!(
624 "hidden type for `impl Trait` captures lifetime that \
625 does not appear in bounds",
628 // Assuming regionck succeeded, then we must
629 // be capturing *some* region from the fn
630 // header, and hence it must be free, so it's
631 // ok to invoke this fn (which doesn't accept
632 // all regions, and would ICE if an
633 // inappropriate region is given). We check
634 // `is_tainted_by_errors` by errors above, so
635 // we don't get in here unless regionck
636 // succeeded. (Note also that if regionck
637 // failed, then the regions we are attempting
638 // to map here may well be giving errors
639 // *because* the constraints were not
641 self.tcx.note_and_explain_free_region(
643 &format!("hidden type `{}` captures ", hidden_ty),
651 self.tcx.lifetimes.re_empty
656 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
658 ty::Closure(def_id, substs) => {
659 // I am a horrible monster and I pray for death. When
660 // we encounter a closure here, it is always a closure
661 // from within the function that we are currently
662 // type-checking -- one that is now being encapsulated
663 // in an existential abstract type. Ideally, we would
664 // go through the types/lifetimes that it references
665 // and treat them just like we would any other type,
666 // which means we would error out if we find any
667 // reference to a type/region that is not in the
670 // **However,** in the case of closures, there is a
671 // somewhat subtle (read: hacky) consideration. The
672 // problem is that our closure types currently include
673 // all the lifetime parameters declared on the
674 // enclosing function, even if they are unused by the
675 // closure itself. We can't readily filter them out,
676 // so here we replace those values with `'empty`. This
677 // can't really make a difference to the rest of the
678 // compiler; those regions are ignored for the
679 // outlives relation, and hence don't affect trait
680 // selection or auto traits, and they are erased
683 let generics = self.tcx.generics_of(def_id);
684 let substs = self.tcx.mk_substs(substs.substs.iter().enumerate().map(
686 if index < generics.parent_count {
687 // Accommodate missing regions in the parent kinds...
688 self.fold_kind_mapping_missing_regions_to_empty(kind)
690 // ...but not elsewhere.
691 self.fold_kind_normally(kind)
696 self.tcx.mk_closure(def_id, ty::ClosureSubsts { substs })
699 ty::Generator(def_id, substs, movability) => {
700 let generics = self.tcx.generics_of(def_id);
701 let substs = self.tcx.mk_substs(substs.substs.iter().enumerate().map(
703 if index < generics.parent_count {
704 // Accommodate missing regions in the parent kinds...
705 self.fold_kind_mapping_missing_regions_to_empty(kind)
707 // ...but not elsewhere.
708 self.fold_kind_normally(kind)
713 self.tcx.mk_generator(def_id, ty::GeneratorSubsts { substs }, movability)
716 _ => ty.super_fold_with(self),
721 struct Instantiator<'a, 'tcx> {
722 infcx: &'a InferCtxt<'a, 'tcx>,
723 parent_def_id: DefId,
725 param_env: ty::ParamEnv<'tcx>,
726 opaque_types: OpaqueTypeMap<'tcx>,
727 obligations: Vec<PredicateObligation<'tcx>>,
730 impl<'a, 'tcx> Instantiator<'a, 'tcx> {
731 fn instantiate_opaque_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
732 debug!("instantiate_opaque_types_in_map(value={:?})", value);
733 let tcx = self.infcx.tcx;
734 value.fold_with(&mut BottomUpFolder {
737 if let ty::Opaque(def_id, substs) = ty.sty {
738 // Check that this is `impl Trait` type is
739 // declared by `parent_def_id` -- i.e., one whose
740 // value we are inferring. At present, this is
741 // always true during the first phase of
742 // type-check, but not always true later on during
743 // NLL. Once we support named abstract types more fully,
744 // this same scenario will be able to arise during all phases.
746 // Here is an example using `abstract type` that indicates
747 // the distinction we are checking for:
751 // pub abstract type Foo: Iterator;
752 // pub fn make_foo() -> Foo { .. }
756 // fn foo() -> a::Foo { a::make_foo() }
760 // Here, the return type of `foo` references a
761 // `Opaque` indeed, but not one whose value is
762 // presently being inferred. You can get into a
763 // similar situation with closure return types
767 // fn foo() -> impl Iterator { .. }
769 // let x = || foo(); // returns the Opaque assoc with `foo`
772 if let Some(opaque_hir_id) = tcx.hir().as_local_hir_id(def_id) {
773 let parent_def_id = self.parent_def_id;
774 let def_scope_default = || {
775 let opaque_parent_hir_id = tcx.hir().get_parent_item(opaque_hir_id);
776 parent_def_id == tcx.hir()
777 .local_def_id_from_hir_id(opaque_parent_hir_id)
779 let (in_definition_scope, origin) =
780 match tcx.hir().find(opaque_hir_id)
782 Some(Node::Item(item)) => match item.node {
783 // Anonymous `impl Trait`
784 hir::ItemKind::Existential(hir::ExistTy {
785 impl_trait_fn: Some(parent),
788 }) => (parent == self.parent_def_id, origin),
789 // Named `existential type`
790 hir::ItemKind::Existential(hir::ExistTy {
795 may_define_existential_type(
802 _ => (def_scope_default(), hir::ExistTyOrigin::ExistentialType),
804 Some(Node::ImplItem(item)) => match item.node {
805 hir::ImplItemKind::Existential(_) => (
806 may_define_existential_type(
811 hir::ExistTyOrigin::ExistentialType,
813 _ => (def_scope_default(), hir::ExistTyOrigin::ExistentialType),
816 "expected (impl) item, found {}",
817 tcx.hir().node_to_string(opaque_hir_id),
820 if in_definition_scope {
821 return self.fold_opaque_ty(ty, def_id, substs, origin);
825 "instantiate_opaque_types_in_map: \
826 encountered opaque outside its definition scope \
844 substs: SubstsRef<'tcx>,
845 origin: hir::ExistTyOrigin,
847 let infcx = self.infcx;
851 "instantiate_opaque_types: Opaque(def_id={:?}, substs={:?})",
855 // Use the same type variable if the exact same opaque type appears more
856 // than once in the return type (e.g., if it's passed to a type alias).
857 if let Some(opaque_defn) = self.opaque_types.get(&def_id) {
858 return opaque_defn.concrete_ty;
860 let span = tcx.def_span(def_id);
861 let ty_var = infcx.next_ty_var(TypeVariableOrigin {
862 kind: TypeVariableOriginKind::TypeInference,
866 let predicates_of = tcx.predicates_of(def_id);
868 "instantiate_opaque_types: predicates={:#?}",
871 let bounds = predicates_of.instantiate(tcx, substs);
872 debug!("instantiate_opaque_types: bounds={:?}", bounds);
874 let required_region_bounds = tcx.required_region_bounds(ty, bounds.predicates.clone());
876 "instantiate_opaque_types: required_region_bounds={:?}",
877 required_region_bounds
880 // Make sure that we are in fact defining the *entire* type
881 // (e.g., `existential type Foo<T: Bound>: Bar;` needs to be
882 // defined by a function like `fn foo<T: Bound>() -> Foo<T>`).
884 "instantiate_opaque_types: param_env={:#?}",
888 "instantiate_opaque_types: generics={:#?}",
889 tcx.generics_of(def_id),
892 self.opaque_types.insert(
897 has_required_region_bounds: !required_region_bounds.is_empty(),
901 debug!("instantiate_opaque_types: ty_var={:?}", ty_var);
903 self.obligations.reserve(bounds.predicates.len());
904 for predicate in bounds.predicates {
905 // Change the predicate to refer to the type variable,
906 // which will be the concrete type instead of the opaque type.
907 // This also instantiates nested instances of `impl Trait`.
908 let predicate = self.instantiate_opaque_types_in_map(&predicate);
910 let cause = traits::ObligationCause::new(span, self.body_id, traits::SizedReturnType);
912 // Require that the predicate holds for the concrete type.
913 debug!("instantiate_opaque_types: predicate={:?}", predicate);
915 .push(traits::Obligation::new(cause, self.param_env, predicate));
922 /// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`.
928 /// pub existential type Baz;
930 /// fn f1() -> Baz { .. }
933 /// fn f2() -> bar::Baz { .. }
937 /// Here, `def_id` is the `DefId` of the defining use of the existential type (e.g., `f1` or `f2`),
938 /// and `opaque_hir_id` is the `HirId` of the definition of the existential type `Baz`.
939 /// For the above example, this function returns `true` for `f1` and `false` for `f2`.
940 pub fn may_define_existential_type(
943 opaque_hir_id: hir::HirId,
945 let mut hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
947 "may_define_existential_type(def={:?}, opaque_node={:?})",
948 tcx.hir().get(hir_id),
949 tcx.hir().get(opaque_hir_id)
952 // Named existential types can be defined by any siblings or children of siblings.
953 let scope = tcx.hir()
954 .get_defining_scope(opaque_hir_id)
955 .expect("could not get defining scope");
956 // We walk up the node tree until we hit the root or the scope of the opaque type.
957 while hir_id != scope && hir_id != hir::CRATE_HIR_ID {
958 hir_id = tcx.hir().get_parent_item(hir_id);
960 // Syntactically, we are allowed to define the concrete type if: