]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/opaque_types.rs
Store the `DefId` of the currently typechecked item in `InferCtxt`
[rust.git] / compiler / rustc_trait_selection / src / opaque_types.rs
1 use crate::infer::InferCtxtExt as _;
2 use crate::traits::{self, ObligationCause, PredicateObligation};
3 use rustc_data_structures::fx::FxHashMap;
4 use rustc_data_structures::sync::Lrc;
5 use rustc_hir as hir;
6 use rustc_hir::def_id::{DefId, LocalDefId};
7 use rustc_infer::infer::error_reporting::unexpected_hidden_region_diagnostic;
8 use rustc_infer::infer::free_regions::FreeRegionRelations;
9 use rustc_infer::infer::opaque_types::OpaqueTypeDecl;
10 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
11 use rustc_infer::infer::{self, InferCtxt, InferOk};
12 use rustc_middle::ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder, TypeVisitor};
13 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, Subst};
14 use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt};
15 use rustc_span::Span;
16
17 use std::ops::ControlFlow;
18
19 /// Whether member constraints should be generated for all opaque types
20 #[derive(Debug)]
21 pub enum GenerateMemberConstraints {
22     /// The default, used by typeck
23     WhenRequired,
24     /// The borrow checker needs member constraints in any case where we don't
25     /// have a `'static` bound. This is because the borrow checker has more
26     /// flexibility in the values of regions. For example, given `f<'a, 'b>`
27     /// the borrow checker can have an inference variable outlive `'a` and `'b`,
28     /// but not be equal to `'static`.
29     IfNoStaticBound,
30 }
31
32 pub trait InferCtxtExt<'tcx> {
33     fn instantiate_opaque_types<T: TypeFoldable<'tcx>>(
34         &self,
35         body_id: hir::HirId,
36         param_env: ty::ParamEnv<'tcx>,
37         value: T,
38         value_span: Span,
39     ) -> InferOk<'tcx, T>;
40
41     fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(&self, free_region_relations: &FRR);
42
43     fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>(
44         &self,
45         opaque_type_key: OpaqueTypeKey<'tcx>,
46         opaque_defn: &OpaqueTypeDecl<'tcx>,
47         mode: GenerateMemberConstraints,
48         free_region_relations: &FRR,
49     );
50
51     /*private*/
52     fn generate_member_constraint(
53         &self,
54         concrete_ty: Ty<'tcx>,
55         opaque_defn: &OpaqueTypeDecl<'tcx>,
56         opaque_type_key: OpaqueTypeKey<'tcx>,
57         first_own_region_index: usize,
58     );
59
60     fn infer_opaque_definition_from_instantiation(
61         &self,
62         opaque_type_key: OpaqueTypeKey<'tcx>,
63         instantiated_ty: Ty<'tcx>,
64         span: Span,
65     ) -> Ty<'tcx>;
66 }
67
68 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
69     /// Replaces all opaque types in `value` with fresh inference variables
70     /// and creates appropriate obligations. For example, given the input:
71     ///
72     ///     impl Iterator<Item = impl Debug>
73     ///
74     /// this method would create two type variables, `?0` and `?1`. It would
75     /// return the type `?0` but also the obligations:
76     ///
77     ///     ?0: Iterator<Item = ?1>
78     ///     ?1: Debug
79     ///
80     /// Moreover, it returns a `OpaqueTypeMap` that would map `?0` to
81     /// info about the `impl Iterator<..>` type and `?1` to info about
82     /// the `impl Debug` type.
83     ///
84     /// # Parameters
85     ///
86     /// - `parent_def_id` -- the `DefId` of the function in which the opaque type
87     ///   is defined
88     /// - `body_id` -- the body-id with which the resulting obligations should
89     ///   be associated
90     /// - `param_env` -- the in-scope parameter environment to be used for
91     ///   obligations
92     /// - `value` -- the value within which we are instantiating opaque types
93     /// - `value_span` -- the span where the value came from, used in error reporting
94     fn instantiate_opaque_types<T: TypeFoldable<'tcx>>(
95         &self,
96         body_id: hir::HirId,
97         param_env: ty::ParamEnv<'tcx>,
98         value: T,
99         value_span: Span,
100     ) -> InferOk<'tcx, T> {
101         debug!(
102             "instantiate_opaque_types(value={:?}, body_id={:?}, \
103              param_env={:?}, value_span={:?})",
104             value, body_id, param_env, value_span,
105         );
106         let mut instantiator =
107             Instantiator { infcx: self, body_id, param_env, value_span, obligations: vec![] };
108         let value = instantiator.instantiate_opaque_types_in_map(value);
109         InferOk { value, obligations: instantiator.obligations }
110     }
111
112     /// Given the map `opaque_types` containing the opaque
113     /// `impl Trait` types whose underlying, hidden types are being
114     /// inferred, this method adds constraints to the regions
115     /// appearing in those underlying hidden types to ensure that they
116     /// at least do not refer to random scopes within the current
117     /// function. These constraints are not (quite) sufficient to
118     /// guarantee that the regions are actually legal values; that
119     /// final condition is imposed after region inference is done.
120     ///
121     /// # The Problem
122     ///
123     /// Let's work through an example to explain how it works. Assume
124     /// the current function is as follows:
125     ///
126     /// ```text
127     /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
128     /// ```
129     ///
130     /// Here, we have two `impl Trait` types whose values are being
131     /// inferred (the `impl Bar<'a>` and the `impl
132     /// Bar<'b>`). Conceptually, this is sugar for a setup where we
133     /// define underlying opaque types (`Foo1`, `Foo2`) and then, in
134     /// the return type of `foo`, we *reference* those definitions:
135     ///
136     /// ```text
137     /// type Foo1<'x> = impl Bar<'x>;
138     /// type Foo2<'x> = impl Bar<'x>;
139     /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
140     ///                    //  ^^^^ ^^
141     ///                    //  |    |
142     ///                    //  |    substs
143     ///                    //  def_id
144     /// ```
145     ///
146     /// As indicating in the comments above, each of those references
147     /// is (in the compiler) basically a substitution (`substs`)
148     /// applied to the type of a suitable `def_id` (which identifies
149     /// `Foo1` or `Foo2`).
150     ///
151     /// Now, at this point in compilation, what we have done is to
152     /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
153     /// fresh inference variables C1 and C2. We wish to use the values
154     /// of these variables to infer the underlying types of `Foo1` and
155     /// `Foo2`. That is, this gives rise to higher-order (pattern) unification
156     /// constraints like:
157     ///
158     /// ```text
159     /// for<'a> (Foo1<'a> = C1)
160     /// for<'b> (Foo1<'b> = C2)
161     /// ```
162     ///
163     /// For these equation to be satisfiable, the types `C1` and `C2`
164     /// can only refer to a limited set of regions. For example, `C1`
165     /// can only refer to `'static` and `'a`, and `C2` can only refer
166     /// to `'static` and `'b`. The job of this function is to impose that
167     /// constraint.
168     ///
169     /// Up to this point, C1 and C2 are basically just random type
170     /// inference variables, and hence they may contain arbitrary
171     /// regions. In fact, it is fairly likely that they do! Consider
172     /// this possible definition of `foo`:
173     ///
174     /// ```text
175     /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
176     ///         (&*x, &*y)
177     ///     }
178     /// ```
179     ///
180     /// Here, the values for the concrete types of the two impl
181     /// traits will include inference variables:
182     ///
183     /// ```text
184     /// &'0 i32
185     /// &'1 i32
186     /// ```
187     ///
188     /// Ordinarily, the subtyping rules would ensure that these are
189     /// sufficiently large. But since `impl Bar<'a>` isn't a specific
190     /// type per se, we don't get such constraints by default. This
191     /// is where this function comes into play. It adds extra
192     /// constraints to ensure that all the regions which appear in the
193     /// inferred type are regions that could validly appear.
194     ///
195     /// This is actually a bit of a tricky constraint in general. We
196     /// want to say that each variable (e.g., `'0`) can only take on
197     /// values that were supplied as arguments to the opaque type
198     /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
199     /// scope. We don't have a constraint quite of this kind in the current
200     /// region checker.
201     ///
202     /// # The Solution
203     ///
204     /// We generally prefer to make `<=` constraints, since they
205     /// integrate best into the region solver. To do that, we find the
206     /// "minimum" of all the arguments that appear in the substs: that
207     /// is, some region which is less than all the others. In the case
208     /// of `Foo1<'a>`, that would be `'a` (it's the only choice, after
209     /// all). Then we apply that as a least bound to the variables
210     /// (e.g., `'a <= '0`).
211     ///
212     /// In some cases, there is no minimum. Consider this example:
213     ///
214     /// ```text
215     /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
216     /// ```
217     ///
218     /// Here we would report a more complex "in constraint", like `'r
219     /// in ['a, 'b, 'static]` (where `'r` is some region appearing in
220     /// the hidden type).
221     ///
222     /// # Constrain regions, not the hidden concrete type
223     ///
224     /// Note that generating constraints on each region `Rc` is *not*
225     /// the same as generating an outlives constraint on `Tc` iself.
226     /// For example, if we had a function like this:
227     ///
228     /// ```rust
229     /// fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> {
230     ///   (x, y)
231     /// }
232     ///
233     /// // Equivalent to:
234     /// type FooReturn<'a, T> = impl Foo<'a>;
235     /// fn foo<'a, T>(..) -> FooReturn<'a, T> { .. }
236     /// ```
237     ///
238     /// then the hidden type `Tc` would be `(&'0 u32, T)` (where `'0`
239     /// is an inference variable). If we generated a constraint that
240     /// `Tc: 'a`, then this would incorrectly require that `T: 'a` --
241     /// but this is not necessary, because the opaque type we
242     /// create will be allowed to reference `T`. So we only generate a
243     /// constraint that `'0: 'a`.
244     ///
245     /// # The `free_region_relations` parameter
246     ///
247     /// The `free_region_relations` argument is used to find the
248     /// "minimum" of the regions supplied to a given opaque type.
249     /// It must be a relation that can answer whether `'a <= 'b`,
250     /// where `'a` and `'b` are regions that appear in the "substs"
251     /// for the opaque type references (the `<'a>` in `Foo1<'a>`).
252     ///
253     /// Note that we do not impose the constraints based on the
254     /// generic regions from the `Foo1` definition (e.g., `'x`). This
255     /// is because the constraints we are imposing here is basically
256     /// the concern of the one generating the constraining type C1,
257     /// which is the current function. It also means that we can
258     /// take "implied bounds" into account in some cases:
259     ///
260     /// ```text
261     /// trait SomeTrait<'a, 'b> { }
262     /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. }
263     /// ```
264     ///
265     /// Here, the fact that `'b: 'a` is known only because of the
266     /// implied bounds from the `&'a &'b u32` parameter, and is not
267     /// "inherent" to the opaque type definition.
268     ///
269     /// # Parameters
270     ///
271     /// - `opaque_types` -- the map produced by `instantiate_opaque_types`
272     /// - `free_region_relations` -- something that can be used to relate
273     ///   the free regions (`'a`) that appear in the impl trait.
274     fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(&self, free_region_relations: &FRR) {
275         let opaque_types = self.inner.borrow().opaque_types.clone();
276         for (opaque_type_key, opaque_defn) in opaque_types {
277             self.constrain_opaque_type(
278                 opaque_type_key,
279                 &opaque_defn,
280                 GenerateMemberConstraints::WhenRequired,
281                 free_region_relations,
282             );
283         }
284     }
285
286     /// See `constrain_opaque_types` for documentation.
287     #[instrument(level = "debug", skip(self, free_region_relations))]
288     fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>(
289         &self,
290         opaque_type_key: OpaqueTypeKey<'tcx>,
291         opaque_defn: &OpaqueTypeDecl<'tcx>,
292         mode: GenerateMemberConstraints,
293         free_region_relations: &FRR,
294     ) {
295         let def_id = opaque_type_key.def_id;
296
297         let tcx = self.tcx;
298
299         let concrete_ty = self.resolve_vars_if_possible(opaque_defn.concrete_ty);
300
301         debug!(?concrete_ty);
302
303         let first_own_region = match opaque_defn.origin {
304             hir::OpaqueTyOrigin::FnReturn | hir::OpaqueTyOrigin::AsyncFn => {
305                 // We lower
306                 //
307                 // fn foo<'l0..'ln>() -> impl Trait<'l0..'lm>
308                 //
309                 // into
310                 //
311                 // type foo::<'p0..'pn>::Foo<'q0..'qm>
312                 // fn foo<l0..'ln>() -> foo::<'static..'static>::Foo<'l0..'lm>.
313                 //
314                 // For these types we only iterate over `'l0..lm` below.
315                 tcx.generics_of(def_id).parent_count
316             }
317             // These opaque type inherit all lifetime parameters from their
318             // parent, so we have to check them all.
319             hir::OpaqueTyOrigin::TyAlias => 0,
320         };
321
322         let span = tcx.def_span(def_id);
323
324         // Check if the `impl Trait` bounds include region bounds.
325         // For example, this would be true for:
326         //
327         //     fn foo<'a, 'b, 'c>() -> impl Trait<'c> + 'a + 'b
328         //
329         // but false for:
330         //
331         //     fn foo<'c>() -> impl Trait<'c>
332         //
333         // unless `Trait` was declared like:
334         //
335         //     trait Trait<'c>: 'c
336         //
337         // in which case it would be true.
338         //
339         // This is used during regionck to decide whether we need to
340         // impose any additional constraints to ensure that region
341         // variables in `concrete_ty` wind up being constrained to
342         // something from `substs` (or, at minimum, things that outlive
343         // the fn body). (Ultimately, writeback is responsible for this
344         // check.)
345         let bounds = tcx.explicit_item_bounds(def_id);
346         debug!("{:#?}", bounds);
347         let bounds: Vec<_> =
348             bounds.iter().map(|(bound, _)| bound.subst(tcx, opaque_type_key.substs)).collect();
349         debug!("{:#?}", bounds);
350         let opaque_type = tcx.mk_opaque(def_id, opaque_type_key.substs);
351
352         let required_region_bounds = required_region_bounds(tcx, opaque_type, bounds.into_iter());
353         if !required_region_bounds.is_empty() {
354             for required_region in required_region_bounds {
355                 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
356                     op: |r| self.sub_regions(infer::CallReturn(span), required_region, r),
357                 });
358             }
359             if let GenerateMemberConstraints::IfNoStaticBound = mode {
360                 self.generate_member_constraint(
361                     concrete_ty,
362                     opaque_defn,
363                     opaque_type_key,
364                     first_own_region,
365                 );
366             }
367             return;
368         }
369
370         // There were no `required_region_bounds`,
371         // so we have to search for a `least_region`.
372         // Go through all the regions used as arguments to the
373         // opaque type. These are the parameters to the opaque
374         // type; so in our example above, `substs` would contain
375         // `['a]` for the first impl trait and `'b` for the
376         // second.
377         let mut least_region = None;
378
379         for subst_arg in &opaque_type_key.substs[first_own_region..] {
380             let subst_region = match subst_arg.unpack() {
381                 GenericArgKind::Lifetime(r) => r,
382                 GenericArgKind::Type(_) | GenericArgKind::Const(_) => continue,
383             };
384
385             // Compute the least upper bound of it with the other regions.
386             debug!(?least_region);
387             debug!(?subst_region);
388             match least_region {
389                 None => least_region = Some(subst_region),
390                 Some(lr) => {
391                     if free_region_relations.sub_free_regions(self.tcx, lr, subst_region) {
392                         // keep the current least region
393                     } else if free_region_relations.sub_free_regions(self.tcx, subst_region, lr) {
394                         // switch to `subst_region`
395                         least_region = Some(subst_region);
396                     } else {
397                         // There are two regions (`lr` and
398                         // `subst_region`) which are not relatable. We
399                         // can't find a best choice. Therefore,
400                         // instead of creating a single bound like
401                         // `'r: 'a` (which is our preferred choice),
402                         // we will create a "in bound" like `'r in
403                         // ['a, 'b, 'c]`, where `'a..'c` are the
404                         // regions that appear in the impl trait.
405
406                         return self.generate_member_constraint(
407                             concrete_ty,
408                             opaque_defn,
409                             opaque_type_key,
410                             first_own_region,
411                         );
412                     }
413                 }
414             }
415         }
416
417         let least_region = least_region.unwrap_or(tcx.lifetimes.re_static);
418         debug!(?least_region);
419
420         if let GenerateMemberConstraints::IfNoStaticBound = mode {
421             if least_region != tcx.lifetimes.re_static {
422                 self.generate_member_constraint(
423                     concrete_ty,
424                     opaque_defn,
425                     opaque_type_key,
426                     first_own_region,
427                 );
428             }
429         }
430         concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
431             op: |r| self.sub_regions(infer::CallReturn(span), least_region, r),
432         });
433     }
434
435     /// As a fallback, we sometimes generate an "in constraint". For
436     /// a case like `impl Foo<'a, 'b>`, where `'a` and `'b` cannot be
437     /// related, we would generate a constraint `'r in ['a, 'b,
438     /// 'static]` for each region `'r` that appears in the hidden type
439     /// (i.e., it must be equal to `'a`, `'b`, or `'static`).
440     ///
441     /// `conflict1` and `conflict2` are the two region bounds that we
442     /// detected which were unrelated. They are used for diagnostics.
443     fn generate_member_constraint(
444         &self,
445         concrete_ty: Ty<'tcx>,
446         opaque_defn: &OpaqueTypeDecl<'tcx>,
447         opaque_type_key: OpaqueTypeKey<'tcx>,
448         first_own_region: usize,
449     ) {
450         // Create the set of choice regions: each region in the hidden
451         // type can be equal to any of the region parameters of the
452         // opaque type definition.
453         let choice_regions: Lrc<Vec<ty::Region<'tcx>>> = Lrc::new(
454             opaque_type_key.substs[first_own_region..]
455                 .iter()
456                 .filter_map(|arg| match arg.unpack() {
457                     GenericArgKind::Lifetime(r) => Some(r),
458                     GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
459                 })
460                 .chain(std::iter::once(self.tcx.lifetimes.re_static))
461                 .collect(),
462         );
463
464         concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
465             op: |r| {
466                 self.member_constraint(
467                     opaque_type_key.def_id,
468                     opaque_defn.definition_span,
469                     concrete_ty,
470                     r,
471                     &choice_regions,
472                 )
473             },
474         });
475     }
476
477     /// Given the fully resolved, instantiated type for an opaque
478     /// type, i.e., the value of an inference variable like C1 or C2
479     /// (*), computes the "definition type" for an opaque type
480     /// definition -- that is, the inferred value of `Foo1<'x>` or
481     /// `Foo2<'x>` that we would conceptually use in its definition:
482     ///
483     ///     type Foo1<'x> = impl Bar<'x> = AAA; <-- this type AAA
484     ///     type Foo2<'x> = impl Bar<'x> = BBB; <-- or this type BBB
485     ///     fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
486     ///
487     /// Note that these values are defined in terms of a distinct set of
488     /// generic parameters (`'x` instead of `'a`) from C1 or C2. The main
489     /// purpose of this function is to do that translation.
490     ///
491     /// (*) C1 and C2 were introduced in the comments on
492     /// `constrain_opaque_types`. Read that comment for more context.
493     ///
494     /// # Parameters
495     ///
496     /// - `def_id`, the `impl Trait` type
497     /// - `substs`, the substs  used to instantiate this opaque type
498     /// - `instantiated_ty`, the inferred type C1 -- fully resolved, lifted version of
499     ///   `opaque_defn.concrete_ty`
500     #[instrument(skip(self))]
501     fn infer_opaque_definition_from_instantiation(
502         &self,
503         opaque_type_key: OpaqueTypeKey<'tcx>,
504         instantiated_ty: Ty<'tcx>,
505         span: Span,
506     ) -> Ty<'tcx> {
507         let OpaqueTypeKey { def_id, substs } = opaque_type_key;
508
509         // Use substs to build up a reverse map from regions to their
510         // identity mappings. This is necessary because of `impl
511         // Trait` lifetimes are computed by replacing existing
512         // lifetimes with 'static and remapping only those used in the
513         // `impl Trait` return type, resulting in the parameters
514         // shifting.
515         let id_substs = InternalSubsts::identity_for_item(self.tcx, def_id);
516         debug!(?id_substs);
517         let map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>> =
518             substs.iter().enumerate().map(|(index, subst)| (subst, id_substs[index])).collect();
519
520         // Convert the type from the function into a type valid outside
521         // the function, by replacing invalid regions with 'static,
522         // after producing an error for each of them.
523         let definition_ty = instantiated_ty.fold_with(&mut ReverseMapper::new(
524             self.tcx,
525             self.is_tainted_by_errors(),
526             def_id,
527             map,
528             instantiated_ty,
529             span,
530         ));
531         debug!(?definition_ty);
532
533         definition_ty
534     }
535 }
536
537 // Visitor that requires that (almost) all regions in the type visited outlive
538 // `least_region`. We cannot use `push_outlives_components` because regions in
539 // closure signatures are not included in their outlives components. We need to
540 // ensure all regions outlive the given bound so that we don't end up with,
541 // say, `ReVar` appearing in a return type and causing ICEs when other
542 // functions end up with region constraints involving regions from other
543 // functions.
544 //
545 // We also cannot use `for_each_free_region` because for closures it includes
546 // the regions parameters from the enclosing item.
547 //
548 // We ignore any type parameters because impl trait values are assumed to
549 // capture all the in-scope type parameters.
550 struct ConstrainOpaqueTypeRegionVisitor<OP> {
551     op: OP,
552 }
553
554 impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<OP>
555 where
556     OP: FnMut(ty::Region<'tcx>),
557 {
558     fn visit_binder<T: TypeFoldable<'tcx>>(
559         &mut self,
560         t: &ty::Binder<'tcx, T>,
561     ) -> ControlFlow<Self::BreakTy> {
562         t.as_ref().skip_binder().visit_with(self);
563         ControlFlow::CONTINUE
564     }
565
566     fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
567         match *r {
568             // ignore bound regions, keep visiting
569             ty::ReLateBound(_, _) => ControlFlow::CONTINUE,
570             _ => {
571                 (self.op)(r);
572                 ControlFlow::CONTINUE
573             }
574         }
575     }
576
577     fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
578         // We're only interested in types involving regions
579         if !ty.flags().intersects(ty::TypeFlags::HAS_FREE_REGIONS) {
580             return ControlFlow::CONTINUE;
581         }
582
583         match ty.kind() {
584             ty::Closure(_, ref substs) => {
585                 // Skip lifetime parameters of the enclosing item(s)
586
587                 substs.as_closure().tupled_upvars_ty().visit_with(self);
588                 substs.as_closure().sig_as_fn_ptr_ty().visit_with(self);
589             }
590
591             ty::Generator(_, ref substs, _) => {
592                 // Skip lifetime parameters of the enclosing item(s)
593                 // Also skip the witness type, because that has no free regions.
594
595                 substs.as_generator().tupled_upvars_ty().visit_with(self);
596                 substs.as_generator().return_ty().visit_with(self);
597                 substs.as_generator().yield_ty().visit_with(self);
598                 substs.as_generator().resume_ty().visit_with(self);
599             }
600             _ => {
601                 ty.super_visit_with(self);
602             }
603         }
604
605         ControlFlow::CONTINUE
606     }
607 }
608
609 struct ReverseMapper<'tcx> {
610     tcx: TyCtxt<'tcx>,
611
612     /// If errors have already been reported in this fn, we suppress
613     /// our own errors because they are sometimes derivative.
614     tainted_by_errors: bool,
615
616     opaque_type_def_id: DefId,
617     map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>>,
618     map_missing_regions_to_empty: bool,
619
620     /// initially `Some`, set to `None` once error has been reported
621     hidden_ty: Option<Ty<'tcx>>,
622
623     /// Span of function being checked.
624     span: Span,
625 }
626
627 impl ReverseMapper<'tcx> {
628     fn new(
629         tcx: TyCtxt<'tcx>,
630         tainted_by_errors: bool,
631         opaque_type_def_id: DefId,
632         map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>>,
633         hidden_ty: Ty<'tcx>,
634         span: Span,
635     ) -> Self {
636         Self {
637             tcx,
638             tainted_by_errors,
639             opaque_type_def_id,
640             map,
641             map_missing_regions_to_empty: false,
642             hidden_ty: Some(hidden_ty),
643             span,
644         }
645     }
646
647     fn fold_kind_mapping_missing_regions_to_empty(
648         &mut self,
649         kind: GenericArg<'tcx>,
650     ) -> GenericArg<'tcx> {
651         assert!(!self.map_missing_regions_to_empty);
652         self.map_missing_regions_to_empty = true;
653         let kind = kind.fold_with(self);
654         self.map_missing_regions_to_empty = false;
655         kind
656     }
657
658     fn fold_kind_normally(&mut self, kind: GenericArg<'tcx>) -> GenericArg<'tcx> {
659         assert!(!self.map_missing_regions_to_empty);
660         kind.fold_with(self)
661     }
662 }
663
664 impl TypeFolder<'tcx> for ReverseMapper<'tcx> {
665     fn tcx(&self) -> TyCtxt<'tcx> {
666         self.tcx
667     }
668
669     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
670         match r {
671             // Ignore bound regions and `'static` regions that appear in the
672             // type, we only need to remap regions that reference lifetimes
673             // from the function declaraion.
674             // This would ignore `'r` in a type like `for<'r> fn(&'r u32)`.
675             ty::ReLateBound(..) | ty::ReStatic => return r,
676
677             // If regions have been erased (by writeback), don't try to unerase
678             // them.
679             ty::ReErased => return r,
680
681             // The regions that we expect from borrow checking.
682             ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReEmpty(ty::UniverseIndex::ROOT) => {}
683
684             ty::ReEmpty(_) | ty::RePlaceholder(_) | ty::ReVar(_) => {
685                 // All of the regions in the type should either have been
686                 // erased by writeback, or mapped back to named regions by
687                 // borrow checking.
688                 bug!("unexpected region kind in opaque type: {:?}", r);
689             }
690         }
691
692         let generics = self.tcx().generics_of(self.opaque_type_def_id);
693         match self.map.get(&r.into()).map(|k| k.unpack()) {
694             Some(GenericArgKind::Lifetime(r1)) => r1,
695             Some(u) => panic!("region mapped to unexpected kind: {:?}", u),
696             None if self.map_missing_regions_to_empty || self.tainted_by_errors => {
697                 self.tcx.lifetimes.re_root_empty
698             }
699             None if generics.parent.is_some() => {
700                 if let Some(hidden_ty) = self.hidden_ty.take() {
701                     unexpected_hidden_region_diagnostic(
702                         self.tcx,
703                         self.tcx.def_span(self.opaque_type_def_id),
704                         hidden_ty,
705                         r,
706                     )
707                     .emit();
708                 }
709                 self.tcx.lifetimes.re_root_empty
710             }
711             None => {
712                 self.tcx
713                     .sess
714                     .struct_span_err(self.span, "non-defining opaque type use in defining scope")
715                     .span_label(
716                         self.span,
717                         format!(
718                             "lifetime `{}` is part of concrete type but not used in \
719                                  parameter list of the `impl Trait` type alias",
720                             r
721                         ),
722                     )
723                     .emit();
724
725                 self.tcx().lifetimes.re_static
726             }
727         }
728     }
729
730     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
731         match *ty.kind() {
732             ty::Closure(def_id, substs) => {
733                 // I am a horrible monster and I pray for death. When
734                 // we encounter a closure here, it is always a closure
735                 // from within the function that we are currently
736                 // type-checking -- one that is now being encapsulated
737                 // in an opaque type. Ideally, we would
738                 // go through the types/lifetimes that it references
739                 // and treat them just like we would any other type,
740                 // which means we would error out if we find any
741                 // reference to a type/region that is not in the
742                 // "reverse map".
743                 //
744                 // **However,** in the case of closures, there is a
745                 // somewhat subtle (read: hacky) consideration. The
746                 // problem is that our closure types currently include
747                 // all the lifetime parameters declared on the
748                 // enclosing function, even if they are unused by the
749                 // closure itself. We can't readily filter them out,
750                 // so here we replace those values with `'empty`. This
751                 // can't really make a difference to the rest of the
752                 // compiler; those regions are ignored for the
753                 // outlives relation, and hence don't affect trait
754                 // selection or auto traits, and they are erased
755                 // during codegen.
756
757                 let generics = self.tcx.generics_of(def_id);
758                 let substs = self.tcx.mk_substs(substs.iter().enumerate().map(|(index, kind)| {
759                     if index < generics.parent_count {
760                         // Accommodate missing regions in the parent kinds...
761                         self.fold_kind_mapping_missing_regions_to_empty(kind)
762                     } else {
763                         // ...but not elsewhere.
764                         self.fold_kind_normally(kind)
765                     }
766                 }));
767
768                 self.tcx.mk_closure(def_id, substs)
769             }
770
771             ty::Generator(def_id, substs, movability) => {
772                 let generics = self.tcx.generics_of(def_id);
773                 let substs = self.tcx.mk_substs(substs.iter().enumerate().map(|(index, kind)| {
774                     if index < generics.parent_count {
775                         // Accommodate missing regions in the parent kinds...
776                         self.fold_kind_mapping_missing_regions_to_empty(kind)
777                     } else {
778                         // ...but not elsewhere.
779                         self.fold_kind_normally(kind)
780                     }
781                 }));
782
783                 self.tcx.mk_generator(def_id, substs, movability)
784             }
785
786             ty::Param(param) => {
787                 // Look it up in the substitution list.
788                 match self.map.get(&ty.into()).map(|k| k.unpack()) {
789                     // Found it in the substitution list; replace with the parameter from the
790                     // opaque type.
791                     Some(GenericArgKind::Type(t1)) => t1,
792                     Some(u) => panic!("type mapped to unexpected kind: {:?}", u),
793                     None => {
794                         debug!(?param, ?self.map);
795                         self.tcx
796                             .sess
797                             .struct_span_err(
798                                 self.span,
799                                 &format!(
800                                     "type parameter `{}` is part of concrete type but not \
801                                           used in parameter list for the `impl Trait` type alias",
802                                     ty
803                                 ),
804                             )
805                             .emit();
806
807                         self.tcx().ty_error()
808                     }
809                 }
810             }
811
812             _ => ty.super_fold_with(self),
813         }
814     }
815
816     fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
817         trace!("checking const {:?}", ct);
818         // Find a const parameter
819         match ct.val {
820             ty::ConstKind::Param(..) => {
821                 // Look it up in the substitution list.
822                 match self.map.get(&ct.into()).map(|k| k.unpack()) {
823                     // Found it in the substitution list, replace with the parameter from the
824                     // opaque type.
825                     Some(GenericArgKind::Const(c1)) => c1,
826                     Some(u) => panic!("const mapped to unexpected kind: {:?}", u),
827                     None => {
828                         self.tcx
829                             .sess
830                             .struct_span_err(
831                                 self.span,
832                                 &format!(
833                                     "const parameter `{}` is part of concrete type but not \
834                                           used in parameter list for the `impl Trait` type alias",
835                                     ct
836                                 ),
837                             )
838                             .emit();
839
840                         self.tcx().const_error(ct.ty)
841                     }
842                 }
843             }
844
845             _ => ct,
846         }
847     }
848 }
849
850 struct Instantiator<'a, 'tcx> {
851     infcx: &'a InferCtxt<'a, 'tcx>,
852     body_id: hir::HirId,
853     param_env: ty::ParamEnv<'tcx>,
854     value_span: Span,
855     obligations: Vec<PredicateObligation<'tcx>>,
856 }
857
858 impl<'a, 'tcx> Instantiator<'a, 'tcx> {
859     #[instrument(skip(self))]
860     fn instantiate_opaque_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
861         let tcx = self.infcx.tcx;
862         value.fold_with(&mut BottomUpFolder {
863             tcx,
864             ty_op: |ty| {
865                 if ty.references_error() {
866                     return tcx.ty_error();
867                 } else if let ty::Opaque(def_id, substs) = ty.kind() {
868                     // Check that this is `impl Trait` type is
869                     // declared by `parent_def_id` -- i.e., one whose
870                     // value we are inferring.  At present, this is
871                     // always true during the first phase of
872                     // type-check, but not always true later on during
873                     // NLL. Once we support named opaque types more fully,
874                     // this same scenario will be able to arise during all phases.
875                     //
876                     // Here is an example using type alias `impl Trait`
877                     // that indicates the distinction we are checking for:
878                     //
879                     // ```rust
880                     // mod a {
881                     //   pub type Foo = impl Iterator;
882                     //   pub fn make_foo() -> Foo { .. }
883                     // }
884                     //
885                     // mod b {
886                     //   fn foo() -> a::Foo { a::make_foo() }
887                     // }
888                     // ```
889                     //
890                     // Here, the return type of `foo` references a
891                     // `Opaque` indeed, but not one whose value is
892                     // presently being inferred. You can get into a
893                     // similar situation with closure return types
894                     // today:
895                     //
896                     // ```rust
897                     // fn foo() -> impl Iterator { .. }
898                     // fn bar() {
899                     //     let x = || foo(); // returns the Opaque assoc with `foo`
900                     // }
901                     // ```
902                     if let Some(def_id) = def_id.as_local() {
903                         let opaque_hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
904                         let parent_def_id = self.infcx.defining_use_anchor;
905                         let def_scope_default = || {
906                             let opaque_parent_hir_id = tcx.hir().get_parent_item(opaque_hir_id);
907                             parent_def_id == tcx.hir().local_def_id(opaque_parent_hir_id)
908                         };
909                         let (in_definition_scope, origin) =
910                             match tcx.hir().expect_item(opaque_hir_id).kind {
911                                 // Anonymous `impl Trait`
912                                 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
913                                     impl_trait_fn: Some(parent),
914                                     origin,
915                                     ..
916                                 }) => (parent == parent_def_id.to_def_id(), origin),
917                                 // Named `type Foo = impl Bar;`
918                                 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
919                                     impl_trait_fn: None,
920                                     origin,
921                                     ..
922                                 }) => (
923                                     may_define_opaque_type(tcx, parent_def_id, opaque_hir_id),
924                                     origin,
925                                 ),
926                                 _ => (def_scope_default(), hir::OpaqueTyOrigin::TyAlias),
927                             };
928                         if in_definition_scope {
929                             let opaque_type_key =
930                                 OpaqueTypeKey { def_id: def_id.to_def_id(), substs };
931                             return self.fold_opaque_ty(ty, opaque_type_key, origin);
932                         }
933
934                         debug!(
935                             "instantiate_opaque_types_in_map: \
936                              encountered opaque outside its definition scope \
937                              def_id={:?}",
938                             def_id,
939                         );
940                     }
941                 }
942
943                 ty
944             },
945             lt_op: |lt| lt,
946             ct_op: |ct| ct,
947         })
948     }
949
950     fn fold_opaque_ty(
951         &mut self,
952         ty: Ty<'tcx>,
953         opaque_type_key: OpaqueTypeKey<'tcx>,
954         origin: hir::OpaqueTyOrigin,
955     ) -> Ty<'tcx> {
956         let infcx = self.infcx;
957         let tcx = infcx.tcx;
958         let OpaqueTypeKey { def_id, substs } = opaque_type_key;
959
960         debug!("instantiate_opaque_types: Opaque(def_id={:?}, substs={:?})", def_id, substs);
961
962         // Use the same type variable if the exact same opaque type appears more
963         // than once in the return type (e.g., if it's passed to a type alias).
964         if let Some(opaque_defn) = infcx.inner.borrow().opaque_types.get(&opaque_type_key) {
965             debug!("instantiate_opaque_types: returning concrete ty {:?}", opaque_defn.concrete_ty);
966             return opaque_defn.concrete_ty;
967         }
968         let span = tcx.def_span(def_id);
969         debug!("fold_opaque_ty {:?} {:?}", self.value_span, span);
970         let ty_var = infcx
971             .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
972
973         // Make sure that we are in fact defining the *entire* type
974         // (e.g., `type Foo<T: Bound> = impl Bar;` needs to be
975         // defined by a function like `fn foo<T: Bound>() -> Foo<T>`).
976         debug!("instantiate_opaque_types: param_env={:#?}", self.param_env,);
977         debug!("instantiate_opaque_types: generics={:#?}", tcx.generics_of(def_id),);
978
979         // Ideally, we'd get the span where *this specific `ty` came
980         // from*, but right now we just use the span from the overall
981         // value being folded. In simple cases like `-> impl Foo`,
982         // these are the same span, but not in cases like `-> (impl
983         // Foo, impl Bar)`.
984         let definition_span = self.value_span;
985
986         {
987             let mut infcx = self.infcx.inner.borrow_mut();
988             infcx.opaque_types.insert(
989                 OpaqueTypeKey { def_id, substs },
990                 OpaqueTypeDecl { opaque_type: ty, definition_span, concrete_ty: ty_var, origin },
991             );
992             infcx.opaque_types_vars.insert(ty_var, ty);
993         }
994
995         debug!("instantiate_opaque_types: ty_var={:?}", ty_var);
996         self.compute_opaque_type_obligations(opaque_type_key, span);
997
998         ty_var
999     }
1000
1001     fn compute_opaque_type_obligations(
1002         &mut self,
1003         opaque_type_key: OpaqueTypeKey<'tcx>,
1004         span: Span,
1005     ) {
1006         let infcx = self.infcx;
1007         let tcx = infcx.tcx;
1008         let OpaqueTypeKey { def_id, substs } = opaque_type_key;
1009
1010         let item_bounds = tcx.explicit_item_bounds(def_id);
1011         debug!("instantiate_opaque_types: bounds={:#?}", item_bounds);
1012         let bounds: Vec<_> =
1013             item_bounds.iter().map(|(bound, _)| bound.subst(tcx, substs)).collect();
1014
1015         let param_env = tcx.param_env(def_id);
1016         let InferOk { value: bounds, obligations } = infcx.partially_normalize_associated_types_in(
1017             ObligationCause::misc(span, self.body_id),
1018             param_env,
1019             bounds,
1020         );
1021         self.obligations.extend(obligations);
1022
1023         debug!("instantiate_opaque_types: bounds={:?}", bounds);
1024
1025         for predicate in &bounds {
1026             if let ty::PredicateKind::Projection(projection) = predicate.kind().skip_binder() {
1027                 if projection.ty.references_error() {
1028                     // No point on adding these obligations since there's a type error involved.
1029                     return;
1030                 }
1031             }
1032         }
1033
1034         self.obligations.reserve(bounds.len());
1035         for predicate in bounds {
1036             // Change the predicate to refer to the type variable,
1037             // which will be the concrete type instead of the opaque type.
1038             // This also instantiates nested instances of `impl Trait`.
1039             let predicate = self.instantiate_opaque_types_in_map(predicate);
1040
1041             let cause = traits::ObligationCause::new(span, self.body_id, traits::OpaqueType);
1042
1043             // Require that the predicate holds for the concrete type.
1044             debug!("instantiate_opaque_types: predicate={:?}", predicate);
1045             self.obligations.push(traits::Obligation::new(cause, self.param_env, predicate));
1046         }
1047     }
1048 }
1049
1050 /// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`.
1051 ///
1052 /// Example:
1053 /// ```rust
1054 /// pub mod foo {
1055 ///     pub mod bar {
1056 ///         pub trait Bar { .. }
1057 ///
1058 ///         pub type Baz = impl Bar;
1059 ///
1060 ///         fn f1() -> Baz { .. }
1061 ///     }
1062 ///
1063 ///     fn f2() -> bar::Baz { .. }
1064 /// }
1065 /// ```
1066 ///
1067 /// Here, `def_id` is the `LocalDefId` of the defining use of the opaque type (e.g., `f1` or `f2`),
1068 /// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`.
1069 /// For the above example, this function returns `true` for `f1` and `false` for `f2`.
1070 pub fn may_define_opaque_type(
1071     tcx: TyCtxt<'_>,
1072     def_id: LocalDefId,
1073     opaque_hir_id: hir::HirId,
1074 ) -> bool {
1075     let mut hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1076
1077     // Named opaque types can be defined by any siblings or children of siblings.
1078     let scope = tcx.hir().get_defining_scope(opaque_hir_id);
1079     // We walk up the node tree until we hit the root or the scope of the opaque type.
1080     while hir_id != scope && hir_id != hir::CRATE_HIR_ID {
1081         hir_id = tcx.hir().get_parent_item(hir_id);
1082     }
1083     // Syntactically, we are allowed to define the concrete type if:
1084     let res = hir_id == scope;
1085     trace!(
1086         "may_define_opaque_type(def={:?}, opaque_node={:?}) = {}",
1087         tcx.hir().find(hir_id),
1088         tcx.hir().get(opaque_hir_id),
1089         res
1090     );
1091     res
1092 }
1093
1094 /// Given a set of predicates that apply to an object type, returns
1095 /// the region bounds that the (erased) `Self` type must
1096 /// outlive. Precisely *because* the `Self` type is erased, the
1097 /// parameter `erased_self_ty` must be supplied to indicate what type
1098 /// has been used to represent `Self` in the predicates
1099 /// themselves. This should really be a unique type; `FreshTy(0)` is a
1100 /// popular choice.
1101 ///
1102 /// N.B., in some cases, particularly around higher-ranked bounds,
1103 /// this function returns a kind of conservative approximation.
1104 /// That is, all regions returned by this function are definitely
1105 /// required, but there may be other region bounds that are not
1106 /// returned, as well as requirements like `for<'a> T: 'a`.
1107 ///
1108 /// Requires that trait definitions have been processed so that we can
1109 /// elaborate predicates and walk supertraits.
1110 crate fn required_region_bounds(
1111     tcx: TyCtxt<'tcx>,
1112     erased_self_ty: Ty<'tcx>,
1113     predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
1114 ) -> Vec<ty::Region<'tcx>> {
1115     debug!("required_region_bounds(erased_self_ty={:?})", erased_self_ty);
1116
1117     assert!(!erased_self_ty.has_escaping_bound_vars());
1118
1119     traits::elaborate_predicates(tcx, predicates)
1120         .filter_map(|obligation| {
1121             debug!("required_region_bounds(obligation={:?})", obligation);
1122             match obligation.predicate.kind().skip_binder() {
1123                 ty::PredicateKind::Projection(..)
1124                 | ty::PredicateKind::Trait(..)
1125                 | ty::PredicateKind::Subtype(..)
1126                 | ty::PredicateKind::WellFormed(..)
1127                 | ty::PredicateKind::ObjectSafe(..)
1128                 | ty::PredicateKind::ClosureKind(..)
1129                 | ty::PredicateKind::RegionOutlives(..)
1130                 | ty::PredicateKind::ConstEvaluatable(..)
1131                 | ty::PredicateKind::ConstEquate(..)
1132                 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
1133                 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => {
1134                     // Search for a bound of the form `erased_self_ty
1135                     // : 'a`, but be wary of something like `for<'a>
1136                     // erased_self_ty : 'a` (we interpret a
1137                     // higher-ranked bound like that as 'static,
1138                     // though at present the code in `fulfill.rs`
1139                     // considers such bounds to be unsatisfiable, so
1140                     // it's kind of a moot point since you could never
1141                     // construct such an object, but this seems
1142                     // correct even if that code changes).
1143                     if t == &erased_self_ty && !r.has_escaping_bound_vars() {
1144                         Some(*r)
1145                     } else {
1146                         None
1147                     }
1148                 }
1149             }
1150         })
1151         .collect()
1152 }