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