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