]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/opaque_types/mod.rs
rename from "in constraint" to "pick constraint"
[rust.git] / src / librustc / infer / opaque_types / mod.rs
1 use crate::hir;
2 use crate::hir::def_id::DefId;
3 use crate::hir::Node;
4 use crate::infer::outlives::free_region_map::FreeRegionRelations;
5 use crate::infer::{self, InferCtxt, InferOk, TypeVariableOrigin, TypeVariableOriginKind};
6 use crate::traits::{self, PredicateObligation};
7 use crate::ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder, TypeVisitor};
8 use crate::ty::subst::{InternalSubsts, Kind, SubstsRef, UnpackedKind};
9 use crate::ty::{self, GenericParamDefKind, Ty, TyCtxt};
10 use crate::util::nodemap::DefIdMap;
11 use rustc_data_structures::fx::FxHashMap;
12 use std::rc::Rc;
13 use syntax::source_map::Span;
14
15 pub type OpaqueTypeMap<'tcx> = DefIdMap<OpaqueTypeDecl<'tcx>>;
16
17 /// Information about the opaque, abstract types whose values we
18 /// are inferring in this function (these are the `impl Trait` that
19 /// appear in the return type).
20 #[derive(Copy, Clone, Debug)]
21 pub struct OpaqueTypeDecl<'tcx> {
22     /// The substitutions that we apply to the abstract that this
23     /// `impl Trait` desugars to. e.g., if:
24     ///
25     ///     fn foo<'a, 'b, T>() -> impl Trait<'a>
26     ///
27     /// winds up desugared to:
28     ///
29     ///     abstract type Foo<'x, X>: Trait<'x>
30     ///     fn foo<'a, 'b, T>() -> Foo<'a, T>
31     ///
32     /// then `substs` would be `['a, T]`.
33     pub substs: SubstsRef<'tcx>,
34
35     /// The type variable that represents the value of the abstract type
36     /// that we require. In other words, after we compile this function,
37     /// we will be created a constraint like:
38     ///
39     ///     Foo<'a, T> = ?C
40     ///
41     /// where `?C` is the value of this type variable. =) It may
42     /// naturally refer to the type and lifetime parameters in scope
43     /// in this function, though ultimately it should only reference
44     /// those that are arguments to `Foo` in the constraint above. (In
45     /// other words, `?C` should not include `'b`, even though it's a
46     /// lifetime parameter on `foo`.)
47     pub concrete_ty: Ty<'tcx>,
48
49     /// Returns `true` if the `impl Trait` bounds include region bounds.
50     /// For example, this would be true for:
51     ///
52     ///     fn foo<'a, 'b, 'c>() -> impl Trait<'c> + 'a + 'b
53     ///
54     /// but false for:
55     ///
56     ///     fn foo<'c>() -> impl Trait<'c>
57     ///
58     /// unless `Trait` was declared like:
59     ///
60     ///     trait Trait<'c>: 'c
61     ///
62     /// in which case it would be true.
63     ///
64     /// This is used during regionck to decide whether we need to
65     /// impose any additional constraints to ensure that region
66     /// variables in `concrete_ty` wind up being constrained to
67     /// something from `substs` (or, at minimum, things that outlive
68     /// the fn body). (Ultimately, writeback is responsible for this
69     /// check.)
70     pub has_required_region_bounds: bool,
71
72     /// The origin of the existential type
73     pub origin: hir::ExistTyOrigin,
74 }
75
76 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
77     /// Replaces all opaque types in `value` with fresh inference variables
78     /// and creates appropriate obligations. For example, given the input:
79     ///
80     ///     impl Iterator<Item = impl Debug>
81     ///
82     /// this method would create two type variables, `?0` and `?1`. It would
83     /// return the type `?0` but also the obligations:
84     ///
85     ///     ?0: Iterator<Item = ?1>
86     ///     ?1: Debug
87     ///
88     /// Moreover, it returns a `OpaqueTypeMap` that would map `?0` to
89     /// info about the `impl Iterator<..>` type and `?1` to info about
90     /// the `impl Debug` type.
91     ///
92     /// # Parameters
93     ///
94     /// - `parent_def_id` -- the `DefId` of the function in which the opaque type
95     ///   is defined
96     /// - `body_id` -- the body-id with which the resulting obligations should
97     ///   be associated
98     /// - `param_env` -- the in-scope parameter environment to be used for
99     ///   obligations
100     /// - `value` -- the value within which we are instantiating opaque types
101     pub fn instantiate_opaque_types<T: TypeFoldable<'tcx>>(
102         &self,
103         parent_def_id: DefId,
104         body_id: hir::HirId,
105         param_env: ty::ParamEnv<'tcx>,
106         value: &T,
107     ) -> InferOk<'tcx, (T, OpaqueTypeMap<'tcx>)> {
108         debug!(
109             "instantiate_opaque_types(value={:?}, parent_def_id={:?}, body_id={:?}, \
110              param_env={:?})",
111             value, parent_def_id, body_id, param_env,
112         );
113         let mut instantiator = Instantiator {
114             infcx: self,
115             parent_def_id,
116             body_id,
117             param_env,
118             opaque_types: Default::default(),
119             obligations: vec![],
120         };
121         let value = instantiator.instantiate_opaque_types_in_map(value);
122         InferOk { value: (value, instantiator.opaque_types), obligations: instantiator.obligations }
123     }
124
125     /// Given the map `opaque_types` containing the existential `impl
126     /// Trait` types whose underlying, hidden types are being
127     /// inferred, this method adds constraints to the regions
128     /// appearing in those underlying hidden types to ensure that they
129     /// at least do not refer to random scopes within the current
130     /// function. These constraints are not (quite) sufficient to
131     /// guarantee that the regions are actually legal values; that
132     /// final condition is imposed after region inference is done.
133     ///
134     /// # The Problem
135     ///
136     /// Let's work through an example to explain how it works. Assume
137     /// the current function is as follows:
138     ///
139     /// ```text
140     /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
141     /// ```
142     ///
143     /// Here, we have two `impl Trait` types whose values are being
144     /// inferred (the `impl Bar<'a>` and the `impl
145     /// Bar<'b>`). Conceptually, this is sugar for a setup where we
146     /// define underlying abstract types (`Foo1`, `Foo2`) and then, in
147     /// the return type of `foo`, we *reference* those definitions:
148     ///
149     /// ```text
150     /// abstract type Foo1<'x>: Bar<'x>;
151     /// abstract type Foo2<'x>: Bar<'x>;
152     /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
153     ///                    //  ^^^^ ^^
154     ///                    //  |    |
155     ///                    //  |    substs
156     ///                    //  def_id
157     /// ```
158     ///
159     /// As indicating in the comments above, each of those references
160     /// is (in the compiler) basically a substitution (`substs`)
161     /// applied to the type of a suitable `def_id` (which identifies
162     /// `Foo1` or `Foo2`).
163     ///
164     /// Now, at this point in compilation, what we have done is to
165     /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
166     /// fresh inference variables C1 and C2. We wish to use the values
167     /// of these variables to infer the underlying types of `Foo1` and
168     /// `Foo2`. That is, this gives rise to higher-order (pattern) unification
169     /// constraints like:
170     ///
171     /// ```text
172     /// for<'a> (Foo1<'a> = C1)
173     /// for<'b> (Foo1<'b> = C2)
174     /// ```
175     ///
176     /// For these equation to be satisfiable, the types `C1` and `C2`
177     /// can only refer to a limited set of regions. For example, `C1`
178     /// can only refer to `'static` and `'a`, and `C2` can only refer
179     /// to `'static` and `'b`. The job of this function is to impose that
180     /// constraint.
181     ///
182     /// Up to this point, C1 and C2 are basically just random type
183     /// inference variables, and hence they may contain arbitrary
184     /// regions. In fact, it is fairly likely that they do! Consider
185     /// this possible definition of `foo`:
186     ///
187     /// ```text
188     /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
189     ///         (&*x, &*y)
190     ///     }
191     /// ```
192     ///
193     /// Here, the values for the concrete types of the two impl
194     /// traits will include inference variables:
195     ///
196     /// ```text
197     /// &'0 i32
198     /// &'1 i32
199     /// ```
200     ///
201     /// Ordinarily, the subtyping rules would ensure that these are
202     /// sufficiently large. But since `impl Bar<'a>` isn't a specific
203     /// type per se, we don't get such constraints by default. This
204     /// is where this function comes into play. It adds extra
205     /// constraints to ensure that all the regions which appear in the
206     /// inferred type are regions that could validly appear.
207     ///
208     /// This is actually a bit of a tricky constraint in general. We
209     /// want to say that each variable (e.g., `'0`) can only take on
210     /// values that were supplied as arguments to the abstract type
211     /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
212     /// scope. We don't have a constraint quite of this kind in the current
213     /// region checker.
214     ///
215     /// # The Solution
216     ///
217     /// We generally prefer to make us our `<=` constraints, since
218     /// they integrate best into the region solve. To do that, we find
219     /// the "minimum" of all the arguments that appear in the substs:
220     /// that is, some region which is less than all the others. In the
221     /// case of `Foo1<'a>`, that would be `'a` (it's the only choice,
222     /// after all). Then we apply that as a least bound to the
223     /// variables (e.g., `'a <= '0`).
224     ///
225     /// In some cases, there is no minimum. Consider this example:
226     ///
227     /// ```text
228     /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
229     /// ```
230     ///
231     /// Here we would report a more complex "in constraint", like `'r
232     /// in ['a, 'b, 'static]` (where `'r` is some regon appearing in
233     /// the hidden type).
234     ///
235     /// # Constrain regions, not the hidden concrete type
236     ///
237     /// Note that generating constraints on each region `Rc` is *not*
238     /// the same as generating an outlives constraint on `Tc` iself.
239     /// For example, if we had a function like this:
240     ///
241     /// ```rust
242     /// fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> {
243     ///   (x, y)
244     /// }
245     ///
246     /// // Equivalent to:
247     /// existential type FooReturn<'a, T>: Foo<'a>;
248     /// fn foo<'a, T>(..) -> FooReturn<'a, T> { .. }
249     /// ```
250     ///
251     /// then the hidden type `Tc` would be `(&'0 u32, T)` (where `'0`
252     /// is an inference variable). If we generated a constraint that
253     /// `Tc: 'a`, then this would incorrectly require that `T: 'a` --
254     /// but this is not necessary, because the existential type we
255     /// create will be allowed to reference `T`. So instead we just
256     /// generate a constraint that `'0: 'a`.
257     ///
258     /// # The `free_region_relations` parameter
259     ///
260     /// The `free_region_relations` argument is used to find the
261     /// "minimum" of the regions supplied to a given abstract type.
262     /// It must be a relation that can answer whether `'a <= 'b`,
263     /// where `'a` and `'b` are regions that appear in the "substs"
264     /// for the abstract type references (the `<'a>` in `Foo1<'a>`).
265     ///
266     /// Note that we do not impose the constraints based on the
267     /// generic regions from the `Foo1` definition (e.g., `'x`). This
268     /// is because the constraints we are imposing here is basically
269     /// the concern of the one generating the constraining type C1,
270     /// which is the current function. It also means that we can
271     /// take "implied bounds" into account in some cases:
272     ///
273     /// ```text
274     /// trait SomeTrait<'a, 'b> { }
275     /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. }
276     /// ```
277     ///
278     /// Here, the fact that `'b: 'a` is known only because of the
279     /// implied bounds from the `&'a &'b u32` parameter, and is not
280     /// "inherent" to the abstract type definition.
281     ///
282     /// # Parameters
283     ///
284     /// - `opaque_types` -- the map produced by `instantiate_opaque_types`
285     /// - `free_region_relations` -- something that can be used to relate
286     ///   the free regions (`'a`) that appear in the impl trait.
287     pub fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(
288         &self,
289         opaque_types: &OpaqueTypeMap<'tcx>,
290         free_region_relations: &FRR,
291     ) {
292         debug!("constrain_opaque_types()");
293
294         for (&def_id, opaque_defn) in opaque_types {
295             self.constrain_opaque_type(def_id, opaque_defn, free_region_relations);
296         }
297     }
298
299     /// See `constrain_opaque_types` for docs
300     pub fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>(
301         &self,
302         def_id: DefId,
303         opaque_defn: &OpaqueTypeDecl<'tcx>,
304         free_region_relations: &FRR,
305     ) {
306         debug!("constrain_opaque_type()");
307         debug!("constrain_opaque_type: def_id={:?}", def_id);
308         debug!("constrain_opaque_type: opaque_defn={:#?}", opaque_defn);
309
310         let tcx = self.tcx;
311
312         let concrete_ty = self.resolve_vars_if_possible(&opaque_defn.concrete_ty);
313
314         debug!("constrain_opaque_type: concrete_ty={:?}", concrete_ty);
315
316         let abstract_type_generics = tcx.generics_of(def_id);
317
318         let span = tcx.def_span(def_id);
319
320         // If there are required region bounds, we can use them.
321         if opaque_defn.has_required_region_bounds {
322             let predicates_of = tcx.predicates_of(def_id);
323             debug!("constrain_opaque_type: predicates: {:#?}", predicates_of,);
324             let bounds = predicates_of.instantiate(tcx, opaque_defn.substs);
325             debug!("constrain_opaque_type: bounds={:#?}", bounds);
326             let opaque_type = tcx.mk_opaque(def_id, opaque_defn.substs);
327
328             let required_region_bounds = tcx.required_region_bounds(opaque_type, bounds.predicates);
329             debug_assert!(!required_region_bounds.is_empty());
330
331             for required_region in required_region_bounds {
332                 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
333                     tcx: self.tcx,
334                     op: |r| self.sub_regions(infer::CallReturn(span), required_region, r),
335                 });
336             }
337             return;
338         }
339
340         // There were no `required_region_bounds`,
341         // so we have to search for a `least_region`.
342         // Go through all the regions used as arguments to the
343         // abstract type. These are the parameters to the abstract
344         // type; so in our example above, `substs` would contain
345         // `['a]` for the first impl trait and `'b` for the
346         // second.
347         let mut least_region = None;
348         for param in &abstract_type_generics.params {
349             match param.kind {
350                 GenericParamDefKind::Lifetime => {}
351                 _ => continue,
352             }
353
354             // Get the value supplied for this region from the substs.
355             let subst_arg = opaque_defn.substs.region_at(param.index as usize);
356
357             // Compute the least upper bound of it with the other regions.
358             debug!("constrain_opaque_types: least_region={:?}", least_region);
359             debug!("constrain_opaque_types: subst_arg={:?}", subst_arg);
360             match least_region {
361                 None => least_region = Some(subst_arg),
362                 Some(lr) => {
363                     if free_region_relations.sub_free_regions(lr, subst_arg) {
364                         // keep the current least region
365                     } else if free_region_relations.sub_free_regions(subst_arg, lr) {
366                         // switch to `subst_arg`
367                         least_region = Some(subst_arg);
368                     } else {
369                         // There are two regions (`lr` and
370                         // `subst_arg`) which are not relatable. We
371                         // can't find a best choice. Therefore,
372                         // instead of creating a single bound like
373                         // `'r: 'a` (which is our preferred choice),
374                         // we will create a "in bound" like `'r in
375                         // ['a, 'b, 'c]`, where `'a..'c` are the
376                         // regions that appear in the impl trait.
377                         return self.generate_in_constraint(
378                             span,
379                             concrete_ty,
380                             abstract_type_generics,
381                             opaque_defn,
382                         );
383                     }
384                 }
385             }
386         }
387
388         let least_region = least_region.unwrap_or(tcx.lifetimes.re_static);
389         debug!("constrain_opaque_types: least_region={:?}", least_region);
390
391         concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
392             tcx: self.tcx,
393             op: |r| self.sub_regions(infer::CallReturn(span), least_region, r),
394         });
395     }
396
397     /// As a fallback, we sometimes generate an "in constraint". For
398     /// case like `impl Foo<'a, 'b>`, where `'a` and `'b` cannot be
399     /// related, we would generate a constraint `'r in ['a, 'b,
400     /// 'static]` for each region `'r` that appears in the hidden type
401     /// (i.e., it must be equal to `'a`, `'b`, or `'static`).
402     fn generate_in_constraint(
403         &self,
404         span: Span,
405         concrete_ty: Ty<'tcx>,
406         abstract_type_generics: &ty::Generics,
407         opaque_defn: &OpaqueTypeDecl<'tcx>,
408     ) {
409         let in_regions: Rc<Vec<ty::Region<'tcx>>> = Rc::new(
410             abstract_type_generics
411                 .params
412                 .iter()
413                 .filter(|param| match param.kind {
414                     GenericParamDefKind::Lifetime => true,
415                     GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => false,
416                 })
417                 .map(|param| opaque_defn.substs.region_at(param.index as usize))
418                 .chain(std::iter::once(self.tcx.lifetimes.re_static))
419                 .collect(),
420         );
421
422         concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
423             tcx: self.tcx,
424             op: |r| self.pick_constraint(infer::CallReturn(span), r, &in_regions),
425         });
426     }
427
428     /// Given the fully resolved, instantiated type for an opaque
429     /// type, i.e., the value of an inference variable like C1 or C2
430     /// (*), computes the "definition type" for an abstract type
431     /// definition -- that is, the inferred value of `Foo1<'x>` or
432     /// `Foo2<'x>` that we would conceptually use in its definition:
433     ///
434     ///     abstract type Foo1<'x>: Bar<'x> = AAA; <-- this type AAA
435     ///     abstract type Foo2<'x>: Bar<'x> = BBB; <-- or this type BBB
436     ///     fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
437     ///
438     /// Note that these values are defined in terms of a distinct set of
439     /// generic parameters (`'x` instead of `'a`) from C1 or C2. The main
440     /// purpose of this function is to do that translation.
441     ///
442     /// (*) C1 and C2 were introduced in the comments on
443     /// `constrain_opaque_types`. Read that comment for more context.
444     ///
445     /// # Parameters
446     ///
447     /// - `def_id`, the `impl Trait` type
448
449     /// - `opaque_defn`, the opaque definition created in `instantiate_opaque_types`
450     /// - `instantiated_ty`, the inferred type C1 -- fully resolved, lifted version of
451     ///   `opaque_defn.concrete_ty`
452     pub fn infer_opaque_definition_from_instantiation(
453         &self,
454         def_id: DefId,
455         opaque_defn: &OpaqueTypeDecl<'tcx>,
456         instantiated_ty: Ty<'tcx>,
457     ) -> Ty<'tcx> {
458         debug!(
459             "infer_opaque_definition_from_instantiation(def_id={:?}, instantiated_ty={:?})",
460             def_id, instantiated_ty
461         );
462
463         let gcx = self.tcx.global_tcx();
464
465         // Use substs to build up a reverse map from regions to their
466         // identity mappings. This is necessary because of `impl
467         // Trait` lifetimes are computed by replacing existing
468         // lifetimes with 'static and remapping only those used in the
469         // `impl Trait` return type, resulting in the parameters
470         // shifting.
471         let id_substs = InternalSubsts::identity_for_item(gcx, def_id);
472         let map: FxHashMap<Kind<'tcx>, Kind<'tcx>> = opaque_defn
473             .substs
474             .iter()
475             .enumerate()
476             .map(|(index, subst)| (*subst, id_substs[index]))
477             .collect();
478
479         // Convert the type from the function into a type valid outside
480         // the function, by replacing invalid regions with 'static,
481         // after producing an error for each of them.
482         let definition_ty = instantiated_ty.fold_with(&mut ReverseMapper::new(
483             self.tcx,
484             self.is_tainted_by_errors(),
485             def_id,
486             map,
487             instantiated_ty,
488         ));
489         debug!("infer_opaque_definition_from_instantiation: definition_ty={:?}", definition_ty);
490
491         definition_ty
492     }
493 }
494
495 // Visitor that requires that (almost) all regions in the type visited outlive
496 // `least_region`. We cannot use `push_outlives_components` because regions in
497 // closure signatures are not included in their outlives components. We need to
498 // ensure all regions outlive the given bound so that we don't end up with,
499 // say, `ReScope` appearing in a return type and causing ICEs when other
500 // functions end up with region constraints involving regions from other
501 // functions.
502 //
503 // We also cannot use `for_each_free_region` because for closures it includes
504 // the regions parameters from the enclosing item.
505 //
506 // We ignore any type parameters because impl trait values are assumed to
507 // capture all the in-scope type parameters.
508 struct ConstrainOpaqueTypeRegionVisitor<'tcx, OP>
509 where
510     OP: FnMut(ty::Region<'tcx>),
511 {
512     tcx: TyCtxt<'tcx>,
513     op: OP,
514 }
515
516 impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<'tcx, OP>
517 where
518     OP: FnMut(ty::Region<'tcx>),
519 {
520     fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool {
521         t.skip_binder().visit_with(self);
522         false // keep visiting
523     }
524
525     fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
526         match *r {
527             // ignore bound regions, keep visiting
528             ty::ReLateBound(_, _) => false,
529             _ => {
530                 (self.op)(r);
531                 false
532             }
533         }
534     }
535
536     fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
537         // We're only interested in types involving regions
538         if !ty.flags.intersects(ty::TypeFlags::HAS_FREE_REGIONS) {
539             return false; // keep visiting
540         }
541
542         match ty.sty {
543             ty::Closure(def_id, ref substs) => {
544                 // Skip lifetime parameters of the enclosing item(s)
545
546                 for upvar_ty in substs.upvar_tys(def_id, self.tcx) {
547                     upvar_ty.visit_with(self);
548                 }
549
550                 substs.closure_sig_ty(def_id, self.tcx).visit_with(self);
551             }
552
553             ty::Generator(def_id, ref substs, _) => {
554                 // Skip lifetime parameters of the enclosing item(s)
555                 // Also skip the witness type, because that has no free regions.
556
557                 for upvar_ty in substs.upvar_tys(def_id, self.tcx) {
558                     upvar_ty.visit_with(self);
559                 }
560
561                 substs.return_ty(def_id, self.tcx).visit_with(self);
562                 substs.yield_ty(def_id, self.tcx).visit_with(self);
563             }
564             _ => {
565                 ty.super_visit_with(self);
566             }
567         }
568
569         false
570     }
571 }
572
573 struct ReverseMapper<'tcx> {
574     tcx: TyCtxt<'tcx>,
575
576     /// If errors have already been reported in this fn, we suppress
577     /// our own errors because they are sometimes derivative.
578     tainted_by_errors: bool,
579
580     opaque_type_def_id: DefId,
581     map: FxHashMap<Kind<'tcx>, Kind<'tcx>>,
582     map_missing_regions_to_empty: bool,
583
584     /// initially `Some`, set to `None` once error has been reported
585     hidden_ty: Option<Ty<'tcx>>,
586 }
587
588 impl ReverseMapper<'tcx> {
589     fn new(
590         tcx: TyCtxt<'tcx>,
591         tainted_by_errors: bool,
592         opaque_type_def_id: DefId,
593         map: FxHashMap<Kind<'tcx>, Kind<'tcx>>,
594         hidden_ty: Ty<'tcx>,
595     ) -> Self {
596         Self {
597             tcx,
598             tainted_by_errors,
599             opaque_type_def_id,
600             map,
601             map_missing_regions_to_empty: false,
602             hidden_ty: Some(hidden_ty),
603         }
604     }
605
606     fn fold_kind_mapping_missing_regions_to_empty(&mut self, kind: Kind<'tcx>) -> Kind<'tcx> {
607         assert!(!self.map_missing_regions_to_empty);
608         self.map_missing_regions_to_empty = true;
609         let kind = kind.fold_with(self);
610         self.map_missing_regions_to_empty = false;
611         kind
612     }
613
614     fn fold_kind_normally(&mut self, kind: Kind<'tcx>) -> Kind<'tcx> {
615         assert!(!self.map_missing_regions_to_empty);
616         kind.fold_with(self)
617     }
618 }
619
620 impl TypeFolder<'tcx> for ReverseMapper<'tcx> {
621     fn tcx(&self) -> TyCtxt<'tcx> {
622         self.tcx
623     }
624
625     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
626         match r {
627             // ignore bound regions that appear in the type (e.g., this
628             // would ignore `'r` in a type like `for<'r> fn(&'r u32)`.
629             ty::ReLateBound(..) |
630
631             // ignore `'static`, as that can appear anywhere
632             ty::ReStatic => return r,
633
634             _ => { }
635         }
636
637         match self.map.get(&r.into()).map(|k| k.unpack()) {
638             Some(UnpackedKind::Lifetime(r1)) => r1,
639             Some(u) => panic!("region mapped to unexpected kind: {:?}", u),
640             None => {
641                 if !self.map_missing_regions_to_empty && !self.tainted_by_errors {
642                     if let Some(hidden_ty) = self.hidden_ty.take() {
643                         let span = self.tcx.def_span(self.opaque_type_def_id);
644                         let mut err = struct_span_err!(
645                             self.tcx.sess,
646                             span,
647                             E0700,
648                             "hidden type for `impl Trait` captures lifetime that \
649                              does not appear in bounds",
650                         );
651
652                         // Explain the region we are capturing.
653                         match r {
654                             ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic | ty::ReEmpty => {
655                                 // Assuming regionck succeeded (*), we
656                                 // ought to always be capturing *some* region
657                                 // from the fn header, and hence it ought to
658                                 // be free. So under normal circumstances, we will
659                                 // go down this path which gives a decent human readable
660                                 // explanation.
661                                 //
662                                 // (*) if not, the `tainted_by_errors`
663                                 // flag would be set to true in any
664                                 // case, so we wouldn't be here at
665                                 // all.
666                                 self.tcx.note_and_explain_free_region(
667                                     &mut err,
668                                     &format!("hidden type `{}` captures ", hidden_ty),
669                                     r,
670                                     "",
671                                 );
672                             }
673                             _ => {
674                                 // This case should not happen: it indicates that regionck
675                                 // failed to enforce an "in constraint".
676                                 err.note(&format!("hidden type `{}` captures `{:?}`", hidden_ty, r));
677                                 err.note(&format!("this is likely a bug in the compiler, please file an issue on github"));
678                             }
679                         }
680
681                         err.emit();
682                     }
683                 }
684                 self.tcx.lifetimes.re_empty
685             }
686         }
687     }
688
689     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
690         match ty.sty {
691             ty::Closure(def_id, substs) => {
692                 // I am a horrible monster and I pray for death. When
693                 // we encounter a closure here, it is always a closure
694                 // from within the function that we are currently
695                 // type-checking -- one that is now being encapsulated
696                 // in an existential abstract type. Ideally, we would
697                 // go through the types/lifetimes that it references
698                 // and treat them just like we would any other type,
699                 // which means we would error out if we find any
700                 // reference to a type/region that is not in the
701                 // "reverse map".
702                 //
703                 // **However,** in the case of closures, there is a
704                 // somewhat subtle (read: hacky) consideration. The
705                 // problem is that our closure types currently include
706                 // all the lifetime parameters declared on the
707                 // enclosing function, even if they are unused by the
708                 // closure itself. We can't readily filter them out,
709                 // so here we replace those values with `'empty`. This
710                 // can't really make a difference to the rest of the
711                 // compiler; those regions are ignored for the
712                 // outlives relation, and hence don't affect trait
713                 // selection or auto traits, and they are erased
714                 // during codegen.
715
716                 let generics = self.tcx.generics_of(def_id);
717                 let substs =
718                     self.tcx.mk_substs(substs.substs.iter().enumerate().map(|(index, &kind)| {
719                         if index < generics.parent_count {
720                             // Accommodate missing regions in the parent kinds...
721                             self.fold_kind_mapping_missing_regions_to_empty(kind)
722                         } else {
723                             // ...but not elsewhere.
724                             self.fold_kind_normally(kind)
725                         }
726                     }));
727
728                 self.tcx.mk_closure(def_id, ty::ClosureSubsts { substs })
729             }
730
731             ty::Generator(def_id, substs, movability) => {
732                 let generics = self.tcx.generics_of(def_id);
733                 let substs =
734                     self.tcx.mk_substs(substs.substs.iter().enumerate().map(|(index, &kind)| {
735                         if index < generics.parent_count {
736                             // Accommodate missing regions in the parent kinds...
737                             self.fold_kind_mapping_missing_regions_to_empty(kind)
738                         } else {
739                             // ...but not elsewhere.
740                             self.fold_kind_normally(kind)
741                         }
742                     }));
743
744                 self.tcx.mk_generator(def_id, ty::GeneratorSubsts { substs }, movability)
745             }
746
747             _ => ty.super_fold_with(self),
748         }
749     }
750 }
751
752 struct Instantiator<'a, 'tcx> {
753     infcx: &'a InferCtxt<'a, 'tcx>,
754     parent_def_id: DefId,
755     body_id: hir::HirId,
756     param_env: ty::ParamEnv<'tcx>,
757     opaque_types: OpaqueTypeMap<'tcx>,
758     obligations: Vec<PredicateObligation<'tcx>>,
759 }
760
761 impl<'a, 'tcx> Instantiator<'a, 'tcx> {
762     fn instantiate_opaque_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
763         debug!("instantiate_opaque_types_in_map(value={:?})", value);
764         let tcx = self.infcx.tcx;
765         value.fold_with(&mut BottomUpFolder {
766             tcx,
767             ty_op: |ty| {
768                 if let ty::Opaque(def_id, substs) = ty.sty {
769                     // Check that this is `impl Trait` type is
770                     // declared by `parent_def_id` -- i.e., one whose
771                     // value we are inferring.  At present, this is
772                     // always true during the first phase of
773                     // type-check, but not always true later on during
774                     // NLL. Once we support named abstract types more fully,
775                     // this same scenario will be able to arise during all phases.
776                     //
777                     // Here is an example using `abstract type` that indicates
778                     // the distinction we are checking for:
779                     //
780                     // ```rust
781                     // mod a {
782                     //   pub abstract type Foo: Iterator;
783                     //   pub fn make_foo() -> Foo { .. }
784                     // }
785                     //
786                     // mod b {
787                     //   fn foo() -> a::Foo { a::make_foo() }
788                     // }
789                     // ```
790                     //
791                     // Here, the return type of `foo` references a
792                     // `Opaque` indeed, but not one whose value is
793                     // presently being inferred. You can get into a
794                     // similar situation with closure return types
795                     // today:
796                     //
797                     // ```rust
798                     // fn foo() -> impl Iterator { .. }
799                     // fn bar() {
800                     //     let x = || foo(); // returns the Opaque assoc with `foo`
801                     // }
802                     // ```
803                     if let Some(opaque_hir_id) = tcx.hir().as_local_hir_id(def_id) {
804                         let parent_def_id = self.parent_def_id;
805                         let def_scope_default = || {
806                             let opaque_parent_hir_id = tcx.hir().get_parent_item(opaque_hir_id);
807                             parent_def_id
808                                 == tcx.hir().local_def_id_from_hir_id(opaque_parent_hir_id)
809                         };
810                         let (in_definition_scope, origin) = match tcx.hir().find(opaque_hir_id) {
811                             Some(Node::Item(item)) => match item.node {
812                                 // Anonymous `impl Trait`
813                                 hir::ItemKind::Existential(hir::ExistTy {
814                                     impl_trait_fn: Some(parent),
815                                     origin,
816                                     ..
817                                 }) => (parent == self.parent_def_id, origin),
818                                 // Named `existential type`
819                                 hir::ItemKind::Existential(hir::ExistTy {
820                                     impl_trait_fn: None,
821                                     origin,
822                                     ..
823                                 }) => (
824                                     may_define_existential_type(
825                                         tcx,
826                                         self.parent_def_id,
827                                         opaque_hir_id,
828                                     ),
829                                     origin,
830                                 ),
831                                 _ => (def_scope_default(), hir::ExistTyOrigin::ExistentialType),
832                             },
833                             Some(Node::ImplItem(item)) => match item.node {
834                                 hir::ImplItemKind::Existential(_) => (
835                                     may_define_existential_type(
836                                         tcx,
837                                         self.parent_def_id,
838                                         opaque_hir_id,
839                                     ),
840                                     hir::ExistTyOrigin::ExistentialType,
841                                 ),
842                                 _ => (def_scope_default(), hir::ExistTyOrigin::ExistentialType),
843                             },
844                             _ => bug!(
845                                 "expected (impl) item, found {}",
846                                 tcx.hir().node_to_string(opaque_hir_id),
847                             ),
848                         };
849                         if in_definition_scope {
850                             return self.fold_opaque_ty(ty, def_id, substs, origin);
851                         }
852
853                         debug!(
854                             "instantiate_opaque_types_in_map: \
855                              encountered opaque outside its definition scope \
856                              def_id={:?}",
857                             def_id,
858                         );
859                     }
860                 }
861
862                 ty
863             },
864             lt_op: |lt| lt,
865             ct_op: |ct| ct,
866         })
867     }
868
869     fn fold_opaque_ty(
870         &mut self,
871         ty: Ty<'tcx>,
872         def_id: DefId,
873         substs: SubstsRef<'tcx>,
874         origin: hir::ExistTyOrigin,
875     ) -> Ty<'tcx> {
876         let infcx = self.infcx;
877         let tcx = infcx.tcx;
878
879         debug!("instantiate_opaque_types: Opaque(def_id={:?}, substs={:?})", def_id, substs);
880
881         // Use the same type variable if the exact same opaque type appears more
882         // than once in the return type (e.g., if it's passed to a type alias).
883         if let Some(opaque_defn) = self.opaque_types.get(&def_id) {
884             return opaque_defn.concrete_ty;
885         }
886         let span = tcx.def_span(def_id);
887         let ty_var = infcx
888             .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
889
890         let predicates_of = tcx.predicates_of(def_id);
891         debug!("instantiate_opaque_types: predicates={:#?}", predicates_of,);
892         let bounds = predicates_of.instantiate(tcx, substs);
893         debug!("instantiate_opaque_types: bounds={:?}", bounds);
894
895         let required_region_bounds = tcx.required_region_bounds(ty, bounds.predicates.clone());
896         debug!("instantiate_opaque_types: required_region_bounds={:?}", required_region_bounds);
897
898         // Make sure that we are in fact defining the *entire* type
899         // (e.g., `existential type Foo<T: Bound>: Bar;` needs to be
900         // defined by a function like `fn foo<T: Bound>() -> Foo<T>`).
901         debug!("instantiate_opaque_types: param_env={:#?}", self.param_env,);
902         debug!("instantiate_opaque_types: generics={:#?}", tcx.generics_of(def_id),);
903
904         self.opaque_types.insert(
905             def_id,
906             OpaqueTypeDecl {
907                 substs,
908                 concrete_ty: ty_var,
909                 has_required_region_bounds: !required_region_bounds.is_empty(),
910                 origin,
911             },
912         );
913         debug!("instantiate_opaque_types: ty_var={:?}", ty_var);
914
915         self.obligations.reserve(bounds.predicates.len());
916         for predicate in bounds.predicates {
917             // Change the predicate to refer to the type variable,
918             // which will be the concrete type instead of the opaque type.
919             // This also instantiates nested instances of `impl Trait`.
920             let predicate = self.instantiate_opaque_types_in_map(&predicate);
921
922             let cause = traits::ObligationCause::new(span, self.body_id, traits::SizedReturnType);
923
924             // Require that the predicate holds for the concrete type.
925             debug!("instantiate_opaque_types: predicate={:?}", predicate);
926             self.obligations.push(traits::Obligation::new(cause, self.param_env, predicate));
927         }
928
929         ty_var
930     }
931 }
932
933 /// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`.
934 ///
935 /// Example:
936 /// ```rust
937 /// pub mod foo {
938 ///     pub mod bar {
939 ///         pub existential type Baz;
940 ///
941 ///         fn f1() -> Baz { .. }
942 ///     }
943 ///
944 ///     fn f2() -> bar::Baz { .. }
945 /// }
946 /// ```
947 ///
948 /// Here, `def_id` is the `DefId` of the defining use of the existential type (e.g., `f1` or `f2`),
949 /// and `opaque_hir_id` is the `HirId` of the definition of the existential type `Baz`.
950 /// For the above example, this function returns `true` for `f1` and `false` for `f2`.
951 pub fn may_define_existential_type(
952     tcx: TyCtxt<'_>,
953     def_id: DefId,
954     opaque_hir_id: hir::HirId,
955 ) -> bool {
956     let mut hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
957     trace!(
958         "may_define_existential_type(def={:?}, opaque_node={:?})",
959         tcx.hir().get(hir_id),
960         tcx.hir().get(opaque_hir_id)
961     );
962
963     // Named existential types can be defined by any siblings or children of siblings.
964     let scope = tcx.hir().get_defining_scope(opaque_hir_id).expect("could not get defining scope");
965     // We walk up the node tree until we hit the root or the scope of the opaque type.
966     while hir_id != scope && hir_id != hir::CRATE_HIR_ID {
967         hir_id = tcx.hir().get_parent_item(hir_id);
968     }
969     // Syntactically, we are allowed to define the concrete type if:
970     hir_id == scope
971 }