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