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