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