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