]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/fold.rs
Merge commit 'dc5423ad448877e33cca28db2f1445c9c4473c75' into clippyup
[rust.git] / compiler / rustc_middle / src / ty / fold.rs
1 //! A generalized traversal mechanism for complex data structures that contain
2 //! type information.
3 //!
4 //! There are two types of traversal.
5 //! - Folding. This is a modifying traversal. It consumes the data structure,
6 //!   producing a (possibly) modified version of it. Both fallible and
7 //!   infallible versions are available. The name is potentially
8 //!   confusing, because this traversal is more like `Iterator::map` than
9 //!   `Iterator::fold`.
10 //! - Visiting. This is a read-only traversal of the data structure.
11 //!
12 //! These traversals have limited flexibility. Only a small number of "types of
13 //! interest" within the complex data structures can receive custom
14 //! modification (when folding) or custom visitation (when visiting). These are
15 //! the ones containing the most important type-related information, such as
16 //! `Ty`, `Predicate`, `Region`, and `Const`.
17 //!
18 //! There are two traits involved in each traversal type.
19 //! - The first trait is `TypeFoldable`, which is implemented once for many
20 //!   types. This includes both (a) types of interest, and (b) all other
21 //!   relevant types, including generic containers like `Vec` and `Option`. It
22 //!   defines a "skeleton" of how they should be traversed, for both folding
23 //!   and visiting.
24 //! - The second trait is `TypeFolder`/`FallibleTypeFolder` (for
25 //!   infallible/fallible folding traversals) or `TypeVisitor` (for visiting
26 //!   traversals). One of these is implemented for each folder/visitor. This
27 //!   defines how types of interest are handled.
28 //!
29 //! This means each traversal is a mixture of (a) generic traversal operations,
30 //! and (b) custom fold/visit operations that are specific to the
31 //! folder/visitor.
32 //! - The `TypeFoldable` impls handle most of the traversal, and call into
33 //!   `TypeFolder`/`FallibleTypeFolder`/`TypeVisitor` when they encounter a
34 //!   type of interest.
35 //! - A `TypeFolder`/`FallibleTypeFolder`/`TypeVisitor` may also call back into
36 //!   a `TypeFoldable` impl, because (a) the types of interest are recursive
37 //!   and can contain other types of interest, and (b) each folder/visitor
38 //!   might provide custom handling only for some types of interest, or only
39 //!   for some variants of each type of interest, and then use default
40 //!   traversal for the remaining cases.
41 //!
42 //! For example, if you have `struct S(Ty, U)` where `S: TypeFoldable` and `U:
43 //! TypeFoldable`, and an instance `S(ty, u)`, it would be visited like so:
44 //! ```
45 //! s.visit_with(visitor) calls
46 //! - s.super_visit_with(visitor) calls
47 //!   - ty.visit_with(visitor) calls
48 //!     - visitor.visit_ty(ty) may call
49 //!       - ty.super_visit_with(visitor)
50 //!   - u.visit_with(visitor)
51 //! ```
52 use crate::mir;
53 use crate::ty::{self, flags::FlagComputation, Binder, Ty, TyCtxt, TypeFlags};
54 use rustc_hir::def_id::DefId;
55
56 use rustc_data_structures::fx::FxHashSet;
57 use rustc_data_structures::sso::SsoHashSet;
58 use std::collections::BTreeMap;
59 use std::fmt;
60 use std::ops::ControlFlow;
61
62 /// This trait is implemented for every type that can be folded/visited,
63 /// providing the skeleton of the traversal.
64 ///
65 /// To implement this conveniently, use the derive macro located in
66 /// `rustc_macros`.
67 pub trait TypeFoldable<'tcx>: fmt::Debug + Clone {
68     /// The main entry point for folding. To fold a value `t` with a folder `f`
69     /// call: `t.try_fold_with(f)`.
70     ///
71     /// For types of interest (such as `Ty`), this default is overridden with a
72     /// method that calls a folder method specifically for that type (such as
73     /// `F::try_fold_ty`). This is where control transfers from `TypeFoldable`
74     /// to `TypeFolder`.
75     ///
76     /// For other types, this default is used.
77     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
78         self.try_super_fold_with(folder)
79     }
80
81     /// A convenient alternative to `try_fold_with` for use with infallible
82     /// folders. Do not override this method, to ensure coherence with
83     /// `try_fold_with`.
84     fn fold_with<F: TypeFolder<'tcx, Error = !>>(self, folder: &mut F) -> Self {
85         self.try_fold_with(folder).into_ok()
86     }
87
88     /// Traverses the type in question, typically by calling `try_fold_with` on
89     /// each field/element. This is true even for types of interest such as
90     /// `Ty`. This should only be called within `TypeFolder` methods, when
91     /// non-custom traversals are desired for types of interest.
92     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
93         self,
94         folder: &mut F,
95     ) -> Result<Self, F::Error>;
96
97     /// A convenient alternative to `try_super_fold_with` for use with
98     /// infallible folders. Do not override this method, to ensure coherence
99     /// with `try_super_fold_with`.
100     fn super_fold_with<F: TypeFolder<'tcx, Error = !>>(self, folder: &mut F) -> Self {
101         self.try_super_fold_with(folder).into_ok()
102     }
103
104     /// The entry point for visiting. To visit a value `t` with a visitor `v`
105     /// call: `t.visit_with(v)`.
106     ///
107     /// For types of interest (such as `Ty`), this default is overridden with a
108     /// method that calls a visitor method specifically for that type (such as
109     /// `V::visit_ty`). This is where control transfers from `TypeFoldable` to
110     /// `TypeVisitor`.
111     ///
112     /// For other types, this default is used.
113     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
114         self.super_visit_with(visitor)
115     }
116
117     /// Traverses the type in question, typically by calling `visit_with` on
118     /// each field/element. This is true even for types of interest such as
119     /// `Ty`. This should only be called within `TypeVisitor` methods, when
120     /// non-custom traversals are desired for types of interest.
121     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy>;
122
123     /// Returns `true` if `self` has any late-bound regions that are either
124     /// bound by `binder` or bound by some binder outside of `binder`.
125     /// If `binder` is `ty::INNERMOST`, this indicates whether
126     /// there are any late-bound regions that appear free.
127     fn has_vars_bound_at_or_above(&self, binder: ty::DebruijnIndex) -> bool {
128         self.visit_with(&mut HasEscapingVarsVisitor { outer_index: binder }).is_break()
129     }
130
131     /// Returns `true` if this `self` has any regions that escape `binder` (and
132     /// hence are not bound by it).
133     fn has_vars_bound_above(&self, binder: ty::DebruijnIndex) -> bool {
134         self.has_vars_bound_at_or_above(binder.shifted_in(1))
135     }
136
137     fn has_escaping_bound_vars(&self) -> bool {
138         self.has_vars_bound_at_or_above(ty::INNERMOST)
139     }
140
141     #[instrument(level = "trace")]
142     fn has_type_flags(&self, flags: TypeFlags) -> bool {
143         self.visit_with(&mut HasTypeFlagsVisitor { flags }).break_value() == Some(FoundFlags)
144     }
145     fn has_projections(&self) -> bool {
146         self.has_type_flags(TypeFlags::HAS_PROJECTION)
147     }
148     fn has_opaque_types(&self) -> bool {
149         self.has_type_flags(TypeFlags::HAS_TY_OPAQUE)
150     }
151     fn references_error(&self) -> bool {
152         self.has_type_flags(TypeFlags::HAS_ERROR)
153     }
154     fn has_param_types_or_consts(&self) -> bool {
155         self.has_type_flags(TypeFlags::HAS_TY_PARAM | TypeFlags::HAS_CT_PARAM)
156     }
157     fn has_infer_regions(&self) -> bool {
158         self.has_type_flags(TypeFlags::HAS_RE_INFER)
159     }
160     fn has_infer_types(&self) -> bool {
161         self.has_type_flags(TypeFlags::HAS_TY_INFER)
162     }
163     fn has_infer_types_or_consts(&self) -> bool {
164         self.has_type_flags(TypeFlags::HAS_TY_INFER | TypeFlags::HAS_CT_INFER)
165     }
166     fn needs_infer(&self) -> bool {
167         self.has_type_flags(TypeFlags::NEEDS_INFER)
168     }
169     fn has_placeholders(&self) -> bool {
170         self.has_type_flags(
171             TypeFlags::HAS_RE_PLACEHOLDER
172                 | TypeFlags::HAS_TY_PLACEHOLDER
173                 | TypeFlags::HAS_CT_PLACEHOLDER,
174         )
175     }
176     fn needs_subst(&self) -> bool {
177         self.has_type_flags(TypeFlags::NEEDS_SUBST)
178     }
179     /// "Free" regions in this context means that it has any region
180     /// that is not (a) erased or (b) late-bound.
181     fn has_free_regions(&self) -> bool {
182         self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
183     }
184
185     fn has_erased_regions(&self) -> bool {
186         self.has_type_flags(TypeFlags::HAS_RE_ERASED)
187     }
188
189     /// True if there are any un-erased free regions.
190     fn has_erasable_regions(&self) -> bool {
191         self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
192     }
193
194     /// Indicates whether this value references only 'global'
195     /// generic parameters that are the same regardless of what fn we are
196     /// in. This is used for caching.
197     fn is_global(&self) -> bool {
198         !self.has_type_flags(TypeFlags::HAS_FREE_LOCAL_NAMES)
199     }
200
201     /// True if there are any late-bound regions
202     fn has_late_bound_regions(&self) -> bool {
203         self.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND)
204     }
205
206     /// Indicates whether this value still has parameters/placeholders/inference variables
207     /// which could be replaced later, in a way that would change the results of `impl`
208     /// specialization.
209     fn still_further_specializable(&self) -> bool {
210         self.has_type_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE)
211     }
212 }
213
214 /// This trait is implemented for every folding traversal. There is a fold
215 /// method defined for every type of interest. Each such method has a default
216 /// that does an "identity" fold.
217 ///
218 /// If this folder is fallible (and therefore its [`Error`][`TypeFolder::Error`]
219 /// associated type is something other than the default `!`) then
220 /// [`FallibleTypeFolder`] should be implemented manually. Otherwise,
221 /// a blanket implementation of [`FallibleTypeFolder`] will defer to
222 /// the infallible methods of this trait to ensure that the two APIs
223 /// are coherent.
224 pub trait TypeFolder<'tcx>: Sized {
225     type Error = !;
226
227     fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
228
229     fn fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Binder<'tcx, T>
230     where
231         T: TypeFoldable<'tcx>,
232         Self: TypeFolder<'tcx, Error = !>,
233     {
234         t.super_fold_with(self)
235     }
236
237     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx>
238     where
239         Self: TypeFolder<'tcx, Error = !>,
240     {
241         t.super_fold_with(self)
242     }
243
244     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx>
245     where
246         Self: TypeFolder<'tcx, Error = !>,
247     {
248         r.super_fold_with(self)
249     }
250
251     fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx>
252     where
253         Self: TypeFolder<'tcx, Error = !>,
254     {
255         c.super_fold_with(self)
256     }
257
258     fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx>
259     where
260         Self: TypeFolder<'tcx, Error = !>,
261     {
262         p.super_fold_with(self)
263     }
264
265     fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx>
266     where
267         Self: TypeFolder<'tcx, Error = !>,
268     {
269         bug!("most type folders should not be folding MIR datastructures: {:?}", c)
270     }
271 }
272
273 /// This trait is implemented for every folding traversal. There is a fold
274 /// method defined for every type of interest. Each such method has a default
275 /// that does an "identity" fold.
276 ///
277 /// A blanket implementation of this trait (that defers to the relevant
278 /// method of [`TypeFolder`]) is provided for all infallible folders in
279 /// order to ensure the two APIs are coherent.
280 pub trait FallibleTypeFolder<'tcx>: TypeFolder<'tcx> {
281     fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, Self::Error>
282     where
283         T: TypeFoldable<'tcx>,
284     {
285         t.try_super_fold_with(self)
286     }
287
288     fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
289         t.try_super_fold_with(self)
290     }
291
292     fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
293         r.try_super_fold_with(self)
294     }
295
296     fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, Self::Error> {
297         c.try_super_fold_with(self)
298     }
299
300     fn try_fold_predicate(
301         &mut self,
302         p: ty::Predicate<'tcx>,
303     ) -> Result<ty::Predicate<'tcx>, Self::Error> {
304         p.try_super_fold_with(self)
305     }
306
307     fn try_fold_mir_const(
308         &mut self,
309         c: mir::ConstantKind<'tcx>,
310     ) -> Result<mir::ConstantKind<'tcx>, Self::Error> {
311         bug!("most type folders should not be folding MIR datastructures: {:?}", c)
312     }
313 }
314
315 // This blanket implementation of the fallible trait for infallible folders
316 // delegates to infallible methods to ensure coherence.
317 impl<'tcx, F> FallibleTypeFolder<'tcx> for F
318 where
319     F: TypeFolder<'tcx, Error = !>,
320 {
321     fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, Self::Error>
322     where
323         T: TypeFoldable<'tcx>,
324     {
325         Ok(self.fold_binder(t))
326     }
327
328     fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
329         Ok(self.fold_ty(t))
330     }
331
332     fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
333         Ok(self.fold_region(r))
334     }
335
336     fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, Self::Error> {
337         Ok(self.fold_const(c))
338     }
339
340     fn try_fold_predicate(
341         &mut self,
342         p: ty::Predicate<'tcx>,
343     ) -> Result<ty::Predicate<'tcx>, Self::Error> {
344         Ok(self.fold_predicate(p))
345     }
346
347     fn try_fold_mir_const(
348         &mut self,
349         c: mir::ConstantKind<'tcx>,
350     ) -> Result<mir::ConstantKind<'tcx>, Self::Error> {
351         Ok(self.fold_mir_const(c))
352     }
353 }
354
355 /// This trait is implemented for every visiting traversal. There is a visit
356 /// method defined for every type of interest. Each such method has a default
357 /// that recurses into the type's fields in a non-custom fashion.
358 pub trait TypeVisitor<'tcx>: Sized {
359     type BreakTy = !;
360
361     fn visit_binder<T: TypeFoldable<'tcx>>(
362         &mut self,
363         t: &Binder<'tcx, T>,
364     ) -> ControlFlow<Self::BreakTy> {
365         t.super_visit_with(self)
366     }
367
368     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
369         t.super_visit_with(self)
370     }
371
372     fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
373         r.super_visit_with(self)
374     }
375
376     fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
377         c.super_visit_with(self)
378     }
379
380     fn visit_unevaluated_const(&mut self, uv: ty::Unevaluated<'tcx>) -> ControlFlow<Self::BreakTy> {
381         uv.super_visit_with(self)
382     }
383
384     fn visit_predicate(&mut self, p: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
385         p.super_visit_with(self)
386     }
387 }
388
389 ///////////////////////////////////////////////////////////////////////////
390 // Some sample folders
391
392 pub struct BottomUpFolder<'tcx, F, G, H>
393 where
394     F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
395     G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
396     H: FnMut(ty::Const<'tcx>) -> ty::Const<'tcx>,
397 {
398     pub tcx: TyCtxt<'tcx>,
399     pub ty_op: F,
400     pub lt_op: G,
401     pub ct_op: H,
402 }
403
404 impl<'tcx, F, G, H> TypeFolder<'tcx> for BottomUpFolder<'tcx, F, G, H>
405 where
406     F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
407     G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
408     H: FnMut(ty::Const<'tcx>) -> ty::Const<'tcx>,
409 {
410     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
411         self.tcx
412     }
413
414     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
415         let t = ty.super_fold_with(self);
416         (self.ty_op)(t)
417     }
418
419     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
420         let r = r.super_fold_with(self);
421         (self.lt_op)(r)
422     }
423
424     fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
425         let ct = ct.super_fold_with(self);
426         (self.ct_op)(ct)
427     }
428 }
429
430 ///////////////////////////////////////////////////////////////////////////
431 // Region folder
432
433 impl<'tcx> TyCtxt<'tcx> {
434     /// Folds the escaping and free regions in `value` using `f`, and
435     /// sets `skipped_regions` to true if any late-bound region was found
436     /// and skipped.
437     pub fn fold_regions<T>(
438         self,
439         value: T,
440         skipped_regions: &mut bool,
441         mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
442     ) -> T
443     where
444         T: TypeFoldable<'tcx>,
445     {
446         value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f))
447     }
448
449     /// Invoke `callback` on every region appearing free in `value`.
450     pub fn for_each_free_region(
451         self,
452         value: &impl TypeFoldable<'tcx>,
453         mut callback: impl FnMut(ty::Region<'tcx>),
454     ) {
455         self.any_free_region_meets(value, |r| {
456             callback(r);
457             false
458         });
459     }
460
461     /// Returns `true` if `callback` returns true for every region appearing free in `value`.
462     pub fn all_free_regions_meet(
463         self,
464         value: &impl TypeFoldable<'tcx>,
465         mut callback: impl FnMut(ty::Region<'tcx>) -> bool,
466     ) -> bool {
467         !self.any_free_region_meets(value, |r| !callback(r))
468     }
469
470     /// Returns `true` if `callback` returns true for some region appearing free in `value`.
471     pub fn any_free_region_meets(
472         self,
473         value: &impl TypeFoldable<'tcx>,
474         callback: impl FnMut(ty::Region<'tcx>) -> bool,
475     ) -> bool {
476         struct RegionVisitor<F> {
477             /// The index of a binder *just outside* the things we have
478             /// traversed. If we encounter a bound region bound by this
479             /// binder or one outer to it, it appears free. Example:
480             ///
481             /// ```
482             ///    for<'a> fn(for<'b> fn(), T)
483             /// ^          ^          ^     ^
484             /// |          |          |     | here, would be shifted in 1
485             /// |          |          | here, would be shifted in 2
486             /// |          | here, would be `INNERMOST` shifted in by 1
487             /// | here, initially, binder would be `INNERMOST`
488             /// ```
489             ///
490             /// You see that, initially, *any* bound value is free,
491             /// because we've not traversed any binders. As we pass
492             /// through a binder, we shift the `outer_index` by 1 to
493             /// account for the new binder that encloses us.
494             outer_index: ty::DebruijnIndex,
495             callback: F,
496         }
497
498         impl<'tcx, F> TypeVisitor<'tcx> for RegionVisitor<F>
499         where
500             F: FnMut(ty::Region<'tcx>) -> bool,
501         {
502             type BreakTy = ();
503
504             fn visit_binder<T: TypeFoldable<'tcx>>(
505                 &mut self,
506                 t: &Binder<'tcx, T>,
507             ) -> ControlFlow<Self::BreakTy> {
508                 self.outer_index.shift_in(1);
509                 let result = t.as_ref().skip_binder().visit_with(self);
510                 self.outer_index.shift_out(1);
511                 result
512             }
513
514             fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
515                 match *r {
516                     ty::ReLateBound(debruijn, _) if debruijn < self.outer_index => {
517                         ControlFlow::CONTINUE
518                     }
519                     _ => {
520                         if (self.callback)(r) {
521                             ControlFlow::BREAK
522                         } else {
523                             ControlFlow::CONTINUE
524                         }
525                     }
526                 }
527             }
528
529             fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
530                 // We're only interested in types involving regions
531                 if ty.flags().intersects(TypeFlags::HAS_FREE_REGIONS) {
532                     ty.super_visit_with(self)
533                 } else {
534                     ControlFlow::CONTINUE
535                 }
536             }
537         }
538
539         value.visit_with(&mut RegionVisitor { outer_index: ty::INNERMOST, callback }).is_break()
540     }
541 }
542
543 /// Folds over the substructure of a type, visiting its component
544 /// types and all regions that occur *free* within it.
545 ///
546 /// That is, `Ty` can contain function or method types that bind
547 /// regions at the call site (`ReLateBound`), and occurrences of
548 /// regions (aka "lifetimes") that are bound within a type are not
549 /// visited by this folder; only regions that occur free will be
550 /// visited by `fld_r`.
551
552 pub struct RegionFolder<'a, 'tcx> {
553     tcx: TyCtxt<'tcx>,
554     skipped_regions: &'a mut bool,
555
556     /// Stores the index of a binder *just outside* the stuff we have
557     /// visited.  So this begins as INNERMOST; when we pass through a
558     /// binder, it is incremented (via `shift_in`).
559     current_index: ty::DebruijnIndex,
560
561     /// Callback invokes for each free region. The `DebruijnIndex`
562     /// points to the binder *just outside* the ones we have passed
563     /// through.
564     fold_region_fn:
565         &'a mut (dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx> + 'a),
566 }
567
568 impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
569     #[inline]
570     pub fn new(
571         tcx: TyCtxt<'tcx>,
572         skipped_regions: &'a mut bool,
573         fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
574     ) -> RegionFolder<'a, 'tcx> {
575         RegionFolder { tcx, skipped_regions, current_index: ty::INNERMOST, fold_region_fn }
576     }
577 }
578
579 impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
580     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
581         self.tcx
582     }
583
584     fn fold_binder<T: TypeFoldable<'tcx>>(
585         &mut self,
586         t: ty::Binder<'tcx, T>,
587     ) -> ty::Binder<'tcx, T> {
588         self.current_index.shift_in(1);
589         let t = t.super_fold_with(self);
590         self.current_index.shift_out(1);
591         t
592     }
593
594     #[instrument(skip(self), level = "debug")]
595     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
596         match *r {
597             ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
598                 debug!(?self.current_index, "skipped bound region");
599                 *self.skipped_regions = true;
600                 r
601             }
602             _ => {
603                 debug!(?self.current_index, "folding free region");
604                 (self.fold_region_fn)(r, self.current_index)
605             }
606         }
607     }
608 }
609
610 ///////////////////////////////////////////////////////////////////////////
611 // Bound vars replacer
612
613 /// Replaces the escaping bound vars (late bound regions or bound types) in a type.
614 struct BoundVarReplacer<'a, 'tcx> {
615     tcx: TyCtxt<'tcx>,
616
617     /// As with `RegionFolder`, represents the index of a binder *just outside*
618     /// the ones we have visited.
619     current_index: ty::DebruijnIndex,
620
621     fld_r: Option<&'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a)>,
622     fld_t: Option<&'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a)>,
623     fld_c: Option<&'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> ty::Const<'tcx> + 'a)>,
624 }
625
626 impl<'a, 'tcx> BoundVarReplacer<'a, 'tcx> {
627     fn new(
628         tcx: TyCtxt<'tcx>,
629         fld_r: Option<&'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a)>,
630         fld_t: Option<&'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a)>,
631         fld_c: Option<&'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> ty::Const<'tcx> + 'a)>,
632     ) -> Self {
633         BoundVarReplacer { tcx, current_index: ty::INNERMOST, fld_r, fld_t, fld_c }
634     }
635 }
636
637 impl<'a, 'tcx> TypeFolder<'tcx> for BoundVarReplacer<'a, 'tcx> {
638     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
639         self.tcx
640     }
641
642     fn fold_binder<T: TypeFoldable<'tcx>>(
643         &mut self,
644         t: ty::Binder<'tcx, T>,
645     ) -> ty::Binder<'tcx, T> {
646         self.current_index.shift_in(1);
647         let t = t.super_fold_with(self);
648         self.current_index.shift_out(1);
649         t
650     }
651
652     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
653         match *t.kind() {
654             ty::Bound(debruijn, bound_ty) if debruijn == self.current_index => {
655                 if let Some(fld_t) = self.fld_t.as_mut() {
656                     let ty = fld_t(bound_ty);
657                     return ty::fold::shift_vars(self.tcx, ty, self.current_index.as_u32());
658                 }
659             }
660             _ if t.has_vars_bound_at_or_above(self.current_index) => {
661                 return t.super_fold_with(self);
662             }
663             _ => {}
664         }
665         t
666     }
667
668     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
669         match *r {
670             ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
671                 if let Some(fld_r) = self.fld_r.as_mut() {
672                     let region = fld_r(br);
673                     return if let ty::ReLateBound(debruijn1, br) = *region {
674                         // If the callback returns a late-bound region,
675                         // that region should always use the INNERMOST
676                         // debruijn index. Then we adjust it to the
677                         // correct depth.
678                         assert_eq!(debruijn1, ty::INNERMOST);
679                         self.tcx.mk_region(ty::ReLateBound(debruijn, br))
680                     } else {
681                         region
682                     };
683                 }
684             }
685             _ => {}
686         }
687         r
688     }
689
690     fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
691         match ct.val() {
692             ty::ConstKind::Bound(debruijn, bound_const) if debruijn == self.current_index => {
693                 if let Some(fld_c) = self.fld_c.as_mut() {
694                     let ct = fld_c(bound_const, ct.ty());
695                     return ty::fold::shift_vars(self.tcx, ct, self.current_index.as_u32());
696                 }
697             }
698             _ if ct.has_vars_bound_at_or_above(self.current_index) => {
699                 return ct.super_fold_with(self);
700             }
701             _ => {}
702         }
703         ct
704     }
705 }
706
707 impl<'tcx> TyCtxt<'tcx> {
708     /// Replaces all regions bound by the given `Binder` with the
709     /// results returned by the closure; the closure is expected to
710     /// return a free region (relative to this binder), and hence the
711     /// binder is removed in the return type. The closure is invoked
712     /// once for each unique `BoundRegionKind`; multiple references to the
713     /// same `BoundRegionKind` will reuse the previous result. A map is
714     /// returned at the end with each bound region and the free region
715     /// that replaced it.
716     ///
717     /// This method only replaces late bound regions and the result may still
718     /// contain escaping bound types.
719     pub fn replace_late_bound_regions<T, F>(
720         self,
721         value: Binder<'tcx, T>,
722         mut fld_r: F,
723     ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
724     where
725         F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
726         T: TypeFoldable<'tcx>,
727     {
728         let mut region_map = BTreeMap::new();
729         let mut real_fld_r =
730             |br: ty::BoundRegion| *region_map.entry(br).or_insert_with(|| fld_r(br));
731         let value = value.skip_binder();
732         let value = if !value.has_escaping_bound_vars() {
733             value
734         } else {
735             let mut replacer = BoundVarReplacer::new(self, Some(&mut real_fld_r), None, None);
736             value.fold_with(&mut replacer)
737         };
738         (value, region_map)
739     }
740
741     /// Replaces all escaping bound vars. The `fld_r` closure replaces escaping
742     /// bound regions; the `fld_t` closure replaces escaping bound types and the `fld_c`
743     /// closure replaces escaping bound consts.
744     pub fn replace_escaping_bound_vars<T, F, G, H>(
745         self,
746         value: T,
747         mut fld_r: F,
748         mut fld_t: G,
749         mut fld_c: H,
750     ) -> T
751     where
752         F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
753         G: FnMut(ty::BoundTy) -> Ty<'tcx>,
754         H: FnMut(ty::BoundVar, Ty<'tcx>) -> ty::Const<'tcx>,
755         T: TypeFoldable<'tcx>,
756     {
757         if !value.has_escaping_bound_vars() {
758             value
759         } else {
760             let mut replacer =
761                 BoundVarReplacer::new(self, Some(&mut fld_r), Some(&mut fld_t), Some(&mut fld_c));
762             value.fold_with(&mut replacer)
763         }
764     }
765
766     /// Replaces all types or regions bound by the given `Binder`. The `fld_r`
767     /// closure replaces bound regions while the `fld_t` closure replaces bound
768     /// types.
769     pub fn replace_bound_vars<T, F, G, H>(
770         self,
771         value: Binder<'tcx, T>,
772         mut fld_r: F,
773         fld_t: G,
774         fld_c: H,
775     ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
776     where
777         F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
778         G: FnMut(ty::BoundTy) -> Ty<'tcx>,
779         H: FnMut(ty::BoundVar, Ty<'tcx>) -> ty::Const<'tcx>,
780         T: TypeFoldable<'tcx>,
781     {
782         let mut region_map = BTreeMap::new();
783         let real_fld_r = |br: ty::BoundRegion| *region_map.entry(br).or_insert_with(|| fld_r(br));
784         let value = self.replace_escaping_bound_vars(value.skip_binder(), real_fld_r, fld_t, fld_c);
785         (value, region_map)
786     }
787
788     /// Replaces any late-bound regions bound in `value` with
789     /// free variants attached to `all_outlive_scope`.
790     pub fn liberate_late_bound_regions<T>(
791         self,
792         all_outlive_scope: DefId,
793         value: ty::Binder<'tcx, T>,
794     ) -> T
795     where
796         T: TypeFoldable<'tcx>,
797     {
798         self.replace_late_bound_regions(value, |br| {
799             self.mk_region(ty::ReFree(ty::FreeRegion {
800                 scope: all_outlive_scope,
801                 bound_region: br.kind,
802             }))
803         })
804         .0
805     }
806
807     pub fn shift_bound_var_indices<T>(self, bound_vars: usize, value: T) -> T
808     where
809         T: TypeFoldable<'tcx>,
810     {
811         self.replace_escaping_bound_vars(
812             value,
813             |r| {
814                 self.mk_region(ty::ReLateBound(
815                     ty::INNERMOST,
816                     ty::BoundRegion {
817                         var: ty::BoundVar::from_usize(r.var.as_usize() + bound_vars),
818                         kind: r.kind,
819                     },
820                 ))
821             },
822             |t| {
823                 self.mk_ty(ty::Bound(
824                     ty::INNERMOST,
825                     ty::BoundTy {
826                         var: ty::BoundVar::from_usize(t.var.as_usize() + bound_vars),
827                         kind: t.kind,
828                     },
829                 ))
830             },
831             |c, ty| {
832                 self.mk_const(ty::ConstS {
833                     val: ty::ConstKind::Bound(
834                         ty::INNERMOST,
835                         ty::BoundVar::from_usize(c.as_usize() + bound_vars),
836                     ),
837                     ty,
838                 })
839             },
840         )
841     }
842
843     /// Returns a set of all late-bound regions that are constrained
844     /// by `value`, meaning that if we instantiate those LBR with
845     /// variables and equate `value` with something else, those
846     /// variables will also be equated.
847     pub fn collect_constrained_late_bound_regions<T>(
848         self,
849         value: &Binder<'tcx, T>,
850     ) -> FxHashSet<ty::BoundRegionKind>
851     where
852         T: TypeFoldable<'tcx>,
853     {
854         self.collect_late_bound_regions(value, true)
855     }
856
857     /// Returns a set of all late-bound regions that appear in `value` anywhere.
858     pub fn collect_referenced_late_bound_regions<T>(
859         self,
860         value: &Binder<'tcx, T>,
861     ) -> FxHashSet<ty::BoundRegionKind>
862     where
863         T: TypeFoldable<'tcx>,
864     {
865         self.collect_late_bound_regions(value, false)
866     }
867
868     fn collect_late_bound_regions<T>(
869         self,
870         value: &Binder<'tcx, T>,
871         just_constraint: bool,
872     ) -> FxHashSet<ty::BoundRegionKind>
873     where
874         T: TypeFoldable<'tcx>,
875     {
876         let mut collector = LateBoundRegionsCollector::new(just_constraint);
877         let result = value.as_ref().skip_binder().visit_with(&mut collector);
878         assert!(result.is_continue()); // should never have stopped early
879         collector.regions
880     }
881
882     /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
883     /// method lookup and a few other places where precise region relationships are not required.
884     pub fn erase_late_bound_regions<T>(self, value: Binder<'tcx, T>) -> T
885     where
886         T: TypeFoldable<'tcx>,
887     {
888         self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
889     }
890
891     /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
892     /// assigned starting at 0 and increasing monotonically in the order traversed
893     /// by the fold operation.
894     ///
895     /// The chief purpose of this function is to canonicalize regions so that two
896     /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
897     /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
898     /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
899     pub fn anonymize_late_bound_regions<T>(self, sig: Binder<'tcx, T>) -> Binder<'tcx, T>
900     where
901         T: TypeFoldable<'tcx>,
902     {
903         let mut counter = 0;
904         let inner = self
905             .replace_late_bound_regions(sig, |_| {
906                 let br = ty::BoundRegion {
907                     var: ty::BoundVar::from_u32(counter),
908                     kind: ty::BrAnon(counter),
909                 };
910                 let r = self.mk_region(ty::ReLateBound(ty::INNERMOST, br));
911                 counter += 1;
912                 r
913             })
914             .0;
915         let bound_vars = self.mk_bound_variable_kinds(
916             (0..counter).map(|i| ty::BoundVariableKind::Region(ty::BrAnon(i))),
917         );
918         Binder::bind_with_vars(inner, bound_vars)
919     }
920 }
921
922 pub struct ValidateBoundVars<'tcx> {
923     bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
924     binder_index: ty::DebruijnIndex,
925     // We may encounter the same variable at different levels of binding, so
926     // this can't just be `Ty`
927     visited: SsoHashSet<(ty::DebruijnIndex, Ty<'tcx>)>,
928 }
929
930 impl<'tcx> ValidateBoundVars<'tcx> {
931     pub fn new(bound_vars: &'tcx ty::List<ty::BoundVariableKind>) -> Self {
932         ValidateBoundVars {
933             bound_vars,
934             binder_index: ty::INNERMOST,
935             visited: SsoHashSet::default(),
936         }
937     }
938 }
939
940 impl<'tcx> TypeVisitor<'tcx> for ValidateBoundVars<'tcx> {
941     type BreakTy = ();
942
943     fn visit_binder<T: TypeFoldable<'tcx>>(
944         &mut self,
945         t: &Binder<'tcx, T>,
946     ) -> ControlFlow<Self::BreakTy> {
947         self.binder_index.shift_in(1);
948         let result = t.super_visit_with(self);
949         self.binder_index.shift_out(1);
950         result
951     }
952
953     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
954         if t.outer_exclusive_binder() < self.binder_index
955             || !self.visited.insert((self.binder_index, t))
956         {
957             return ControlFlow::BREAK;
958         }
959         match *t.kind() {
960             ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => {
961                 if self.bound_vars.len() <= bound_ty.var.as_usize() {
962                     bug!("Not enough bound vars: {:?} not found in {:?}", t, self.bound_vars);
963                 }
964                 let list_var = self.bound_vars[bound_ty.var.as_usize()];
965                 match list_var {
966                     ty::BoundVariableKind::Ty(kind) => {
967                         if kind != bound_ty.kind {
968                             bug!(
969                                 "Mismatched type kinds: {:?} doesn't var in list {:?}",
970                                 bound_ty.kind,
971                                 list_var
972                             );
973                         }
974                     }
975                     _ => {
976                         bug!("Mismatched bound variable kinds! Expected type, found {:?}", list_var)
977                     }
978                 }
979             }
980
981             _ => (),
982         };
983
984         t.super_visit_with(self)
985     }
986
987     fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
988         match *r {
989             ty::ReLateBound(index, br) if index == self.binder_index => {
990                 if self.bound_vars.len() <= br.var.as_usize() {
991                     bug!("Not enough bound vars: {:?} not found in {:?}", br, self.bound_vars);
992                 }
993                 let list_var = self.bound_vars[br.var.as_usize()];
994                 match list_var {
995                     ty::BoundVariableKind::Region(kind) => {
996                         if kind != br.kind {
997                             bug!(
998                                 "Mismatched region kinds: {:?} doesn't match var ({:?}) in list ({:?})",
999                                 br.kind,
1000                                 list_var,
1001                                 self.bound_vars
1002                             );
1003                         }
1004                     }
1005                     _ => bug!(
1006                         "Mismatched bound variable kinds! Expected region, found {:?}",
1007                         list_var
1008                     ),
1009                 }
1010             }
1011
1012             _ => (),
1013         };
1014
1015         r.super_visit_with(self)
1016     }
1017 }
1018
1019 ///////////////////////////////////////////////////////////////////////////
1020 // Shifter
1021 //
1022 // Shifts the De Bruijn indices on all escaping bound vars by a
1023 // fixed amount. Useful in substitution or when otherwise introducing
1024 // a binding level that is not intended to capture the existing bound
1025 // vars. See comment on `shift_vars_through_binders` method in
1026 // `subst.rs` for more details.
1027
1028 struct Shifter<'tcx> {
1029     tcx: TyCtxt<'tcx>,
1030     current_index: ty::DebruijnIndex,
1031     amount: u32,
1032 }
1033
1034 impl<'tcx> Shifter<'tcx> {
1035     pub fn new(tcx: TyCtxt<'tcx>, amount: u32) -> Self {
1036         Shifter { tcx, current_index: ty::INNERMOST, amount }
1037     }
1038 }
1039
1040 impl<'tcx> TypeFolder<'tcx> for Shifter<'tcx> {
1041     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1042         self.tcx
1043     }
1044
1045     fn fold_binder<T: TypeFoldable<'tcx>>(
1046         &mut self,
1047         t: ty::Binder<'tcx, T>,
1048     ) -> ty::Binder<'tcx, T> {
1049         self.current_index.shift_in(1);
1050         let t = t.super_fold_with(self);
1051         self.current_index.shift_out(1);
1052         t
1053     }
1054
1055     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
1056         match *r {
1057             ty::ReLateBound(debruijn, br) => {
1058                 if self.amount == 0 || debruijn < self.current_index {
1059                     r
1060                 } else {
1061                     let debruijn = debruijn.shifted_in(self.amount);
1062                     let shifted = ty::ReLateBound(debruijn, br);
1063                     self.tcx.mk_region(shifted)
1064                 }
1065             }
1066             _ => r,
1067         }
1068     }
1069
1070     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1071         match *ty.kind() {
1072             ty::Bound(debruijn, bound_ty) => {
1073                 if self.amount == 0 || debruijn < self.current_index {
1074                     ty
1075                 } else {
1076                     let debruijn = debruijn.shifted_in(self.amount);
1077                     self.tcx.mk_ty(ty::Bound(debruijn, bound_ty))
1078                 }
1079             }
1080
1081             _ => ty.super_fold_with(self),
1082         }
1083     }
1084
1085     fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1086         if let ty::ConstKind::Bound(debruijn, bound_ct) = ct.val() {
1087             if self.amount == 0 || debruijn < self.current_index {
1088                 ct
1089             } else {
1090                 let debruijn = debruijn.shifted_in(self.amount);
1091                 self.tcx.mk_const(ty::ConstS {
1092                     val: ty::ConstKind::Bound(debruijn, bound_ct),
1093                     ty: ct.ty(),
1094                 })
1095             }
1096         } else {
1097             ct.super_fold_with(self)
1098         }
1099     }
1100 }
1101
1102 pub fn shift_region<'tcx>(
1103     tcx: TyCtxt<'tcx>,
1104     region: ty::Region<'tcx>,
1105     amount: u32,
1106 ) -> ty::Region<'tcx> {
1107     match *region {
1108         ty::ReLateBound(debruijn, br) if amount > 0 => {
1109             tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), br))
1110         }
1111         _ => region,
1112     }
1113 }
1114
1115 pub fn shift_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: T, amount: u32) -> T
1116 where
1117     T: TypeFoldable<'tcx>,
1118 {
1119     debug!("shift_vars(value={:?}, amount={})", value, amount);
1120
1121     value.fold_with(&mut Shifter::new(tcx, amount))
1122 }
1123
1124 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
1125 struct FoundEscapingVars;
1126
1127 /// An "escaping var" is a bound var whose binder is not part of `t`. A bound var can be a
1128 /// bound region or a bound type.
1129 ///
1130 /// So, for example, consider a type like the following, which has two binders:
1131 ///
1132 ///    for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
1133 ///    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
1134 ///                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~  inner scope
1135 ///
1136 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
1137 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
1138 /// fn type*, that type has an escaping region: `'a`.
1139 ///
1140 /// Note that what I'm calling an "escaping var" is often just called a "free var". However,
1141 /// we already use the term "free var". It refers to the regions or types that we use to represent
1142 /// bound regions or type params on a fn definition while we are type checking its body.
1143 ///
1144 /// To clarify, conceptually there is no particular difference between
1145 /// an "escaping" var and a "free" var. However, there is a big
1146 /// difference in practice. Basically, when "entering" a binding
1147 /// level, one is generally required to do some sort of processing to
1148 /// a bound var, such as replacing it with a fresh/placeholder
1149 /// var, or making an entry in the environment to represent the
1150 /// scope to which it is attached, etc. An escaping var represents
1151 /// a bound var for which this processing has not yet been done.
1152 struct HasEscapingVarsVisitor {
1153     /// Anything bound by `outer_index` or "above" is escaping.
1154     outer_index: ty::DebruijnIndex,
1155 }
1156
1157 impl<'tcx> TypeVisitor<'tcx> for HasEscapingVarsVisitor {
1158     type BreakTy = FoundEscapingVars;
1159
1160     fn visit_binder<T: TypeFoldable<'tcx>>(
1161         &mut self,
1162         t: &Binder<'tcx, T>,
1163     ) -> ControlFlow<Self::BreakTy> {
1164         self.outer_index.shift_in(1);
1165         let result = t.super_visit_with(self);
1166         self.outer_index.shift_out(1);
1167         result
1168     }
1169
1170     #[inline]
1171     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1172         // If the outer-exclusive-binder is *strictly greater* than
1173         // `outer_index`, that means that `t` contains some content
1174         // bound at `outer_index` or above (because
1175         // `outer_exclusive_binder` is always 1 higher than the
1176         // content in `t`). Therefore, `t` has some escaping vars.
1177         if t.outer_exclusive_binder() > self.outer_index {
1178             ControlFlow::Break(FoundEscapingVars)
1179         } else {
1180             ControlFlow::CONTINUE
1181         }
1182     }
1183
1184     #[inline]
1185     fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1186         // If the region is bound by `outer_index` or anything outside
1187         // of outer index, then it escapes the binders we have
1188         // visited.
1189         if r.bound_at_or_above_binder(self.outer_index) {
1190             ControlFlow::Break(FoundEscapingVars)
1191         } else {
1192             ControlFlow::CONTINUE
1193         }
1194     }
1195
1196     fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1197         // we don't have a `visit_infer_const` callback, so we have to
1198         // hook in here to catch this case (annoying...), but
1199         // otherwise we do want to remember to visit the rest of the
1200         // const, as it has types/regions embedded in a lot of other
1201         // places.
1202         match ct.val() {
1203             ty::ConstKind::Bound(debruijn, _) if debruijn >= self.outer_index => {
1204                 ControlFlow::Break(FoundEscapingVars)
1205             }
1206             _ => ct.super_visit_with(self),
1207         }
1208     }
1209
1210     #[inline]
1211     fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
1212         if predicate.outer_exclusive_binder() > self.outer_index {
1213             ControlFlow::Break(FoundEscapingVars)
1214         } else {
1215             ControlFlow::CONTINUE
1216         }
1217     }
1218 }
1219
1220 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
1221 struct FoundFlags;
1222
1223 // FIXME: Optimize for checking for infer flags
1224 struct HasTypeFlagsVisitor {
1225     flags: ty::TypeFlags,
1226 }
1227
1228 impl std::fmt::Debug for HasTypeFlagsVisitor {
1229     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1230         self.flags.fmt(fmt)
1231     }
1232 }
1233
1234 impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor {
1235     type BreakTy = FoundFlags;
1236
1237     #[inline]
1238     #[instrument(level = "trace")]
1239     fn visit_ty(&mut self, t: Ty<'_>) -> ControlFlow<Self::BreakTy> {
1240         debug!(
1241             "HasTypeFlagsVisitor: t={:?} t.flags={:?} self.flags={:?}",
1242             t,
1243             t.flags(),
1244             self.flags
1245         );
1246         if t.flags().intersects(self.flags) {
1247             ControlFlow::Break(FoundFlags)
1248         } else {
1249             ControlFlow::CONTINUE
1250         }
1251     }
1252
1253     #[inline]
1254     #[instrument(skip(self), level = "trace")]
1255     fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1256         let flags = r.type_flags();
1257         trace!(r.flags=?flags);
1258         if flags.intersects(self.flags) {
1259             ControlFlow::Break(FoundFlags)
1260         } else {
1261             ControlFlow::CONTINUE
1262         }
1263     }
1264
1265     #[inline]
1266     #[instrument(level = "trace")]
1267     fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1268         let flags = FlagComputation::for_const(c);
1269         trace!(r.flags=?flags);
1270         if flags.intersects(self.flags) {
1271             ControlFlow::Break(FoundFlags)
1272         } else {
1273             ControlFlow::CONTINUE
1274         }
1275     }
1276
1277     #[inline]
1278     #[instrument(level = "trace")]
1279     fn visit_unevaluated_const(&mut self, uv: ty::Unevaluated<'tcx>) -> ControlFlow<Self::BreakTy> {
1280         let flags = FlagComputation::for_unevaluated_const(uv);
1281         trace!(r.flags=?flags);
1282         if flags.intersects(self.flags) {
1283             ControlFlow::Break(FoundFlags)
1284         } else {
1285             ControlFlow::CONTINUE
1286         }
1287     }
1288
1289     #[inline]
1290     #[instrument(level = "trace")]
1291     fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
1292         debug!(
1293             "HasTypeFlagsVisitor: predicate={:?} predicate.flags={:?} self.flags={:?}",
1294             predicate,
1295             predicate.flags(),
1296             self.flags
1297         );
1298         if predicate.flags().intersects(self.flags) {
1299             ControlFlow::Break(FoundFlags)
1300         } else {
1301             ControlFlow::CONTINUE
1302         }
1303     }
1304 }
1305
1306 /// Collects all the late-bound regions at the innermost binding level
1307 /// into a hash set.
1308 struct LateBoundRegionsCollector {
1309     current_index: ty::DebruijnIndex,
1310     regions: FxHashSet<ty::BoundRegionKind>,
1311
1312     /// `true` if we only want regions that are known to be
1313     /// "constrained" when you equate this type with another type. In
1314     /// particular, if you have e.g., `&'a u32` and `&'b u32`, equating
1315     /// them constraints `'a == 'b`. But if you have `<&'a u32 as
1316     /// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those
1317     /// types may mean that `'a` and `'b` don't appear in the results,
1318     /// so they are not considered *constrained*.
1319     just_constrained: bool,
1320 }
1321
1322 impl LateBoundRegionsCollector {
1323     fn new(just_constrained: bool) -> Self {
1324         LateBoundRegionsCollector {
1325             current_index: ty::INNERMOST,
1326             regions: Default::default(),
1327             just_constrained,
1328         }
1329     }
1330 }
1331
1332 impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector {
1333     fn visit_binder<T: TypeFoldable<'tcx>>(
1334         &mut self,
1335         t: &Binder<'tcx, T>,
1336     ) -> ControlFlow<Self::BreakTy> {
1337         self.current_index.shift_in(1);
1338         let result = t.super_visit_with(self);
1339         self.current_index.shift_out(1);
1340         result
1341     }
1342
1343     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1344         // if we are only looking for "constrained" region, we have to
1345         // ignore the inputs to a projection, as they may not appear
1346         // in the normalized form
1347         if self.just_constrained {
1348             if let ty::Projection(..) | ty::Opaque(..) = t.kind() {
1349                 return ControlFlow::CONTINUE;
1350             }
1351         }
1352
1353         t.super_visit_with(self)
1354     }
1355
1356     fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1357         // if we are only looking for "constrained" region, we have to
1358         // ignore the inputs of an unevaluated const, as they may not appear
1359         // in the normalized form
1360         if self.just_constrained {
1361             if let ty::ConstKind::Unevaluated(..) = c.val() {
1362                 return ControlFlow::CONTINUE;
1363             }
1364         }
1365
1366         c.super_visit_with(self)
1367     }
1368
1369     fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1370         if let ty::ReLateBound(debruijn, br) = *r {
1371             if debruijn == self.current_index {
1372                 self.regions.insert(br.kind);
1373             }
1374         }
1375         ControlFlow::CONTINUE
1376     }
1377 }