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