1 use hir::def_id::DefId;
4 use infer::{self, InferCtxt, InferOk, TypeVariableOrigin};
5 use infer::outlives::free_region_map::FreeRegionRelations;
6 use rustc_data_structures::fx::FxHashMap;
8 use traits::{self, PredicateObligation};
9 use ty::{self, Ty, TyCtxt, GenericParamDefKind};
10 use ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder};
11 use ty::outlives::Component;
12 use ty::subst::{Kind, Substs, UnpackedKind};
13 use 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, T>: Trait<'x>
30 /// fn foo<'a, 'b, T>() -> Foo<'a, T>
32 /// then `substs` would be `['a, T]`.
33 pub substs: &'tcx Substs<'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 /// 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,
73 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
74 /// Replace all opaque types in `value` with fresh inference variables
75 /// and creates appropriate obligations. For example, given the input:
77 /// impl Iterator<Item = impl Debug>
79 /// this method would create two type variables, `?0` and `?1`. It would
80 /// return the type `?0` but also the obligations:
82 /// ?0: Iterator<Item = ?1>
85 /// Moreover, it returns a `OpaqueTypeMap` that would map `?0` to
86 /// info about the `impl Iterator<..>` type and `?1` to info about
87 /// the `impl Debug` type.
91 /// - `parent_def_id` -- the def-id of the function in which the opaque type
93 /// - `body_id` -- the body-id with which the resulting obligations should
95 /// - `param_env` -- the in-scope parameter environment to be used for
97 /// - `value` -- the value within which we are instantiating opaque types
98 pub fn instantiate_opaque_types<T: TypeFoldable<'tcx>>(
100 parent_def_id: DefId,
101 body_id: ast::NodeId,
102 param_env: ty::ParamEnv<'tcx>,
104 ) -> InferOk<'tcx, (T, OpaqueTypeMap<'tcx>)> {
105 debug!("instantiate_opaque_types(value={:?}, parent_def_id={:?}, body_id={:?}, \
107 value, parent_def_id, body_id, param_env,
109 let mut instantiator = Instantiator {
114 opaque_types: Default::default(),
117 let value = instantiator.instantiate_opaque_types_in_map(value);
119 value: (value, instantiator.opaque_types),
120 obligations: instantiator.obligations,
124 /// Given the map `opaque_types` containing the existential `impl
125 /// Trait` types whose underlying, hidden types are being
126 /// inferred, this method adds constraints to the regions
127 /// appearing in those underlying hidden types to ensure that they
128 /// at least do not refer to random scopes within the current
129 /// function. These constraints are not (quite) sufficient to
130 /// guarantee that the regions are actually legal values; that
131 /// final condition is imposed after region inference is done.
135 /// Let's work through an example to explain how it works. Assume
136 /// the current function is as follows:
139 /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
142 /// Here, we have two `impl Trait` types whose values are being
143 /// inferred (the `impl Bar<'a>` and the `impl
144 /// Bar<'b>`). Conceptually, this is sugar for a setup where we
145 /// define underlying abstract types (`Foo1`, `Foo2`) and then, in
146 /// the return type of `foo`, we *reference* those definitions:
149 /// abstract type Foo1<'x>: Bar<'x>;
150 /// abstract type Foo2<'x>: Bar<'x>;
151 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
158 /// As indicating in the comments above, each of those references
159 /// is (in the compiler) basically a substitution (`substs`)
160 /// applied to the type of a suitable `def_id` (which identifies
161 /// `Foo1` or `Foo2`).
163 /// Now, at this point in compilation, what we have done is to
164 /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
165 /// fresh inference variables C1 and C2. We wish to use the values
166 /// of these variables to infer the underlying types of `Foo1` and
167 /// `Foo2`. That is, this gives rise to higher-order (pattern) unification
168 /// constraints like:
171 /// for<'a> (Foo1<'a> = C1)
172 /// for<'b> (Foo1<'b> = C2)
175 /// For these equation to be satisfiable, the types `C1` and `C2`
176 /// can only refer to a limited set of regions. For example, `C1`
177 /// can only refer to `'static` and `'a`, and `C2` can only refer
178 /// to `'static` and `'b`. The job of this function is to impose that
181 /// Up to this point, C1 and C2 are basically just random type
182 /// inference variables, and hence they may contain arbitrary
183 /// regions. In fact, it is fairly likely that they do! Consider
184 /// this possible definition of `foo`:
187 /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
192 /// Here, the values for the concrete types of the two impl
193 /// traits will include inference variables:
200 /// Ordinarily, the subtyping rules would ensure that these are
201 /// sufficiently large. But since `impl Bar<'a>` isn't a specific
202 /// type per se, we don't get such constraints by default. This
203 /// is where this function comes into play. It adds extra
204 /// constraints to ensure that all the regions which appear in the
205 /// inferred type are regions that could validly appear.
207 /// This is actually a bit of a tricky constraint in general. We
208 /// want to say that each variable (e.g., `'0`) can only take on
209 /// values that were supplied as arguments to the abstract type
210 /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
211 /// scope. We don't have a constraint quite of this kind in the current
216 /// We make use of the constraint that we *do* have in the `<=`
217 /// relation. To do that, we find the "minimum" of all the
218 /// arguments that appear in the substs: that is, some region
219 /// which is less than all the others. In the case of `Foo1<'a>`,
220 /// that would be `'a` (it's the only choice, after all). Then we
221 /// apply that as a least bound to the variables (e.g., `'a <=
224 /// In some cases, there is no minimum. Consider this example:
227 /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
230 /// Here we would report an error, because `'a` and `'b` have no
231 /// relation to one another.
233 /// # The `free_region_relations` parameter
235 /// The `free_region_relations` argument is used to find the
236 /// "minimum" of the regions supplied to a given abstract type.
237 /// It must be a relation that can answer whether `'a <= 'b`,
238 /// where `'a` and `'b` are regions that appear in the "substs"
239 /// for the abstract type references (the `<'a>` in `Foo1<'a>`).
241 /// Note that we do not impose the constraints based on the
242 /// generic regions from the `Foo1` definition (e.g., `'x`). This
243 /// is because the constraints we are imposing here is basically
244 /// the concern of the one generating the constraining type C1,
245 /// which is the current function. It also means that we can
246 /// take "implied bounds" into account in some cases:
249 /// trait SomeTrait<'a, 'b> { }
250 /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. }
253 /// Here, the fact that `'b: 'a` is known only because of the
254 /// implied bounds from the `&'a &'b u32` parameter, and is not
255 /// "inherent" to the abstract type definition.
259 /// - `opaque_types` -- the map produced by `instantiate_opaque_types`
260 /// - `free_region_relations` -- something that can be used to relate
261 /// the free regions (`'a`) that appear in the impl trait.
262 pub fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(
264 opaque_types: &OpaqueTypeMap<'tcx>,
265 free_region_relations: &FRR,
267 debug!("constrain_opaque_types()");
269 for (&def_id, opaque_defn) in opaque_types {
270 self.constrain_opaque_type(def_id, opaque_defn, free_region_relations);
274 pub fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>(
277 opaque_defn: &OpaqueTypeDecl<'tcx>,
278 free_region_relations: &FRR,
280 debug!("constrain_opaque_type()");
281 debug!("constrain_opaque_type: def_id={:?}", def_id);
282 debug!("constrain_opaque_type: opaque_defn={:#?}", opaque_defn);
284 let concrete_ty = self.resolve_type_vars_if_possible(&opaque_defn.concrete_ty);
286 debug!("constrain_opaque_type: concrete_ty={:?}", concrete_ty);
288 let abstract_type_generics = self.tcx.generics_of(def_id);
290 let span = self.tcx.def_span(def_id);
292 // If there are required region bounds, we can just skip
293 // ahead. There will already be a registered region
294 // obligation related `concrete_ty` to those regions.
295 if opaque_defn.has_required_region_bounds {
299 // There were no `required_region_bounds`,
300 // so we have to search for a `least_region`.
301 // Go through all the regions used as arguments to the
302 // abstract type. These are the parameters to the abstract
303 // type; so in our example above, `substs` would contain
304 // `['a]` for the first impl trait and `'b` for the
306 let mut least_region = None;
307 for param in &abstract_type_generics.params {
309 GenericParamDefKind::Lifetime => {}
312 // Get the value supplied for this region from the substs.
313 let subst_arg = opaque_defn.substs.region_at(param.index as usize);
315 // Compute the least upper bound of it with the other regions.
316 debug!("constrain_opaque_types: least_region={:?}", least_region);
317 debug!("constrain_opaque_types: subst_arg={:?}", subst_arg);
319 None => least_region = Some(subst_arg),
321 if free_region_relations.sub_free_regions(lr, subst_arg) {
322 // keep the current least region
323 } else if free_region_relations.sub_free_regions(subst_arg, lr) {
324 // switch to `subst_arg`
325 least_region = Some(subst_arg);
327 // There are two regions (`lr` and
328 // `subst_arg`) which are not relatable. We can't
329 // find a best choice.
332 .struct_span_err(span, "ambiguous lifetime bound in `impl Trait`")
335 format!("neither `{}` nor `{}` outlives the other", lr, subst_arg),
339 least_region = Some(self.tcx.mk_region(ty::ReEmpty));
346 let least_region = least_region.unwrap_or(self.tcx.types.re_static);
347 debug!("constrain_opaque_types: least_region={:?}", least_region);
349 // Require that the type `concrete_ty` outlives
350 // `least_region`, modulo any type parameters that appear
351 // in the type, which we ignore. This is because impl
352 // trait values are assumed to capture all the in-scope
353 // type parameters. This little loop here just invokes
354 // `outlives` repeatedly, draining all the nested
355 // obligations that result.
356 let mut types = vec![concrete_ty];
357 let bound_region = |r| self.sub_regions(infer::CallReturn(span), least_region, r);
358 while let Some(ty) = types.pop() {
359 let mut components = smallvec![];
360 self.tcx.push_outlives_components(ty, &mut components);
361 while let Some(component) = components.pop() {
363 Component::Region(r) => {
367 Component::Param(_) => {
368 // ignore type parameters like `T`, they are captured
369 // implicitly by the `impl Trait`
372 Component::UnresolvedInferenceVariable(_) => {
373 // we should get an error that more type
374 // annotations are needed in this case
377 .delay_span_bug(span, "unresolved inf var in opaque");
380 Component::Projection(ty::ProjectionTy {
384 for r in substs.regions() {
387 types.extend(substs.types());
390 Component::EscapingProjection(more_components) => {
391 components.extend(more_components);
398 /// Given the fully resolved, instantiated type for an opaque
399 /// type, i.e., the value of an inference variable like C1 or C2
400 /// (*), computes the "definition type" for an abstract type
401 /// definition -- that is, the inferred value of `Foo1<'x>` or
402 /// `Foo2<'x>` that we would conceptually use in its definition:
404 /// abstract type Foo1<'x>: Bar<'x> = AAA; <-- this type AAA
405 /// abstract type Foo2<'x>: Bar<'x> = BBB; <-- or this type BBB
406 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
408 /// Note that these values are defined in terms of a distinct set of
409 /// generic parameters (`'x` instead of `'a`) from C1 or C2. The main
410 /// purpose of this function is to do that translation.
412 /// (*) C1 and C2 were introduced in the comments on
413 /// `constrain_opaque_types`. Read that comment for more context.
417 /// - `def_id`, the `impl Trait` type
418 /// - `opaque_defn`, the opaque definition created in `instantiate_opaque_types`
419 /// - `instantiated_ty`, the inferred type C1 -- fully resolved, lifted version of
420 /// `opaque_defn.concrete_ty`
421 pub fn infer_opaque_definition_from_instantiation(
424 opaque_defn: &OpaqueTypeDecl<'tcx>,
425 instantiated_ty: Ty<'gcx>,
428 "infer_opaque_definition_from_instantiation(def_id={:?}, instantiated_ty={:?})",
429 def_id, instantiated_ty
432 let gcx = self.tcx.global_tcx();
434 // Use substs to build up a reverse map from regions to their
435 // identity mappings. This is necessary because of `impl
436 // Trait` lifetimes are computed by replacing existing
437 // lifetimes with 'static and remapping only those used in the
438 // `impl Trait` return type, resulting in the parameters
440 let id_substs = Substs::identity_for_item(gcx, def_id);
441 let map: FxHashMap<Kind<'tcx>, Kind<'gcx>> = opaque_defn
445 .map(|(index, subst)| (*subst, id_substs[index]))
448 // Convert the type from the function into a type valid outside
449 // the function, by replacing invalid regions with 'static,
450 // after producing an error for each of them.
452 instantiated_ty.fold_with(&mut ReverseMapper::new(
454 self.is_tainted_by_errors(),
460 "infer_opaque_definition_from_instantiation: definition_ty={:?}",
464 // We can unwrap here because our reverse mapper always
465 // produces things with 'gcx lifetime, though the type folder
467 let definition_ty = gcx.lift(&definition_ty).unwrap();
473 struct ReverseMapper<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
474 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
476 /// If errors have already been reported in this fn, we suppress
477 /// our own errors because they are sometimes derivative.
478 tainted_by_errors: bool,
480 opaque_type_def_id: DefId,
481 map: FxHashMap<Kind<'tcx>, Kind<'gcx>>,
482 map_missing_regions_to_empty: bool,
484 /// initially `Some`, set to `None` once error has been reported
485 hidden_ty: Option<Ty<'tcx>>,
488 impl<'cx, 'gcx, 'tcx> ReverseMapper<'cx, 'gcx, 'tcx> {
490 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
491 tainted_by_errors: bool,
492 opaque_type_def_id: DefId,
493 map: FxHashMap<Kind<'tcx>, Kind<'gcx>>,
501 map_missing_regions_to_empty: false,
502 hidden_ty: Some(hidden_ty),
506 fn fold_kind_mapping_missing_regions_to_empty(&mut self, kind: Kind<'tcx>) -> Kind<'tcx> {
507 assert!(!self.map_missing_regions_to_empty);
508 self.map_missing_regions_to_empty = true;
509 let kind = kind.fold_with(self);
510 self.map_missing_regions_to_empty = false;
514 fn fold_kind_normally(&mut self, kind: Kind<'tcx>) -> Kind<'tcx> {
515 assert!(!self.map_missing_regions_to_empty);
520 impl<'cx, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ReverseMapper<'cx, 'gcx, 'tcx> {
521 fn tcx(&self) -> TyCtxt<'_, 'gcx, 'tcx> {
525 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
527 // ignore bound regions that appear in the type (e.g., this
528 // would ignore `'r` in a type like `for<'r> fn(&'r u32)`.
529 ty::ReLateBound(..) |
531 // ignore `'static`, as that can appear anywhere
534 // ignore `ReScope`, as that can appear anywhere
535 // See `src/test/run-pass/issue-49556.rs` for example.
536 ty::ReScope(..) => return r,
541 match self.map.get(&r.into()).map(|k| k.unpack()) {
542 Some(UnpackedKind::Lifetime(r1)) => r1,
543 Some(u) => panic!("region mapped to unexpected kind: {:?}", u),
545 if !self.map_missing_regions_to_empty && !self.tainted_by_errors {
546 if let Some(hidden_ty) = self.hidden_ty.take() {
547 let span = self.tcx.def_span(self.opaque_type_def_id);
548 let mut err = struct_span_err!(
552 "hidden type for `impl Trait` captures lifetime that \
553 does not appear in bounds",
556 // Assuming regionck succeeded, then we must
557 // be capturing *some* region from the fn
558 // header, and hence it must be free, so it's
559 // ok to invoke this fn (which doesn't accept
560 // all regions, and would ICE if an
561 // inappropriate region is given). We check
562 // `is_tainted_by_errors` by errors above, so
563 // we don't get in here unless regionck
564 // succeeded. (Note also that if regionck
565 // failed, then the regions we are attempting
566 // to map here may well be giving errors
567 // *because* the constraints were not
569 self.tcx.note_and_explain_free_region(
571 &format!("hidden type `{}` captures ", hidden_ty),
579 self.tcx.types.re_empty
584 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
586 ty::Closure(def_id, substs) => {
587 // I am a horrible monster and I pray for death. When
588 // we encounter a closure here, it is always a closure
589 // from within the function that we are currently
590 // type-checking -- one that is now being encapsulated
591 // in an existential abstract type. Ideally, we would
592 // go through the types/lifetimes that it references
593 // and treat them just like we would any other type,
594 // which means we would error out if we find any
595 // reference to a type/region that is not in the
598 // **However,** in the case of closures, there is a
599 // somewhat subtle (read: hacky) consideration. The
600 // problem is that our closure types currently include
601 // all the lifetime parameters declared on the
602 // enclosing function, even if they are unused by the
603 // closure itself. We can't readily filter them out,
604 // so here we replace those values with `'empty`. This
605 // can't really make a difference to the rest of the
606 // compiler; those regions are ignored for the
607 // outlives relation, and hence don't affect trait
608 // selection or auto traits, and they are erased
611 let generics = self.tcx.generics_of(def_id);
612 let substs = self.tcx.mk_substs(substs.substs.iter().enumerate().map(
614 if index < generics.parent_count {
615 // Accommodate missing regions in the parent kinds...
616 self.fold_kind_mapping_missing_regions_to_empty(kind)
618 // ...but not elsewhere.
619 self.fold_kind_normally(kind)
624 self.tcx.mk_closure(def_id, ty::ClosureSubsts { substs })
627 _ => ty.super_fold_with(self),
632 struct Instantiator<'a, 'gcx: 'tcx, 'tcx: 'a> {
633 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
634 parent_def_id: DefId,
635 body_id: ast::NodeId,
636 param_env: ty::ParamEnv<'tcx>,
637 opaque_types: OpaqueTypeMap<'tcx>,
638 obligations: Vec<PredicateObligation<'tcx>>,
641 impl<'a, 'gcx, 'tcx> Instantiator<'a, 'gcx, 'tcx> {
642 fn instantiate_opaque_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
643 debug!("instantiate_opaque_types_in_map(value={:?})", value);
644 let tcx = self.infcx.tcx;
645 value.fold_with(&mut BottomUpFolder {
649 if let ty::Opaque(def_id, substs) = ty.sty {
650 // Check that this is `impl Trait` type is
651 // declared by `parent_def_id` -- i.e., one whose
652 // value we are inferring. At present, this is
653 // always true during the first phase of
654 // type-check, but not always true later on during
655 // NLL. Once we support named abstract types more fully,
656 // this same scenario will be able to arise during all phases.
658 // Here is an example using `abstract type` that indicates
659 // the distinction we are checking for:
663 // pub abstract type Foo: Iterator;
664 // pub fn make_foo() -> Foo { .. }
668 // fn foo() -> a::Foo { a::make_foo() }
672 // Here, the return type of `foo` references a
673 // `Opaque` indeed, but not one whose value is
674 // presently being inferred. You can get into a
675 // similar situation with closure return types
679 // fn foo() -> impl Iterator { .. }
681 // let x = || foo(); // returns the Opaque assoc with `foo`
684 if let Some(opaque_node_id) = tcx.hir().as_local_node_id(def_id) {
685 let parent_def_id = self.parent_def_id;
686 let def_scope_default = || {
687 let opaque_parent_node_id = tcx.hir().get_parent(opaque_node_id);
688 parent_def_id == tcx.hir().local_def_id(opaque_parent_node_id)
690 let in_definition_scope = match tcx.hir().find(opaque_node_id) {
691 Some(Node::Item(item)) => match item.node {
693 hir::ItemKind::Existential(hir::ExistTy {
694 impl_trait_fn: Some(parent),
696 }) => parent == self.parent_def_id,
697 // named existential types
698 hir::ItemKind::Existential(hir::ExistTy {
701 }) => may_define_existential_type(
706 _ => def_scope_default(),
708 Some(Node::ImplItem(item)) => match item.node {
709 hir::ImplItemKind::Existential(_) => may_define_existential_type(
714 _ => def_scope_default(),
717 "expected (impl) item, found {}",
718 tcx.hir().node_to_string(opaque_node_id),
721 if in_definition_scope {
722 return self.fold_opaque_ty(ty, def_id, substs);
726 "instantiate_opaque_types_in_map: \
727 encountered opaque outside its definition scope \
743 substs: &'tcx Substs<'tcx>,
745 let infcx = self.infcx;
749 "instantiate_opaque_types: Opaque(def_id={:?}, substs={:?})",
753 // Use the same type variable if the exact same Opaque appears more
754 // than once in the return type (e.g., if it's passed to a type alias).
755 if let Some(opaque_defn) = self.opaque_types.get(&def_id) {
756 return opaque_defn.concrete_ty;
758 let span = tcx.def_span(def_id);
759 let ty_var = infcx.next_ty_var(TypeVariableOrigin::TypeInference(span));
761 let predicates_of = tcx.predicates_of(def_id);
763 "instantiate_opaque_types: predicates: {:#?}",
766 let bounds = predicates_of.instantiate(tcx, substs);
767 debug!("instantiate_opaque_types: bounds={:?}", bounds);
769 let required_region_bounds = tcx.required_region_bounds(ty, bounds.predicates.clone());
771 "instantiate_opaque_types: required_region_bounds={:?}",
772 required_region_bounds
775 // make sure that we are in fact defining the *entire* type
776 // e.g., `existential type Foo<T: Bound>: Bar;` needs to be
777 // defined by a function like `fn foo<T: Bound>() -> Foo<T>`.
779 "instantiate_opaque_types: param_env: {:#?}",
783 "instantiate_opaque_types: generics: {:#?}",
784 tcx.generics_of(def_id),
787 self.opaque_types.insert(
792 has_required_region_bounds: !required_region_bounds.is_empty(),
795 debug!("instantiate_opaque_types: ty_var={:?}", ty_var);
797 self.obligations.reserve(bounds.predicates.len());
798 for predicate in bounds.predicates {
799 // Change the predicate to refer to the type variable,
800 // which will be the concrete type instead of the opaque type.
801 // This also instantiates nested instances of `impl Trait`.
802 let predicate = self.instantiate_opaque_types_in_map(&predicate);
804 let cause = traits::ObligationCause::new(span, self.body_id, traits::SizedReturnType);
806 // Require that the predicate holds for the concrete type.
807 debug!("instantiate_opaque_types: predicate={:?}", predicate);
809 .push(traits::Obligation::new(cause, self.param_env, predicate));
816 /// Whether `opaque_node_id` is a sibling or a child of a sibling of `def_id`
821 /// pub existential type Baz;
823 /// fn f1() -> Baz { .. }
826 /// fn f2() -> bar::Baz { .. }
830 /// Here, `def_id` will be the `DefId` of the existential type `Baz`.
831 /// `opaque_node_id` is the `NodeId` of the reference to Baz --
832 /// so either the return type of f1 or f2.
833 /// We will return true if the reference is within the same module as the existential type
834 /// So true for f1, false for f2.
835 pub fn may_define_existential_type(
836 tcx: TyCtxt<'_, '_, '_>,
838 opaque_node_id: ast::NodeId,
840 let mut node_id = tcx
842 .as_local_node_id(def_id)
844 // named existential types can be defined by any siblings or
845 // children of siblings
846 let mod_id = tcx.hir().get_parent(opaque_node_id);
847 // so we walk up the node tree until we hit the root or the parent
848 // of the opaque type
849 while node_id != mod_id && node_id != ast::CRATE_NODE_ID {
850 node_id = tcx.hir().get_parent(node_id);
852 // syntactically we are allowed to define the concrete type