]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/anon_types/mod.rs
Rollup merge of #52540 - alexcrichton:tweak-script, r=kennytm
[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 hir;
13 use infer::{self, InferCtxt, InferOk, TypeVariableOrigin};
14 use infer::outlives::free_region_map::FreeRegionRelations;
15 use rustc_data_structures::fx::FxHashMap;
16 use syntax::ast;
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;
23
24 pub type AnonTypeMap<'tcx> = DefIdMap<AnonTypeDecl<'tcx>>;
25
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:
33     ///
34     ///     fn foo<'a, 'b, T>() -> impl Trait<'a>
35     ///
36     /// winds up desugared to:
37     ///
38     ///     abstract type Foo<'x, T>: Trait<'x>
39     ///     fn foo<'a, 'b, T>() -> Foo<'a, T>
40     ///
41     /// then `substs` would be `['a, T]`.
42     pub substs: &'tcx Substs<'tcx>,
43
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:
47     ///
48     ///     Foo<'a, T> = ?C
49     ///
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>,
57
58     /// True if the `impl Trait` bounds include region bounds.
59     /// For example, this would be true for:
60     ///
61     ///     fn foo<'a, 'b, 'c>() -> impl Trait<'c> + 'a + 'b
62     ///
63     /// but false for:
64     ///
65     ///     fn foo<'c>() -> impl Trait<'c>
66     ///
67     /// unless `Trait` was declared like:
68     ///
69     ///     trait Trait<'c>: 'c
70     ///
71     /// in which case it would be true.
72     ///
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
78     /// check.)
79     pub has_required_region_bounds: bool,
80 }
81
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:
85     ///
86     ///     impl Iterator<Item = impl Debug>
87     ///
88     /// this method would create two type variables, `?0` and `?1`. It would
89     /// return the type `?0` but also the obligations:
90     ///
91     ///     ?0: Iterator<Item = ?1>
92     ///     ?1: Debug
93     ///
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.
97     ///
98     /// # Parameters
99     ///
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
104     ///   be associated
105     /// - `param_env` -- the in-scope parameter environment to be used for
106     ///   obligations
107     /// - `value` -- the value within which we are instantiating anon types
108     pub fn instantiate_anon_types<T: TypeFoldable<'tcx>>(
109         &self,
110         parent_def_id: DefId,
111         body_id: ast::NodeId,
112         param_env: ty::ParamEnv<'tcx>,
113         value: &T,
114     ) -> InferOk<'tcx, (T, AnonTypeMap<'tcx>)> {
115         debug!(
116             "instantiate_anon_types(value={:?}, parent_def_id={:?}, body_id={:?}, param_env={:?})",
117             value, parent_def_id, body_id, param_env,
118         );
119         let mut instantiator = Instantiator {
120             infcx: self,
121             parent_def_id,
122             body_id,
123             param_env,
124             anon_types: DefIdMap(),
125             obligations: vec![],
126         };
127         let value = instantiator.instantiate_anon_types_in_map(value);
128         InferOk {
129             value: (value, instantiator.anon_types),
130             obligations: instantiator.obligations,
131         }
132     }
133
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.
142     ///
143     /// # The Problem
144     ///
145     /// Let's work through an example to explain how it works.  Assume
146     /// the current function is as follows:
147     ///
148     /// ```text
149     /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
150     /// ```
151     ///
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:
157     ///
158     /// ```text
159     /// abstract type Foo1<'x>: Bar<'x>;
160     /// abstract type Foo2<'x>: Bar<'x>;
161     /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
162     ///                    //  ^^^^ ^^
163     ///                    //  |    |
164     ///                    //  |    substs
165     ///                    //  def_id
166     /// ```
167     ///
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`).
172     ///
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:
179     ///
180     /// ```text
181     /// for<'a> (Foo1<'a> = C1)
182     /// for<'b> (Foo1<'b> = C2)
183     /// ```
184     ///
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
189     /// constraint.
190     ///
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`:
195     ///
196     /// ```text
197     /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
198     ///         (&*x, &*y)
199     ///     }
200     /// ```
201     ///
202     /// Here, the values for the concrete types of the two impl
203     /// traits will include inference variables:
204     ///
205     /// ```text
206     /// &'0 i32
207     /// &'1 i32
208     /// ```
209     ///
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.
216     ///
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
222     /// region checker.
223     ///
224     /// # The Solution
225     ///
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 <=
232     /// '0`).
233     ///
234     /// In some cases, there is no minimum. Consider this example:
235     ///
236     /// ```text
237     /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
238     /// ```
239     ///
240     /// Here we would report an error, because `'a` and `'b` have no
241     /// relation to one another.
242     ///
243     /// # The `free_region_relations` parameter
244     ///
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>`).
250     ///
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:
257     ///
258     /// ```text
259     /// trait SomeTrait<'a, 'b> { }
260     /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. }
261     /// ```
262     ///
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.
266     ///
267     /// # Parameters
268     ///
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>>(
273         &self,
274         anon_types: &AnonTypeMap<'tcx>,
275         free_region_relations: &FRR,
276     ) {
277         debug!("constrain_anon_types()");
278
279         for (&def_id, anon_defn) in anon_types {
280             self.constrain_anon_type(def_id, anon_defn, free_region_relations);
281         }
282     }
283
284     fn constrain_anon_type<FRR: FreeRegionRelations<'tcx>>(
285         &self,
286         def_id: DefId,
287         anon_defn: &AnonTypeDecl<'tcx>,
288         free_region_relations: &FRR,
289     ) {
290         debug!("constrain_anon_type()");
291         debug!("constrain_anon_type: def_id={:?}", def_id);
292         debug!("constrain_anon_type: anon_defn={:#?}", anon_defn);
293
294         let concrete_ty = self.resolve_type_vars_if_possible(&anon_defn.concrete_ty);
295
296         debug!("constrain_anon_type: concrete_ty={:?}", concrete_ty);
297
298         let abstract_type_generics = self.tcx.generics_of(def_id);
299
300         let span = self.tcx.def_span(def_id);
301
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 {
306             return;
307         }
308
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
315         // second.
316         let mut least_region = None;
317         for param in &abstract_type_generics.params {
318             match param.kind {
319                 GenericParamDefKind::Lifetime => {}
320                 _ => continue
321             }
322             // Get the value supplied for this region from the substs.
323             let subst_arg = anon_defn.substs.region_at(param.index as usize);
324
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);
328             match least_region {
329                 None => least_region = Some(subst_arg),
330                 Some(lr) => {
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);
336                     } else {
337                         // There are two regions (`lr` and
338                         // `subst_arg`) which are not relatable. We can't
339                         // find a best choice.
340                         self.tcx
341                             .sess
342                             .struct_span_err(span, "ambiguous lifetime bound in `impl Trait`")
343                             .span_label(
344                                 span,
345                                 format!("neither `{}` nor `{}` outlives the other", lr, subst_arg),
346                             )
347                             .emit();
348
349                         least_region = Some(self.tcx.mk_region(ty::ReEmpty));
350                         break;
351                     }
352                 }
353             }
354         }
355
356         let least_region = least_region.unwrap_or(self.tcx.types.re_static);
357         debug!("constrain_anon_types: least_region={:?}", least_region);
358
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() {
371                 match component {
372                     Component::Region(r) => {
373                         bound_region(r);
374                     }
375
376                     Component::Param(_) => {
377                         // ignore type parameters like `T`, they are captured
378                         // implicitly by the `impl Trait`
379                     }
380
381                     Component::UnresolvedInferenceVariable(_) => {
382                         // we should get an error that more type
383                         // annotations are needed in this case
384                         self.tcx
385                             .sess
386                             .delay_span_bug(span, "unresolved inf var in anon");
387                     }
388
389                     Component::Projection(ty::ProjectionTy {
390                         substs,
391                         item_def_id: _,
392                     }) => {
393                         for r in substs.regions() {
394                             bound_region(r);
395                         }
396                         types.extend(substs.types());
397                     }
398
399                     Component::EscapingProjection(more_components) => {
400                         components.extend(more_components);
401                     }
402                 }
403             }
404         }
405     }
406
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:
412     ///
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>) { .. }
416     ///
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.
420     ///
421     /// (*) C1 and C2 were introduced in the comments on
422     /// `constrain_anon_types`. Read that comment for more context.
423     ///
424     /// # Parameters
425     ///
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(
431         &self,
432         def_id: DefId,
433         anon_defn: &AnonTypeDecl<'tcx>,
434         instantiated_ty: Ty<'gcx>,
435     ) -> Ty<'gcx> {
436         debug!(
437             "infer_anon_definition_from_instantiation(def_id={:?}, instantiated_ty={:?})",
438             def_id, instantiated_ty
439         );
440
441         let gcx = self.tcx.global_tcx();
442
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
448         // shifting.
449         let id_substs = Substs::identity_for_item(gcx, def_id);
450         let map: FxHashMap<Kind<'tcx>, Kind<'gcx>> = anon_defn
451             .substs
452             .iter()
453             .enumerate()
454             .map(|(index, subst)| (*subst, id_substs[index]))
455             .collect();
456
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.
460         let definition_ty =
461             instantiated_ty.fold_with(&mut ReverseMapper::new(
462                 self.tcx,
463                 self.is_tainted_by_errors(),
464                 def_id,
465                 map,
466                 instantiated_ty,
467             ));
468         debug!(
469             "infer_anon_definition_from_instantiation: definition_ty={:?}",
470             definition_ty
471         );
472
473         // We can unwrap here because our reverse mapper always
474         // produces things with 'gcx lifetime, though the type folder
475         // obscures that.
476         let definition_ty = gcx.lift(&definition_ty).unwrap();
477
478         definition_ty
479     }
480 }
481
482 struct ReverseMapper<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
483     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
484
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,
488
489     anon_type_def_id: DefId,
490     map: FxHashMap<Kind<'tcx>, Kind<'gcx>>,
491     map_missing_regions_to_empty: bool,
492
493     /// initially `Some`, set to `None` once error has been reported
494     hidden_ty: Option<Ty<'tcx>>,
495 }
496
497 impl<'cx, 'gcx, 'tcx> ReverseMapper<'cx, 'gcx, 'tcx> {
498     fn new(
499         tcx: TyCtxt<'cx, 'gcx, 'tcx>,
500         tainted_by_errors: bool,
501         anon_type_def_id: DefId,
502         map: FxHashMap<Kind<'tcx>, Kind<'gcx>>,
503         hidden_ty: Ty<'tcx>,
504     ) -> Self {
505         Self {
506             tcx,
507             tainted_by_errors,
508             anon_type_def_id,
509             map,
510             map_missing_regions_to_empty: false,
511             hidden_ty: Some(hidden_ty),
512         }
513     }
514
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;
520         kind
521     }
522
523     fn fold_kind_normally(&mut self, kind: Kind<'tcx>) -> Kind<'tcx> {
524         assert!(!self.map_missing_regions_to_empty);
525         kind.fold_with(self)
526     }
527 }
528
529 impl<'cx, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ReverseMapper<'cx, 'gcx, 'tcx> {
530     fn tcx(&self) -> TyCtxt<'_, 'gcx, 'tcx> {
531         self.tcx
532     }
533
534     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
535         match r {
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(..) |
539
540             // ignore `'static`, as that can appear anywhere
541             ty::ReStatic |
542
543             // ignore `ReScope`, as that can appear anywhere
544             // See `src/test/run-pass/issue-49556.rs` for example.
545             ty::ReScope(..) => return r,
546
547             _ => { }
548         }
549
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),
553             None => {
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!(
558                             self.tcx.sess,
559                             span,
560                             E0700,
561                             "hidden type for `impl Trait` captures lifetime that \
562                              does not appear in bounds",
563                         );
564
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
577                         // satisfiable.)
578                         self.tcx.note_and_explain_free_region(
579                             &mut err,
580                             &format!("hidden type `{}` captures ", hidden_ty),
581                             r,
582                             ""
583                         );
584
585                         err.emit();
586                     }
587                 }
588                 self.tcx.types.re_empty
589             },
590         }
591     }
592
593     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
594         match ty.sty {
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
605                 // "reverse map".
606                 //
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
618                 // during codegen.
619
620                 let generics = self.tcx.generics_of(def_id);
621                 let substs = self.tcx.mk_substs(substs.substs.iter().enumerate().map(
622                     |(index, &kind)| {
623                         if index < generics.parent_count {
624                             // Accommodate missing regions in the parent kinds...
625                             self.fold_kind_mapping_missing_regions_to_empty(kind)
626                         } else {
627                             // ...but not elsewhere.
628                             self.fold_kind_normally(kind)
629                         }
630                     },
631                 ));
632
633                 self.tcx.mk_closure(def_id, ty::ClosureSubsts { substs })
634             }
635
636             _ => ty.super_fold_with(self),
637         }
638     }
639 }
640
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>>,
648 }
649
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 {
655             tcx,
656             reg_op: |reg| reg,
657             fldop: |ty| {
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.
666                     //
667                     // Here is an example using `abstract type` that indicates
668                     // the distinction we are checking for:
669                     //
670                     // ```rust
671                     // mod a {
672                     //   pub abstract type Foo: Iterator;
673                     //   pub fn make_foo() -> Foo { .. }
674                     // }
675                     //
676                     // mod b {
677                     //   fn foo() -> a::Foo { a::make_foo() }
678                     // }
679                     // ```
680                     //
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
685                     // today:
686                     //
687                     // ```rust
688                     // fn foo() -> impl Iterator { .. }
689                     // fn bar() {
690                     //     let x = || foo(); // returns the Anon assoc with `foo`
691                     // }
692                     // ```
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 {
695                             // impl trait
696                             hir::ItemKind::Existential(hir::ExistTy {
697                                 impl_trait_fn: Some(parent),
698                                 ..
699                             }) => parent == self.parent_def_id,
700                             // named existential types
701                             hir::ItemKind::Existential(hir::ExistTy {
702                                 impl_trait_fn: None,
703                                 ..
704                             }) => may_define_existential_type(
705                                 tcx,
706                                 self.parent_def_id,
707                                 anon_node_id,
708                             ),
709                             _ => {
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)
712                             },
713                         };
714                         if in_definition_scope {
715                             return self.fold_anon_ty(ty, def_id, substs);
716                         }
717
718                         debug!(
719                             "instantiate_anon_types_in_map: \
720                              encountered anon outside it's definition scope \
721                              def_id={:?}",
722                             def_id,
723                         );
724                     }
725                 }
726
727                 ty
728             },
729         })
730     }
731
732     fn fold_anon_ty(
733         &mut self,
734         ty: Ty<'tcx>,
735         def_id: DefId,
736         substs: &'tcx Substs<'tcx>,
737     ) -> Ty<'tcx> {
738         let infcx = self.infcx;
739         let tcx = infcx.tcx;
740
741         debug!(
742             "instantiate_anon_types: TyAnon(def_id={:?}, substs={:?})",
743             def_id, substs
744         );
745
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;
750         }
751         let span = tcx.def_span(def_id);
752         let ty_var = infcx.next_ty_var(TypeVariableOrigin::TypeInference(span));
753
754         let predicates_of = tcx.predicates_of(def_id);
755         debug!(
756             "instantiate_anon_types: predicates: {:#?}",
757             predicates_of,
758         );
759         let bounds = predicates_of.instantiate(tcx, substs);
760         debug!("instantiate_anon_types: bounds={:?}", bounds);
761
762         let required_region_bounds = tcx.required_region_bounds(ty, bounds.predicates.clone());
763         debug!(
764             "instantiate_anon_types: required_region_bounds={:?}",
765             required_region_bounds
766         );
767
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>`.
771         debug!(
772             "instantiate_anon_types: param_env: {:#?}",
773             self.param_env,
774         );
775         debug!(
776             "instantiate_anon_types: generics: {:#?}",
777             tcx.generics_of(def_id),
778         );
779
780         self.anon_types.insert(
781             def_id,
782             AnonTypeDecl {
783                 substs,
784                 concrete_ty: ty_var,
785                 has_required_region_bounds: !required_region_bounds.is_empty(),
786             },
787         );
788         debug!("instantiate_anon_types: ty_var={:?}", ty_var);
789
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);
795
796             let cause = traits::ObligationCause::new(span, self.body_id, traits::SizedReturnType);
797
798             // Require that the predicate holds for the concrete type.
799             debug!("instantiate_anon_types: predicate={:?}", predicate);
800             self.obligations
801                 .push(traits::Obligation::new(cause, self.param_env, predicate));
802         }
803
804         ty_var
805     }
806 }
807
808 /// Whether `anon_node_id` is a sibling or a child of a sibling of `def_id`
809 ///
810 /// ```rust
811 /// pub mod foo {
812 ///     pub mod bar {
813 ///         pub existential type Baz;
814 ///
815 ///         fn f1() -> Baz { .. }
816 ///     }
817 ///
818 ///     fn f2() -> bar::Baz { .. }
819 /// }
820 /// ```
821 ///
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(
827     tcx: TyCtxt,
828     def_id: DefId,
829     anon_node_id: ast::NodeId,
830 ) -> bool {
831     let mut node_id = tcx
832         .hir
833         .as_local_node_id(def_id)
834         .unwrap();
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
839     // of the anon type
840     while node_id != mod_id && node_id != ast::CRATE_NODE_ID {
841         node_id = tcx.hir.get_parent(node_id);
842     }
843     // syntactically we are allowed to define the concrete type
844     node_id == mod_id
845 }