]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/anon_types/mod.rs
Auto merge of #50234 - cramertj:extend, r=alexcrichton
[rust.git] / src / librustc / infer / anon_types / mod.rs
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.
4 //
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.
10
11 use hir::def_id::DefId;
12 use infer::{self, InferCtxt, InferOk, TypeVariableOrigin};
13 use infer::outlives::free_region_map::FreeRegionRelations;
14 use rustc_data_structures::fx::FxHashMap;
15 use syntax::ast;
16 use traits::{self, PredicateObligation};
17 use ty::{self, Ty, TyCtxt, GenericParamDefKind};
18 use ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder};
19 use ty::outlives::Component;
20 use ty::subst::{Kind, Substs, UnpackedKind};
21 use util::nodemap::DefIdMap;
22
23 pub type AnonTypeMap<'tcx> = DefIdMap<AnonTypeDecl<'tcx>>;
24
25 /// Information about the anonymous, abstract types whose values we
26 /// are inferring in this function (these are the `impl Trait` that
27 /// appear in the return type).
28 #[derive(Copy, Clone, Debug)]
29 pub struct AnonTypeDecl<'tcx> {
30     /// The substitutions that we apply to the abstract that that this
31     /// `impl Trait` desugars to. e.g., if:
32     ///
33     ///     fn foo<'a, 'b, T>() -> impl Trait<'a>
34     ///
35     /// winds up desugared to:
36     ///
37     ///     abstract type Foo<'x, T>: Trait<'x>
38     ///     fn foo<'a, 'b, T>() -> Foo<'a, T>
39     ///
40     /// then `substs` would be `['a, T]`.
41     pub substs: &'tcx Substs<'tcx>,
42
43     /// The type variable that represents the value of the abstract type
44     /// that we require. In other words, after we compile this function,
45     /// we will be created a constraint like:
46     ///
47     ///     Foo<'a, T> = ?C
48     ///
49     /// where `?C` is the value of this type variable. =) It may
50     /// naturally refer to the type and lifetime parameters in scope
51     /// in this function, though ultimately it should only reference
52     /// those that are arguments to `Foo` in the constraint above. (In
53     /// other words, `?C` should not include `'b`, even though it's a
54     /// lifetime parameter on `foo`.)
55     pub concrete_ty: Ty<'tcx>,
56
57     /// True if the `impl Trait` bounds include region bounds.
58     /// For example, this would be true for:
59     ///
60     ///     fn foo<'a, 'b, 'c>() -> impl Trait<'c> + 'a + 'b
61     ///
62     /// but false for:
63     ///
64     ///     fn foo<'c>() -> impl Trait<'c>
65     ///
66     /// unless `Trait` was declared like:
67     ///
68     ///     trait Trait<'c>: 'c
69     ///
70     /// in which case it would be true.
71     ///
72     /// This is used during regionck to decide whether we need to
73     /// impose any additional constraints to ensure that region
74     /// variables in `concrete_ty` wind up being constrained to
75     /// something from `substs` (or, at minimum, things that outlive
76     /// the fn body). (Ultimately, writeback is responsible for this
77     /// check.)
78     pub has_required_region_bounds: bool,
79 }
80
81 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
82     /// Replace all anonymized types in `value` with fresh inference variables
83     /// and creates appropriate obligations. For example, given the input:
84     ///
85     ///     impl Iterator<Item = impl Debug>
86     ///
87     /// this method would create two type variables, `?0` and `?1`. It would
88     /// return the type `?0` but also the obligations:
89     ///
90     ///     ?0: Iterator<Item = ?1>
91     ///     ?1: Debug
92     ///
93     /// Moreover, it returns a `AnonTypeMap` that would map `?0` to
94     /// info about the `impl Iterator<..>` type and `?1` to info about
95     /// the `impl Debug` type.
96     ///
97     /// # Parameters
98     ///
99     /// - `parent_def_id` -- we will only instantiate anonymous types
100     ///   with this parent. This is typically the def-id of the function
101     ///   in whose return type anon types are being instantiated.
102     /// - `body_id` -- the body-id with which the resulting obligations should
103     ///   be associated
104     /// - `param_env` -- the in-scope parameter environment to be used for
105     ///   obligations
106     /// - `value` -- the value within which we are instantiating anon types
107     pub fn instantiate_anon_types<T: TypeFoldable<'tcx>>(
108         &self,
109         parent_def_id: DefId,
110         body_id: ast::NodeId,
111         param_env: ty::ParamEnv<'tcx>,
112         value: &T,
113     ) -> InferOk<'tcx, (T, AnonTypeMap<'tcx>)> {
114         debug!(
115             "instantiate_anon_types(value={:?}, parent_def_id={:?}, body_id={:?}, param_env={:?})",
116             value, parent_def_id, body_id, param_env,
117         );
118         let mut instantiator = Instantiator {
119             infcx: self,
120             parent_def_id,
121             body_id,
122             param_env,
123             anon_types: DefIdMap(),
124             obligations: vec![],
125         };
126         let value = instantiator.instantiate_anon_types_in_map(value);
127         InferOk {
128             value: (value, instantiator.anon_types),
129             obligations: instantiator.obligations,
130         }
131     }
132
133     /// Given the map `anon_types` containing the existential `impl
134     /// Trait` types whose underlying, hidden types are being
135     /// inferred, this method adds constraints to the regions
136     /// appearing in those underlying hidden types to ensure that they
137     /// at least do not refer to random scopes within the current
138     /// function. These constraints are not (quite) sufficient to
139     /// guarantee that the regions are actually legal values; that
140     /// final condition is imposed after region inference is done.
141     ///
142     /// # The Problem
143     ///
144     /// Let's work through an example to explain how it works.  Assume
145     /// the current function is as follows:
146     ///
147     /// ```text
148     /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
149     /// ```
150     ///
151     /// Here, we have two `impl Trait` types whose values are being
152     /// inferred (the `impl Bar<'a>` and the `impl
153     /// Bar<'b>`). Conceptually, this is sugar for a setup where we
154     /// define underlying abstract types (`Foo1`, `Foo2`) and then, in
155     /// the return type of `foo`, we *reference* those definitions:
156     ///
157     /// ```text
158     /// abstract type Foo1<'x>: Bar<'x>;
159     /// abstract type Foo2<'x>: Bar<'x>;
160     /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
161     ///                    //  ^^^^ ^^
162     ///                    //  |    |
163     ///                    //  |    substs
164     ///                    //  def_id
165     /// ```
166     ///
167     /// As indicating in the comments above, each of those references
168     /// is (in the compiler) basically a substitution (`substs`)
169     /// applied to the type of a suitable `def_id` (which identifies
170     /// `Foo1` or `Foo2`).
171     ///
172     /// Now, at this point in compilation, what we have done is to
173     /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
174     /// fresh inference variables C1 and C2. We wish to use the values
175     /// of these variables to infer the underlying types of `Foo1` and
176     /// `Foo2`.  That is, this gives rise to higher-order (pattern) unification
177     /// constraints like:
178     ///
179     /// ```text
180     /// for<'a> (Foo1<'a> = C1)
181     /// for<'b> (Foo1<'b> = C2)
182     /// ```
183     ///
184     /// For these equation to be satisfiable, the types `C1` and `C2`
185     /// can only refer to a limited set of regions. For example, `C1`
186     /// can only refer to `'static` and `'a`, and `C2` can only refer
187     /// to `'static` and `'b`. The job of this function is to impose that
188     /// constraint.
189     ///
190     /// Up to this point, C1 and C2 are basically just random type
191     /// inference variables, and hence they may contain arbitrary
192     /// regions. In fact, it is fairly likely that they do! Consider
193     /// this possible definition of `foo`:
194     ///
195     /// ```text
196     /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
197     ///         (&*x, &*y)
198     ///     }
199     /// ```
200     ///
201     /// Here, the values for the concrete types of the two impl
202     /// traits will include inference variables:
203     ///
204     /// ```text
205     /// &'0 i32
206     /// &'1 i32
207     /// ```
208     ///
209     /// Ordinarily, the subtyping rules would ensure that these are
210     /// sufficiently large. But since `impl Bar<'a>` isn't a specific
211     /// type per se, we don't get such constraints by default.  This
212     /// is where this function comes into play. It adds extra
213     /// constraints to ensure that all the regions which appear in the
214     /// inferred type are regions that could validly appear.
215     ///
216     /// This is actually a bit of a tricky constraint in general. We
217     /// want to say that each variable (e.g., `'0`) can only take on
218     /// values that were supplied as arguments to the abstract type
219     /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
220     /// scope. We don't have a constraint quite of this kind in the current
221     /// region checker.
222     ///
223     /// # The Solution
224     ///
225     /// We make use of the constraint that we *do* have in the `<=`
226     /// relation. To do that, we find the "minimum" of all the
227     /// arguments that appear in the substs: that is, some region
228     /// which is less than all the others. In the case of `Foo1<'a>`,
229     /// that would be `'a` (it's the only choice, after all). Then we
230     /// apply that as a least bound to the variables (e.g., `'a <=
231     /// '0`).
232     ///
233     /// In some cases, there is no minimum. Consider this example:
234     ///
235     /// ```text
236     /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
237     /// ```
238     ///
239     /// Here we would report an error, because `'a` and `'b` have no
240     /// relation to one another.
241     ///
242     /// # The `free_region_relations` parameter
243     ///
244     /// The `free_region_relations` argument is used to find the
245     /// "minimum" of the regions supplied to a given abstract type.
246     /// It must be a relation that can answer whether `'a <= 'b`,
247     /// where `'a` and `'b` are regions that appear in the "substs"
248     /// for the abstract type references (the `<'a>` in `Foo1<'a>`).
249     ///
250     /// Note that we do not impose the constraints based on the
251     /// generic regions from the `Foo1` definition (e.g., `'x`). This
252     /// is because the constraints we are imposing here is basically
253     /// the concern of the one generating the constraining type C1,
254     /// which is the current function. It also means that we can
255     /// take "implied bounds" into account in some cases:
256     ///
257     /// ```text
258     /// trait SomeTrait<'a, 'b> { }
259     /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. }
260     /// ```
261     ///
262     /// Here, the fact that `'b: 'a` is known only because of the
263     /// implied bounds from the `&'a &'b u32` parameter, and is not
264     /// "inherent" to the abstract type definition.
265     ///
266     /// # Parameters
267     ///
268     /// - `anon_types` -- the map produced by `instantiate_anon_types`
269     /// - `free_region_relations` -- something that can be used to relate
270     ///   the free regions (`'a`) that appear in the impl trait.
271     pub fn constrain_anon_types<FRR: FreeRegionRelations<'tcx>>(
272         &self,
273         anon_types: &AnonTypeMap<'tcx>,
274         free_region_relations: &FRR,
275     ) {
276         debug!("constrain_anon_types()");
277
278         for (&def_id, anon_defn) in anon_types {
279             self.constrain_anon_type(def_id, anon_defn, free_region_relations);
280         }
281     }
282
283     fn constrain_anon_type<FRR: FreeRegionRelations<'tcx>>(
284         &self,
285         def_id: DefId,
286         anon_defn: &AnonTypeDecl<'tcx>,
287         free_region_relations: &FRR,
288     ) {
289         debug!("constrain_anon_type()");
290         debug!("constrain_anon_type: def_id={:?}", def_id);
291         debug!("constrain_anon_type: anon_defn={:#?}", anon_defn);
292
293         let concrete_ty = self.resolve_type_vars_if_possible(&anon_defn.concrete_ty);
294
295         debug!("constrain_anon_type: concrete_ty={:?}", concrete_ty);
296
297         let abstract_type_generics = self.tcx.generics_of(def_id);
298
299         let span = self.tcx.def_span(def_id);
300
301         // If there are required region bounds, we can just skip
302         // ahead.  There will already be a registered region
303         // obligation related `concrete_ty` to those regions.
304         if anon_defn.has_required_region_bounds {
305             return;
306         }
307
308         // There were no `required_region_bounds`,
309         // so we have to search for a `least_region`.
310         // Go through all the regions used as arguments to the
311         // abstract type. These are the parameters to the abstract
312         // type; so in our example above, `substs` would contain
313         // `['a]` for the first impl trait and `'b` for the
314         // second.
315         let mut least_region = None;
316         for param in &abstract_type_generics.params {
317             match param.kind {
318                 GenericParamDefKind::Lifetime => {}
319                 _ => continue
320             }
321             // Get the value supplied for this region from the substs.
322             let subst_arg = anon_defn.substs.region_at(param.index as usize);
323
324             // Compute the least upper bound of it with the other regions.
325             debug!("constrain_anon_types: least_region={:?}", least_region);
326             debug!("constrain_anon_types: subst_arg={:?}", subst_arg);
327             match least_region {
328                 None => least_region = Some(subst_arg),
329                 Some(lr) => {
330                     if free_region_relations.sub_free_regions(lr, subst_arg) {
331                         // keep the current least region
332                     } else if free_region_relations.sub_free_regions(subst_arg, lr) {
333                         // switch to `subst_arg`
334                         least_region = Some(subst_arg);
335                     } else {
336                         // There are two regions (`lr` and
337                         // `subst_arg`) which are not relatable. We can't
338                         // find a best choice.
339                         self.tcx
340                             .sess
341                             .struct_span_err(span, "ambiguous lifetime bound in `impl Trait`")
342                             .span_label(
343                                 span,
344                                 format!("neither `{}` nor `{}` outlives the other", lr, subst_arg),
345                             )
346                             .emit();
347
348                         least_region = Some(self.tcx.mk_region(ty::ReEmpty));
349                         break;
350                     }
351                 }
352             }
353         }
354
355         let least_region = least_region.unwrap_or(self.tcx.types.re_static);
356         debug!("constrain_anon_types: least_region={:?}", least_region);
357
358         // Require that the type `concrete_ty` outlives
359         // `least_region`, modulo any type parameters that appear
360         // in the type, which we ignore. This is because impl
361         // trait values are assumed to capture all the in-scope
362         // type parameters. This little loop here just invokes
363         // `outlives` repeatedly, draining all the nested
364         // obligations that result.
365         let mut types = vec![concrete_ty];
366         let bound_region = |r| self.sub_regions(infer::CallReturn(span), least_region, r);
367         while let Some(ty) = types.pop() {
368             let mut components = self.tcx.outlives_components(ty);
369             while let Some(component) = components.pop() {
370                 match component {
371                     Component::Region(r) => {
372                         bound_region(r);
373                     }
374
375                     Component::Param(_) => {
376                         // ignore type parameters like `T`, they are captured
377                         // implicitly by the `impl Trait`
378                     }
379
380                     Component::UnresolvedInferenceVariable(_) => {
381                         // we should get an error that more type
382                         // annotations are needed in this case
383                         self.tcx
384                             .sess
385                             .delay_span_bug(span, "unresolved inf var in anon");
386                     }
387
388                     Component::Projection(ty::ProjectionTy {
389                         substs,
390                         item_def_id: _,
391                     }) => {
392                         for r in substs.regions() {
393                             bound_region(r);
394                         }
395                         types.extend(substs.types());
396                     }
397
398                     Component::EscapingProjection(more_components) => {
399                         components.extend(more_components);
400                     }
401                 }
402             }
403         }
404     }
405
406     /// Given the fully resolved, instantiated type for an anonymous
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:
411     ///
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>) { .. }
415     ///
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.
419     ///
420     /// (*) C1 and C2 were introduced in the comments on
421     /// `constrain_anon_types`. Read that comment for more context.
422     ///
423     /// # Parameters
424     ///
425     /// - `def_id`, the `impl Trait` type
426     /// - `anon_defn`, the anonymous definition created in `instantiate_anon_types`
427     /// - `instantiated_ty`, the inferred type C1 -- fully resolved, lifted version of
428     ///   `anon_defn.concrete_ty`
429     pub fn infer_anon_definition_from_instantiation(
430         &self,
431         def_id: DefId,
432         anon_defn: &AnonTypeDecl<'tcx>,
433         instantiated_ty: Ty<'gcx>,
434     ) -> Ty<'gcx> {
435         debug!(
436             "infer_anon_definition_from_instantiation(instantiated_ty={:?})",
437             instantiated_ty
438         );
439
440         let gcx = self.tcx.global_tcx();
441
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
447         // shifting.
448         let id_substs = Substs::identity_for_item(gcx, def_id);
449         let map: FxHashMap<Kind<'tcx>, Kind<'gcx>> = anon_defn
450             .substs
451             .iter()
452             .enumerate()
453             .map(|(index, subst)| (*subst, id_substs[index]))
454             .collect();
455
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.
459         let definition_ty =
460             instantiated_ty.fold_with(&mut ReverseMapper::new(
461                 self.tcx,
462                 self.is_tainted_by_errors(),
463                 def_id,
464                 map,
465                 instantiated_ty,
466             ));
467         debug!(
468             "infer_anon_definition_from_instantiation: definition_ty={:?}",
469             definition_ty
470         );
471
472         // We can unwrap here because our reverse mapper always
473         // produces things with 'gcx lifetime, though the type folder
474         // obscures that.
475         let definition_ty = gcx.lift(&definition_ty).unwrap();
476
477         definition_ty
478     }
479 }
480
481 struct ReverseMapper<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
482     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
483
484     /// If errors have already been reported in this fn, we suppress
485     /// our own errors because they are sometimes derivative.
486     tainted_by_errors: bool,
487
488     anon_type_def_id: DefId,
489     map: FxHashMap<Kind<'tcx>, Kind<'gcx>>,
490     map_missing_regions_to_empty: bool,
491
492     /// initially `Some`, set to `None` once error has been reported
493     hidden_ty: Option<Ty<'tcx>>,
494 }
495
496 impl<'cx, 'gcx, 'tcx> ReverseMapper<'cx, 'gcx, 'tcx> {
497     fn new(
498         tcx: TyCtxt<'cx, 'gcx, 'tcx>,
499         tainted_by_errors: bool,
500         anon_type_def_id: DefId,
501         map: FxHashMap<Kind<'tcx>, Kind<'gcx>>,
502         hidden_ty: Ty<'tcx>,
503     ) -> Self {
504         Self {
505             tcx,
506             tainted_by_errors,
507             anon_type_def_id,
508             map,
509             map_missing_regions_to_empty: false,
510             hidden_ty: Some(hidden_ty),
511         }
512     }
513
514     fn fold_kind_mapping_missing_regions_to_empty(&mut self, kind: Kind<'tcx>) -> Kind<'tcx> {
515         assert!(!self.map_missing_regions_to_empty);
516         self.map_missing_regions_to_empty = true;
517         let kind = kind.fold_with(self);
518         self.map_missing_regions_to_empty = false;
519         kind
520     }
521
522     fn fold_kind_normally(&mut self, kind: Kind<'tcx>) -> Kind<'tcx> {
523         assert!(!self.map_missing_regions_to_empty);
524         kind.fold_with(self)
525     }
526 }
527
528 impl<'cx, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ReverseMapper<'cx, 'gcx, 'tcx> {
529     fn tcx(&self) -> TyCtxt<'_, 'gcx, 'tcx> {
530         self.tcx
531     }
532
533     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
534         match r {
535             // ignore bound regions that appear in the type (e.g., this
536             // would ignore `'r` in a type like `for<'r> fn(&'r u32)`.
537             ty::ReLateBound(..) |
538
539             // ignore `'static`, as that can appear anywhere
540             ty::ReStatic |
541
542             // ignore `ReScope`, as that can appear anywhere
543             // See `src/test/run-pass/issue-49556.rs` for example.
544             ty::ReScope(..) => return r,
545
546             _ => { }
547         }
548
549         match self.map.get(&r.into()).map(|k| k.unpack()) {
550             Some(UnpackedKind::Lifetime(r1)) => r1,
551             Some(u) => panic!("region mapped to unexpected kind: {:?}", u),
552             None => {
553                 if !self.map_missing_regions_to_empty && !self.tainted_by_errors {
554                     if let Some(hidden_ty) = self.hidden_ty.take() {
555                         let span = self.tcx.def_span(self.anon_type_def_id);
556                         let mut err = struct_span_err!(
557                             self.tcx.sess,
558                             span,
559                             E0909,
560                             "hidden type for `impl Trait` captures lifetime that \
561                              does not appear in bounds",
562                         );
563
564                         // Assuming regionck succeeded, then we must
565                         // be capturing *some* region from the fn
566                         // header, and hence it must be free, so it's
567                         // ok to invoke this fn (which doesn't accept
568                         // all regions, and would ICE if an
569                         // inappropriate region is given). We check
570                         // `is_tainted_by_errors` by errors above, so
571                         // we don't get in here unless regionck
572                         // succeeded. (Note also that if regionck
573                         // failed, then the regions we are attempting
574                         // to map here may well be giving errors
575                         // *because* the constraints were not
576                         // satisfiable.)
577                         self.tcx.note_and_explain_free_region(
578                             &mut err,
579                             &format!("hidden type `{}` captures ", hidden_ty),
580                             r,
581                             ""
582                         );
583
584                         err.emit();
585                     }
586                 }
587                 self.tcx.types.re_empty
588             },
589         }
590     }
591
592     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
593         match ty.sty {
594             ty::TyClosure(def_id, substs) => {
595                 // I am a horrible monster and I pray for death. When
596                 // we encounter a closure here, it is always a closure
597                 // from within the function that we are currently
598                 // type-checking -- one that is now being encapsulated
599                 // in an existential abstract type. Ideally, we would
600                 // go through the types/lifetimes that it references
601                 // and treat them just like we would any other type,
602                 // which means we would error out if we find any
603                 // reference to a type/region that is not in the
604                 // "reverse map".
605                 //
606                 // **However,** in the case of closures, there is a
607                 // somewhat subtle (read: hacky) consideration. The
608                 // problem is that our closure types currently include
609                 // all the lifetime parameters declared on the
610                 // enclosing function, even if they are unused by the
611                 // closure itself. We can't readily filter them out,
612                 // so here we replace those values with `'empty`. This
613                 // can't really make a difference to the rest of the
614                 // compiler; those regions are ignored for the
615                 // outlives relation, and hence don't affect trait
616                 // selection or auto traits, and they are erased
617                 // during codegen.
618
619                 let generics = self.tcx.generics_of(def_id);
620                 let substs = self.tcx.mk_substs(substs.substs.iter().enumerate().map(
621                     |(index, &kind)| {
622                         if index < generics.parent_count {
623                             // Accommodate missing regions in the parent kinds...
624                             self.fold_kind_mapping_missing_regions_to_empty(kind)
625                         } else {
626                             // ...but not elsewhere.
627                             self.fold_kind_normally(kind)
628                         }
629                     },
630                 ));
631
632                 self.tcx.mk_closure(def_id, ty::ClosureSubsts { substs })
633             }
634
635             _ => ty.super_fold_with(self),
636         }
637     }
638 }
639
640 struct Instantiator<'a, 'gcx: 'tcx, 'tcx: 'a> {
641     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
642     parent_def_id: DefId,
643     body_id: ast::NodeId,
644     param_env: ty::ParamEnv<'tcx>,
645     anon_types: AnonTypeMap<'tcx>,
646     obligations: Vec<PredicateObligation<'tcx>>,
647 }
648
649 impl<'a, 'gcx, 'tcx> Instantiator<'a, 'gcx, 'tcx> {
650     fn instantiate_anon_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
651         debug!("instantiate_anon_types_in_map(value={:?})", value);
652         let tcx = self.infcx.tcx;
653         value.fold_with(&mut BottomUpFolder {
654             tcx,
655             fldop: |ty| {
656                 if let ty::TyAnon(def_id, substs) = ty.sty {
657                     // Check that this is `impl Trait` type is
658                     // declared by `parent_def_id` -- i.e., one whose
659                     // value we are inferring.  At present, this is
660                     // always true during the first phase of
661                     // type-check, but not always true later on during
662                     // NLL. Once we support named abstract types more fully,
663                     // this same scenario will be able to arise during all phases.
664                     //
665                     // Here is an example using `abstract type` that indicates
666                     // the distinction we are checking for:
667                     //
668                     // ```rust
669                     // mod a {
670                     //   pub abstract type Foo: Iterator;
671                     //   pub fn make_foo() -> Foo { .. }
672                     // }
673                     //
674                     // mod b {
675                     //   fn foo() -> a::Foo { a::make_foo() }
676                     // }
677                     // ```
678                     //
679                     // Here, the return type of `foo` references a
680                     // `TyAnon` indeed, but not one whose value is
681                     // presently being inferred. You can get into a
682                     // similar situation with closure return types
683                     // today:
684                     //
685                     // ```rust
686                     // fn foo() -> impl Iterator { .. }
687                     // fn bar() {
688                     //     let x = || foo(); // returns the Anon assoc with `foo`
689                     // }
690                     // ```
691                     if let Some(anon_node_id) = tcx.hir.as_local_node_id(def_id) {
692                         let anon_parent_node_id = tcx.hir.get_parent(anon_node_id);
693                         let anon_parent_def_id = tcx.hir.local_def_id(anon_parent_node_id);
694                         if self.parent_def_id == anon_parent_def_id {
695                             return self.fold_anon_ty(ty, def_id, substs);
696                         }
697
698                         debug!(
699                             "instantiate_anon_types_in_map: \
700                              encountered anon with wrong parent \
701                              def_id={:?} \
702                              anon_parent_def_id={:?}",
703                             def_id, anon_parent_def_id
704                         );
705                     }
706                 }
707
708                 ty
709             },
710         })
711     }
712
713     fn fold_anon_ty(
714         &mut self,
715         ty: Ty<'tcx>,
716         def_id: DefId,
717         substs: &'tcx Substs<'tcx>,
718     ) -> Ty<'tcx> {
719         let infcx = self.infcx;
720         let tcx = infcx.tcx;
721
722         debug!(
723             "instantiate_anon_types: TyAnon(def_id={:?}, substs={:?})",
724             def_id, substs
725         );
726
727         // Use the same type variable if the exact same TyAnon appears more
728         // than once in the return type (e.g. if it's passed to a type alias).
729         if let Some(anon_defn) = self.anon_types.get(&def_id) {
730             return anon_defn.concrete_ty;
731         }
732         let span = tcx.def_span(def_id);
733         let ty_var = infcx.next_ty_var(TypeVariableOrigin::TypeInference(span));
734
735         let predicates_of = tcx.predicates_of(def_id);
736         let bounds = predicates_of.instantiate(tcx, substs);
737         debug!("instantiate_anon_types: bounds={:?}", bounds);
738
739         let required_region_bounds = tcx.required_region_bounds(ty, bounds.predicates.clone());
740         debug!(
741             "instantiate_anon_types: required_region_bounds={:?}",
742             required_region_bounds
743         );
744
745         self.anon_types.insert(
746             def_id,
747             AnonTypeDecl {
748                 substs,
749                 concrete_ty: ty_var,
750                 has_required_region_bounds: !required_region_bounds.is_empty(),
751             },
752         );
753         debug!("instantiate_anon_types: ty_var={:?}", ty_var);
754
755         for predicate in bounds.predicates {
756             // Change the predicate to refer to the type variable,
757             // which will be the concrete type, instead of the TyAnon.
758             // This also instantiates nested `impl Trait`.
759             let predicate = self.instantiate_anon_types_in_map(&predicate);
760
761             let cause = traits::ObligationCause::new(span, self.body_id, traits::SizedReturnType);
762
763             // Require that the predicate holds for the concrete type.
764             debug!("instantiate_anon_types: predicate={:?}", predicate);
765             self.obligations
766                 .push(traits::Obligation::new(cause, self.param_env, predicate));
767         }
768
769         ty_var
770     }
771 }