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