1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use hir::def_id::DefId;
13 use infer::{self, InferCtxt, InferOk, TypeVariableOrigin};
14 use infer::outlives::free_region_map::FreeRegionRelations;
15 use rustc_data_structures::fx::FxHashMap;
17 use traits::{self, PredicateObligation};
18 use ty::{self, Ty, TyCtxt, GenericParamDefKind};
19 use ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder};
20 use ty::outlives::Component;
21 use ty::subst::{Kind, Substs, UnpackedKind};
22 use util::nodemap::DefIdMap;
24 pub type AnonTypeMap<'tcx> = DefIdMap<AnonTypeDecl<'tcx>>;
26 /// Information about the anonymous, abstract types whose values we
27 /// are inferring in this function (these are the `impl Trait` that
28 /// appear in the return type).
29 #[derive(Copy, Clone, Debug)]
30 pub struct AnonTypeDecl<'tcx> {
31 /// The substitutions that we apply to the abstract that that this
32 /// `impl Trait` desugars to. e.g., if:
34 /// fn foo<'a, 'b, T>() -> impl Trait<'a>
36 /// winds up desugared to:
38 /// abstract type Foo<'x, T>: Trait<'x>
39 /// fn foo<'a, 'b, T>() -> Foo<'a, T>
41 /// then `substs` would be `['a, T]`.
42 pub substs: &'tcx Substs<'tcx>,
44 /// The type variable that represents the value of the abstract type
45 /// that we require. In other words, after we compile this function,
46 /// we will be created a constraint like:
50 /// where `?C` is the value of this type variable. =) It may
51 /// naturally refer to the type and lifetime parameters in scope
52 /// in this function, though ultimately it should only reference
53 /// those that are arguments to `Foo` in the constraint above. (In
54 /// other words, `?C` should not include `'b`, even though it's a
55 /// lifetime parameter on `foo`.)
56 pub concrete_ty: Ty<'tcx>,
58 /// True if the `impl Trait` bounds include region bounds.
59 /// For example, this would be true for:
61 /// fn foo<'a, 'b, 'c>() -> impl Trait<'c> + 'a + 'b
65 /// fn foo<'c>() -> impl Trait<'c>
67 /// unless `Trait` was declared like:
69 /// trait Trait<'c>: 'c
71 /// in which case it would be true.
73 /// This is used during regionck to decide whether we need to
74 /// impose any additional constraints to ensure that region
75 /// variables in `concrete_ty` wind up being constrained to
76 /// something from `substs` (or, at minimum, things that outlive
77 /// the fn body). (Ultimately, writeback is responsible for this
79 pub has_required_region_bounds: bool,
82 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
83 /// Replace all anonymized types in `value` with fresh inference variables
84 /// and creates appropriate obligations. For example, given the input:
86 /// impl Iterator<Item = impl Debug>
88 /// this method would create two type variables, `?0` and `?1`. It would
89 /// return the type `?0` but also the obligations:
91 /// ?0: Iterator<Item = ?1>
94 /// Moreover, it returns a `AnonTypeMap` that would map `?0` to
95 /// info about the `impl Iterator<..>` type and `?1` to info about
96 /// the `impl Debug` type.
100 /// - `parent_def_id` -- we will only instantiate anonymous types
101 /// with this parent. This is typically the def-id of the function
102 /// in whose return type anon types are being instantiated.
103 /// - `body_id` -- the body-id with which the resulting obligations should
105 /// - `param_env` -- the in-scope parameter environment to be used for
107 /// - `value` -- the value within which we are instantiating anon types
108 pub fn instantiate_anon_types<T: TypeFoldable<'tcx>>(
110 parent_def_id: DefId,
111 body_id: ast::NodeId,
112 param_env: ty::ParamEnv<'tcx>,
114 ) -> InferOk<'tcx, (T, AnonTypeMap<'tcx>)> {
116 "instantiate_anon_types(value={:?}, parent_def_id={:?}, body_id={:?}, param_env={:?})",
117 value, parent_def_id, body_id, param_env,
119 let mut instantiator = Instantiator {
124 anon_types: DefIdMap(),
127 let value = instantiator.instantiate_anon_types_in_map(value);
129 value: (value, instantiator.anon_types),
130 obligations: instantiator.obligations,
134 /// Given the map `anon_types` containing the existential `impl
135 /// Trait` types whose underlying, hidden types are being
136 /// inferred, this method adds constraints to the regions
137 /// appearing in those underlying hidden types to ensure that they
138 /// at least do not refer to random scopes within the current
139 /// function. These constraints are not (quite) sufficient to
140 /// guarantee that the regions are actually legal values; that
141 /// final condition is imposed after region inference is done.
145 /// Let's work through an example to explain how it works. Assume
146 /// the current function is as follows:
149 /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
152 /// Here, we have two `impl Trait` types whose values are being
153 /// inferred (the `impl Bar<'a>` and the `impl
154 /// Bar<'b>`). Conceptually, this is sugar for a setup where we
155 /// define underlying abstract types (`Foo1`, `Foo2`) and then, in
156 /// the return type of `foo`, we *reference* those definitions:
159 /// abstract type Foo1<'x>: Bar<'x>;
160 /// abstract type Foo2<'x>: Bar<'x>;
161 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
168 /// As indicating in the comments above, each of those references
169 /// is (in the compiler) basically a substitution (`substs`)
170 /// applied to the type of a suitable `def_id` (which identifies
171 /// `Foo1` or `Foo2`).
173 /// Now, at this point in compilation, what we have done is to
174 /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
175 /// fresh inference variables C1 and C2. We wish to use the values
176 /// of these variables to infer the underlying types of `Foo1` and
177 /// `Foo2`. That is, this gives rise to higher-order (pattern) unification
178 /// constraints like:
181 /// for<'a> (Foo1<'a> = C1)
182 /// for<'b> (Foo1<'b> = C2)
185 /// For these equation to be satisfiable, the types `C1` and `C2`
186 /// can only refer to a limited set of regions. For example, `C1`
187 /// can only refer to `'static` and `'a`, and `C2` can only refer
188 /// to `'static` and `'b`. The job of this function is to impose that
191 /// Up to this point, C1 and C2 are basically just random type
192 /// inference variables, and hence they may contain arbitrary
193 /// regions. In fact, it is fairly likely that they do! Consider
194 /// this possible definition of `foo`:
197 /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
202 /// Here, the values for the concrete types of the two impl
203 /// traits will include inference variables:
210 /// Ordinarily, the subtyping rules would ensure that these are
211 /// sufficiently large. But since `impl Bar<'a>` isn't a specific
212 /// type per se, we don't get such constraints by default. This
213 /// is where this function comes into play. It adds extra
214 /// constraints to ensure that all the regions which appear in the
215 /// inferred type are regions that could validly appear.
217 /// This is actually a bit of a tricky constraint in general. We
218 /// want to say that each variable (e.g., `'0`) can only take on
219 /// values that were supplied as arguments to the abstract type
220 /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
221 /// scope. We don't have a constraint quite of this kind in the current
226 /// We make use of the constraint that we *do* have in the `<=`
227 /// relation. To do that, we find the "minimum" of all the
228 /// arguments that appear in the substs: that is, some region
229 /// which is less than all the others. In the case of `Foo1<'a>`,
230 /// that would be `'a` (it's the only choice, after all). Then we
231 /// apply that as a least bound to the variables (e.g., `'a <=
234 /// In some cases, there is no minimum. Consider this example:
237 /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
240 /// Here we would report an error, because `'a` and `'b` have no
241 /// relation to one another.
243 /// # The `free_region_relations` parameter
245 /// The `free_region_relations` argument is used to find the
246 /// "minimum" of the regions supplied to a given abstract type.
247 /// It must be a relation that can answer whether `'a <= 'b`,
248 /// where `'a` and `'b` are regions that appear in the "substs"
249 /// for the abstract type references (the `<'a>` in `Foo1<'a>`).
251 /// Note that we do not impose the constraints based on the
252 /// generic regions from the `Foo1` definition (e.g., `'x`). This
253 /// is because the constraints we are imposing here is basically
254 /// the concern of the one generating the constraining type C1,
255 /// which is the current function. It also means that we can
256 /// take "implied bounds" into account in some cases:
259 /// trait SomeTrait<'a, 'b> { }
260 /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. }
263 /// Here, the fact that `'b: 'a` is known only because of the
264 /// implied bounds from the `&'a &'b u32` parameter, and is not
265 /// "inherent" to the abstract type definition.
269 /// - `anon_types` -- the map produced by `instantiate_anon_types`
270 /// - `free_region_relations` -- something that can be used to relate
271 /// the free regions (`'a`) that appear in the impl trait.
272 pub fn constrain_anon_types<FRR: FreeRegionRelations<'tcx>>(
274 anon_types: &AnonTypeMap<'tcx>,
275 free_region_relations: &FRR,
277 debug!("constrain_anon_types()");
279 for (&def_id, anon_defn) in anon_types {
280 self.constrain_anon_type(def_id, anon_defn, free_region_relations);
284 fn constrain_anon_type<FRR: FreeRegionRelations<'tcx>>(
287 anon_defn: &AnonTypeDecl<'tcx>,
288 free_region_relations: &FRR,
290 debug!("constrain_anon_type()");
291 debug!("constrain_anon_type: def_id={:?}", def_id);
292 debug!("constrain_anon_type: anon_defn={:#?}", anon_defn);
294 let concrete_ty = self.resolve_type_vars_if_possible(&anon_defn.concrete_ty);
296 debug!("constrain_anon_type: concrete_ty={:?}", concrete_ty);
298 let abstract_type_generics = self.tcx.generics_of(def_id);
300 let span = self.tcx.def_span(def_id);
302 // If there are required region bounds, we can just skip
303 // ahead. There will already be a registered region
304 // obligation related `concrete_ty` to those regions.
305 if anon_defn.has_required_region_bounds {
309 // There were no `required_region_bounds`,
310 // so we have to search for a `least_region`.
311 // Go through all the regions used as arguments to the
312 // abstract type. These are the parameters to the abstract
313 // type; so in our example above, `substs` would contain
314 // `['a]` for the first impl trait and `'b` for the
316 let mut least_region = None;
317 for param in &abstract_type_generics.params {
319 GenericParamDefKind::Lifetime => {}
322 // Get the value supplied for this region from the substs.
323 let subst_arg = anon_defn.substs.region_at(param.index as usize);
325 // Compute the least upper bound of it with the other regions.
326 debug!("constrain_anon_types: least_region={:?}", least_region);
327 debug!("constrain_anon_types: subst_arg={:?}", subst_arg);
329 None => least_region = Some(subst_arg),
331 if free_region_relations.sub_free_regions(lr, subst_arg) {
332 // keep the current least region
333 } else if free_region_relations.sub_free_regions(subst_arg, lr) {
334 // switch to `subst_arg`
335 least_region = Some(subst_arg);
337 // There are two regions (`lr` and
338 // `subst_arg`) which are not relatable. We can't
339 // find a best choice.
342 .struct_span_err(span, "ambiguous lifetime bound in `impl Trait`")
345 format!("neither `{}` nor `{}` outlives the other", lr, subst_arg),
349 least_region = Some(self.tcx.mk_region(ty::ReEmpty));
356 let least_region = least_region.unwrap_or(self.tcx.types.re_static);
357 debug!("constrain_anon_types: least_region={:?}", least_region);
359 // Require that the type `concrete_ty` outlives
360 // `least_region`, modulo any type parameters that appear
361 // in the type, which we ignore. This is because impl
362 // trait values are assumed to capture all the in-scope
363 // type parameters. This little loop here just invokes
364 // `outlives` repeatedly, draining all the nested
365 // obligations that result.
366 let mut types = vec![concrete_ty];
367 let bound_region = |r| self.sub_regions(infer::CallReturn(span), least_region, r);
368 while let Some(ty) = types.pop() {
369 let mut components = self.tcx.outlives_components(ty);
370 while let Some(component) = components.pop() {
372 Component::Region(r) => {
376 Component::Param(_) => {
377 // ignore type parameters like `T`, they are captured
378 // implicitly by the `impl Trait`
381 Component::UnresolvedInferenceVariable(_) => {
382 // we should get an error that more type
383 // annotations are needed in this case
386 .delay_span_bug(span, "unresolved inf var in anon");
389 Component::Projection(ty::ProjectionTy {
393 for r in substs.regions() {
396 types.extend(substs.types());
399 Component::EscapingProjection(more_components) => {
400 components.extend(more_components);
407 /// Given the fully resolved, instantiated type for an anonymous
408 /// type, i.e., the value of an inference variable like C1 or C2
409 /// (*), computes the "definition type" for an abstract type
410 /// definition -- that is, the inferred value of `Foo1<'x>` or
411 /// `Foo2<'x>` that we would conceptually use in its definition:
413 /// abstract type Foo1<'x>: Bar<'x> = AAA; <-- this type AAA
414 /// abstract type Foo2<'x>: Bar<'x> = BBB; <-- or this type BBB
415 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
417 /// Note that these values are defined in terms of a distinct set of
418 /// generic parameters (`'x` instead of `'a`) from C1 or C2. The main
419 /// purpose of this function is to do that translation.
421 /// (*) C1 and C2 were introduced in the comments on
422 /// `constrain_anon_types`. Read that comment for more context.
426 /// - `def_id`, the `impl Trait` type
427 /// - `anon_defn`, the anonymous definition created in `instantiate_anon_types`
428 /// - `instantiated_ty`, the inferred type C1 -- fully resolved, lifted version of
429 /// `anon_defn.concrete_ty`
430 pub fn infer_anon_definition_from_instantiation(
433 anon_defn: &AnonTypeDecl<'tcx>,
434 instantiated_ty: Ty<'gcx>,
437 "infer_anon_definition_from_instantiation(def_id={:?}, instantiated_ty={:?})",
438 def_id, instantiated_ty
441 let gcx = self.tcx.global_tcx();
443 // Use substs to build up a reverse map from regions to their
444 // identity mappings. This is necessary because of `impl
445 // Trait` lifetimes are computed by replacing existing
446 // lifetimes with 'static and remapping only those used in the
447 // `impl Trait` return type, resulting in the parameters
449 let id_substs = Substs::identity_for_item(gcx, def_id);
450 let map: FxHashMap<Kind<'tcx>, Kind<'gcx>> = anon_defn
454 .map(|(index, subst)| (*subst, id_substs[index]))
457 // Convert the type from the function into a type valid outside
458 // the function, by replacing invalid regions with 'static,
459 // after producing an error for each of them.
461 instantiated_ty.fold_with(&mut ReverseMapper::new(
463 self.is_tainted_by_errors(),
469 "infer_anon_definition_from_instantiation: definition_ty={:?}",
473 // We can unwrap here because our reverse mapper always
474 // produces things with 'gcx lifetime, though the type folder
476 let definition_ty = gcx.lift(&definition_ty).unwrap();
482 struct ReverseMapper<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
483 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
485 /// If errors have already been reported in this fn, we suppress
486 /// our own errors because they are sometimes derivative.
487 tainted_by_errors: bool,
489 anon_type_def_id: DefId,
490 map: FxHashMap<Kind<'tcx>, Kind<'gcx>>,
491 map_missing_regions_to_empty: bool,
493 /// initially `Some`, set to `None` once error has been reported
494 hidden_ty: Option<Ty<'tcx>>,
497 impl<'cx, 'gcx, 'tcx> ReverseMapper<'cx, 'gcx, 'tcx> {
499 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
500 tainted_by_errors: bool,
501 anon_type_def_id: DefId,
502 map: FxHashMap<Kind<'tcx>, Kind<'gcx>>,
510 map_missing_regions_to_empty: false,
511 hidden_ty: Some(hidden_ty),
515 fn fold_kind_mapping_missing_regions_to_empty(&mut self, kind: Kind<'tcx>) -> Kind<'tcx> {
516 assert!(!self.map_missing_regions_to_empty);
517 self.map_missing_regions_to_empty = true;
518 let kind = kind.fold_with(self);
519 self.map_missing_regions_to_empty = false;
523 fn fold_kind_normally(&mut self, kind: Kind<'tcx>) -> Kind<'tcx> {
524 assert!(!self.map_missing_regions_to_empty);
529 impl<'cx, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ReverseMapper<'cx, 'gcx, 'tcx> {
530 fn tcx(&self) -> TyCtxt<'_, 'gcx, 'tcx> {
534 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
536 // ignore bound regions that appear in the type (e.g., this
537 // would ignore `'r` in a type like `for<'r> fn(&'r u32)`.
538 ty::ReLateBound(..) |
540 // ignore `'static`, as that can appear anywhere
543 // ignore `ReScope`, as that can appear anywhere
544 // See `src/test/run-pass/issue-49556.rs` for example.
545 ty::ReScope(..) => return r,
550 match self.map.get(&r.into()).map(|k| k.unpack()) {
551 Some(UnpackedKind::Lifetime(r1)) => r1,
552 Some(u) => panic!("region mapped to unexpected kind: {:?}", u),
554 if !self.map_missing_regions_to_empty && !self.tainted_by_errors {
555 if let Some(hidden_ty) = self.hidden_ty.take() {
556 let span = self.tcx.def_span(self.anon_type_def_id);
557 let mut err = struct_span_err!(
561 "hidden type for `impl Trait` captures lifetime that \
562 does not appear in bounds",
565 // Assuming regionck succeeded, then we must
566 // be capturing *some* region from the fn
567 // header, and hence it must be free, so it's
568 // ok to invoke this fn (which doesn't accept
569 // all regions, and would ICE if an
570 // inappropriate region is given). We check
571 // `is_tainted_by_errors` by errors above, so
572 // we don't get in here unless regionck
573 // succeeded. (Note also that if regionck
574 // failed, then the regions we are attempting
575 // to map here may well be giving errors
576 // *because* the constraints were not
578 self.tcx.note_and_explain_free_region(
580 &format!("hidden type `{}` captures ", hidden_ty),
588 self.tcx.types.re_empty
593 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
595 ty::TyClosure(def_id, substs) => {
596 // I am a horrible monster and I pray for death. When
597 // we encounter a closure here, it is always a closure
598 // from within the function that we are currently
599 // type-checking -- one that is now being encapsulated
600 // in an existential abstract type. Ideally, we would
601 // go through the types/lifetimes that it references
602 // and treat them just like we would any other type,
603 // which means we would error out if we find any
604 // reference to a type/region that is not in the
607 // **However,** in the case of closures, there is a
608 // somewhat subtle (read: hacky) consideration. The
609 // problem is that our closure types currently include
610 // all the lifetime parameters declared on the
611 // enclosing function, even if they are unused by the
612 // closure itself. We can't readily filter them out,
613 // so here we replace those values with `'empty`. This
614 // can't really make a difference to the rest of the
615 // compiler; those regions are ignored for the
616 // outlives relation, and hence don't affect trait
617 // selection or auto traits, and they are erased
620 let generics = self.tcx.generics_of(def_id);
621 let substs = self.tcx.mk_substs(substs.substs.iter().enumerate().map(
623 if index < generics.parent_count {
624 // Accommodate missing regions in the parent kinds...
625 self.fold_kind_mapping_missing_regions_to_empty(kind)
627 // ...but not elsewhere.
628 self.fold_kind_normally(kind)
633 self.tcx.mk_closure(def_id, ty::ClosureSubsts { substs })
636 _ => ty.super_fold_with(self),
641 struct Instantiator<'a, 'gcx: 'tcx, 'tcx: 'a> {
642 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
643 parent_def_id: DefId,
644 body_id: ast::NodeId,
645 param_env: ty::ParamEnv<'tcx>,
646 anon_types: AnonTypeMap<'tcx>,
647 obligations: Vec<PredicateObligation<'tcx>>,
650 impl<'a, 'gcx, 'tcx> Instantiator<'a, 'gcx, 'tcx> {
651 fn instantiate_anon_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
652 debug!("instantiate_anon_types_in_map(value={:?})", value);
653 let tcx = self.infcx.tcx;
654 value.fold_with(&mut BottomUpFolder {
658 if let ty::TyAnon(def_id, substs) = ty.sty {
659 // Check that this is `impl Trait` type is
660 // declared by `parent_def_id` -- i.e., one whose
661 // value we are inferring. At present, this is
662 // always true during the first phase of
663 // type-check, but not always true later on during
664 // NLL. Once we support named abstract types more fully,
665 // this same scenario will be able to arise during all phases.
667 // Here is an example using `abstract type` that indicates
668 // the distinction we are checking for:
672 // pub abstract type Foo: Iterator;
673 // pub fn make_foo() -> Foo { .. }
677 // fn foo() -> a::Foo { a::make_foo() }
681 // Here, the return type of `foo` references a
682 // `TyAnon` indeed, but not one whose value is
683 // presently being inferred. You can get into a
684 // similar situation with closure return types
688 // fn foo() -> impl Iterator { .. }
690 // let x = || foo(); // returns the Anon assoc with `foo`
693 if let Some(anon_node_id) = tcx.hir.as_local_node_id(def_id) {
694 let in_definition_scope = match tcx.hir.expect_item(anon_node_id).node {
696 hir::ItemKind::Existential(hir::ExistTy {
697 impl_trait_fn: Some(parent),
699 }) => parent == self.parent_def_id,
700 // named existential types
701 hir::ItemKind::Existential(hir::ExistTy {
704 }) => may_define_existential_type(
710 let anon_parent_node_id = tcx.hir.get_parent(anon_node_id);
711 self.parent_def_id == tcx.hir.local_def_id(anon_parent_node_id)
714 if in_definition_scope {
715 return self.fold_anon_ty(ty, def_id, substs);
719 "instantiate_anon_types_in_map: \
720 encountered anon outside it's definition scope \
736 substs: &'tcx Substs<'tcx>,
738 let infcx = self.infcx;
742 "instantiate_anon_types: TyAnon(def_id={:?}, substs={:?})",
746 // Use the same type variable if the exact same TyAnon appears more
747 // than once in the return type (e.g. if it's passed to a type alias).
748 if let Some(anon_defn) = self.anon_types.get(&def_id) {
749 return anon_defn.concrete_ty;
751 let span = tcx.def_span(def_id);
752 let ty_var = infcx.next_ty_var(TypeVariableOrigin::TypeInference(span));
754 let predicates_of = tcx.predicates_of(def_id);
756 "instantiate_anon_types: predicates: {:#?}",
759 let bounds = predicates_of.instantiate(tcx, substs);
760 debug!("instantiate_anon_types: bounds={:?}", bounds);
762 let required_region_bounds = tcx.required_region_bounds(ty, bounds.predicates.clone());
764 "instantiate_anon_types: required_region_bounds={:?}",
765 required_region_bounds
768 // make sure that we are in fact defining the *entire* type
769 // e.g. `existential type Foo<T: Bound>: Bar;` needs to be
770 // defined by a function like `fn foo<T: Bound>() -> Foo<T>`.
772 "instantiate_anon_types: param_env: {:#?}",
776 "instantiate_anon_types: generics: {:#?}",
777 tcx.generics_of(def_id),
780 self.anon_types.insert(
785 has_required_region_bounds: !required_region_bounds.is_empty(),
788 debug!("instantiate_anon_types: ty_var={:?}", ty_var);
790 for predicate in bounds.predicates {
791 // Change the predicate to refer to the type variable,
792 // which will be the concrete type, instead of the TyAnon.
793 // This also instantiates nested `impl Trait`.
794 let predicate = self.instantiate_anon_types_in_map(&predicate);
796 let cause = traits::ObligationCause::new(span, self.body_id, traits::SizedReturnType);
798 // Require that the predicate holds for the concrete type.
799 debug!("instantiate_anon_types: predicate={:?}", predicate);
801 .push(traits::Obligation::new(cause, self.param_env, predicate));
808 /// Whether `anon_node_id` is a sibling or a child of a sibling of `def_id`
813 /// pub existential type Baz;
815 /// fn f1() -> Baz { .. }
818 /// fn f2() -> bar::Baz { .. }
822 /// Here, `def_id` will be the `DefId` of the existential type `Baz`.
823 /// `anon_node_id` is the `NodeId` of the reference to Baz -- so either the return type of f1 or f2.
824 /// We will return true if the reference is within the same module as the existential type
825 /// So true for f1, false for f2.
826 pub fn may_define_existential_type(
829 anon_node_id: ast::NodeId,
831 let mut node_id = tcx
833 .as_local_node_id(def_id)
835 // named existential types can be defined by any siblings or
836 // children of siblings
837 let mod_id = tcx.hir.get_parent(anon_node_id);
838 // so we walk up the node tree until we hit the root or the parent
840 while node_id != mod_id && node_id != ast::CRATE_NODE_ID {
841 node_id = tcx.hir.get_parent(node_id);
843 // syntactically we are allowed to define the concrete type