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