]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/fold.rs
cb46a9dba579fd6d40a75e0b835cba021d2a7661
[rust.git] / compiler / rustc_middle / src / ty / fold.rs
1 //! A folding traversal mechanism for complex data structures that contain type
2 //! information.
3 //!
4 //! This is a modifying traversal. It consumes the data structure, producing a
5 //! (possibly) modified version of it. Both fallible and infallible versions are
6 //! available. The name is potentially confusing, because this traversal is more
7 //! like `Iterator::map` than `Iterator::fold`.
8 //!
9 //! This traversal has limited flexibility. Only a small number of "types of
10 //! interest" within the complex data structures can receive custom
11 //! modification. These are the ones containing the most important type-related
12 //! information, such as `Ty`, `Predicate`, `Region`, and `Const`.
13 //!
14 //! There are three groups of traits involved in each traversal.
15 //! - `TypeFoldable`. This is implemented once for many types, including:
16 //!   - Types of interest, for which the the methods delegate to the
17 //!     folder.
18 //!   - All other types, including generic containers like `Vec` and `Option`.
19 //!     It defines a "skeleton" of how they should be folded.
20 //! - `TypeSuperFoldable`. This is implemented only for each type of interest,
21 //!   and defines the folding "skeleton" for these types.
22 //! - `TypeFolder`/`FallibleTypeFolder. One of these is implemented for each
23 //!   folder. This defines how types of interest are folded.
24 //!
25 //! This means each fold is a mixture of (a) generic folding operations, and (b)
26 //! custom fold operations that are specific to the folder.
27 //! - The `TypeFoldable` impls handle most of the traversal, and call into
28 //!   `TypeFolder`/`FallibleTypeFolder` when they encounter a type of interest.
29 //! - A `TypeFolder`/`FallibleTypeFolder` may call into another `TypeFoldable`
30 //!   impl, because some of the types of interest are recursive and can contain
31 //!   other types of interest.
32 //! - A `TypeFolder`/`FallibleTypeFolder` may also call into a `TypeSuperFoldable`
33 //!   impl, because each folder might provide custom handling only for some types
34 //!   of interest, or only for some variants of each type of interest, and then
35 //!   use default traversal for the remaining cases.
36 //!
37 //! For example, if you have `struct S(Ty, U)` where `S: TypeFoldable` and `U:
38 //! TypeFoldable`, and an instance `s = S(ty, u)`, it would be folded like so:
39 //! ```text
40 //! s.fold_with(folder) calls
41 //! - ty.fold_with(folder) calls
42 //!   - folder.fold_ty(ty) may call
43 //!     - ty.super_fold_with(folder)
44 //! - u.fold_with(folder)
45 //! ```
46 use crate::mir;
47 use crate::ty::{self, Binder, BoundTy, Ty, TyCtxt, TypeVisitable};
48 use rustc_data_structures::fx::FxIndexMap;
49 use rustc_hir::def_id::DefId;
50
51 use std::collections::BTreeMap;
52
53 /// This trait is implemented for every type that can be folded,
54 /// providing the skeleton of the traversal.
55 ///
56 /// To implement this conveniently, use the derive macro located in
57 /// `rustc_macros`.
58 pub trait TypeFoldable<'tcx>: TypeVisitable<'tcx> {
59     /// The entry point for folding. To fold a value `t` with a folder `f`
60     /// call: `t.try_fold_with(f)`.
61     ///
62     /// For most types, this just traverses the value, calling `try_fold_with`
63     /// on each field/element.
64     ///
65     /// For types of interest (such as `Ty`), the implementation of method
66     /// calls a folder method specifically for that type (such as
67     /// `F::try_fold_ty`). This is where control transfers from `TypeFoldable`
68     /// to `TypeFolder`.
69     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error>;
70
71     /// A convenient alternative to `try_fold_with` for use with infallible
72     /// folders. Do not override this method, to ensure coherence with
73     /// `try_fold_with`.
74     fn fold_with<F: TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
75         self.try_fold_with(folder).into_ok()
76     }
77 }
78
79 // This trait is implemented for types of interest.
80 pub trait TypeSuperFoldable<'tcx>: TypeFoldable<'tcx> {
81     /// Provides a default fold for a type of interest. This should only be
82     /// called within `TypeFolder` methods, when a non-custom traversal is
83     /// desired for the value of the type of interest passed to that method.
84     /// For example, in `MyFolder::try_fold_ty(ty)`, it is valid to call
85     /// `ty.try_super_fold_with(self)`, but any other folding should be done
86     /// with `xyz.try_fold_with(self)`.
87     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
88         self,
89         folder: &mut F,
90     ) -> Result<Self, F::Error>;
91
92     /// A convenient alternative to `try_super_fold_with` for use with
93     /// infallible folders. Do not override this method, to ensure coherence
94     /// with `try_super_fold_with`.
95     fn super_fold_with<F: TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
96         self.try_super_fold_with(folder).into_ok()
97     }
98 }
99
100 /// This trait is implemented for every infallible folding traversal. There is
101 /// a fold method defined for every type of interest. Each such method has a
102 /// default that does an "identity" fold. Implementations of these methods
103 /// often fall back to a `super_fold_with` method if the primary argument
104 /// doesn't satisfy a particular condition.
105 ///
106 /// A blanket implementation of [`FallibleTypeFolder`] will defer to
107 /// the infallible methods of this trait to ensure that the two APIs
108 /// are coherent.
109 pub trait TypeFolder<'tcx>: FallibleTypeFolder<'tcx, Error = !> {
110     fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
111
112     fn fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Binder<'tcx, T>
113     where
114         T: TypeFoldable<'tcx>,
115     {
116         t.super_fold_with(self)
117     }
118
119     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
120         t.super_fold_with(self)
121     }
122
123     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
124         r.super_fold_with(self)
125     }
126
127     fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
128         c.super_fold_with(self)
129     }
130
131     fn fold_unevaluated(&mut self, uv: ty::Unevaluated<'tcx>) -> ty::Unevaluated<'tcx> {
132         uv.super_fold_with(self)
133     }
134
135     fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
136         p.super_fold_with(self)
137     }
138
139     fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx> {
140         bug!("most type folders should not be folding MIR datastructures: {:?}", c)
141     }
142 }
143
144 /// This trait is implemented for every folding traversal. There is a fold
145 /// method defined for every type of interest. Each such method has a default
146 /// that does an "identity" fold.
147 ///
148 /// A blanket implementation of this trait (that defers to the relevant
149 /// method of [`TypeFolder`]) is provided for all infallible folders in
150 /// order to ensure the two APIs are coherent.
151 pub trait FallibleTypeFolder<'tcx>: Sized {
152     type Error;
153
154     fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
155
156     fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, Self::Error>
157     where
158         T: TypeFoldable<'tcx>,
159     {
160         t.try_super_fold_with(self)
161     }
162
163     fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
164         t.try_super_fold_with(self)
165     }
166
167     fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
168         r.try_super_fold_with(self)
169     }
170
171     fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, Self::Error> {
172         c.try_super_fold_with(self)
173     }
174
175     fn try_fold_unevaluated(
176         &mut self,
177         c: ty::Unevaluated<'tcx>,
178     ) -> Result<ty::Unevaluated<'tcx>, Self::Error> {
179         c.try_super_fold_with(self)
180     }
181
182     fn try_fold_predicate(
183         &mut self,
184         p: ty::Predicate<'tcx>,
185     ) -> Result<ty::Predicate<'tcx>, Self::Error> {
186         p.try_super_fold_with(self)
187     }
188
189     fn try_fold_mir_const(
190         &mut self,
191         c: mir::ConstantKind<'tcx>,
192     ) -> Result<mir::ConstantKind<'tcx>, Self::Error> {
193         bug!("most type folders should not be folding MIR datastructures: {:?}", c)
194     }
195 }
196
197 // This blanket implementation of the fallible trait for infallible folders
198 // delegates to infallible methods to ensure coherence.
199 impl<'tcx, F> FallibleTypeFolder<'tcx> for F
200 where
201     F: TypeFolder<'tcx>,
202 {
203     type Error = !;
204
205     fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
206         TypeFolder::tcx(self)
207     }
208
209     fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, !>
210     where
211         T: TypeFoldable<'tcx>,
212     {
213         Ok(self.fold_binder(t))
214     }
215
216     fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, !> {
217         Ok(self.fold_ty(t))
218     }
219
220     fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, !> {
221         Ok(self.fold_region(r))
222     }
223
224     fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, !> {
225         Ok(self.fold_const(c))
226     }
227
228     fn try_fold_unevaluated(
229         &mut self,
230         c: ty::Unevaluated<'tcx>,
231     ) -> Result<ty::Unevaluated<'tcx>, !> {
232         Ok(self.fold_unevaluated(c))
233     }
234
235     fn try_fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> Result<ty::Predicate<'tcx>, !> {
236         Ok(self.fold_predicate(p))
237     }
238
239     fn try_fold_mir_const(
240         &mut self,
241         c: mir::ConstantKind<'tcx>,
242     ) -> Result<mir::ConstantKind<'tcx>, !> {
243         Ok(self.fold_mir_const(c))
244     }
245 }
246
247 ///////////////////////////////////////////////////////////////////////////
248 // Some sample folders
249
250 pub struct BottomUpFolder<'tcx, F, G, H>
251 where
252     F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
253     G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
254     H: FnMut(ty::Const<'tcx>) -> ty::Const<'tcx>,
255 {
256     pub tcx: TyCtxt<'tcx>,
257     pub ty_op: F,
258     pub lt_op: G,
259     pub ct_op: H,
260 }
261
262 impl<'tcx, F, G, H> TypeFolder<'tcx> for BottomUpFolder<'tcx, F, G, H>
263 where
264     F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
265     G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
266     H: FnMut(ty::Const<'tcx>) -> ty::Const<'tcx>,
267 {
268     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
269         self.tcx
270     }
271
272     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
273         let t = ty.super_fold_with(self);
274         (self.ty_op)(t)
275     }
276
277     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
278         let r = r.super_fold_with(self);
279         (self.lt_op)(r)
280     }
281
282     fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
283         let ct = ct.super_fold_with(self);
284         (self.ct_op)(ct)
285     }
286 }
287
288 ///////////////////////////////////////////////////////////////////////////
289 // Region folder
290
291 impl<'tcx> TyCtxt<'tcx> {
292     /// Folds the escaping and free regions in `value` using `f`, and
293     /// sets `skipped_regions` to true if any late-bound region was found
294     /// and skipped.
295     pub fn fold_regions<T>(
296         self,
297         value: T,
298         mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
299     ) -> T
300     where
301         T: TypeFoldable<'tcx>,
302     {
303         value.fold_with(&mut RegionFolder::new(self, &mut f))
304     }
305 }
306
307 /// Folds over the substructure of a type, visiting its component
308 /// types and all regions that occur *free* within it.
309 ///
310 /// That is, `Ty` can contain function or method types that bind
311 /// regions at the call site (`ReLateBound`), and occurrences of
312 /// regions (aka "lifetimes") that are bound within a type are not
313 /// visited by this folder; only regions that occur free will be
314 /// visited by `fld_r`.
315
316 pub struct RegionFolder<'a, 'tcx> {
317     tcx: TyCtxt<'tcx>,
318
319     /// Stores the index of a binder *just outside* the stuff we have
320     /// visited.  So this begins as INNERMOST; when we pass through a
321     /// binder, it is incremented (via `shift_in`).
322     current_index: ty::DebruijnIndex,
323
324     /// Callback invokes for each free region. The `DebruijnIndex`
325     /// points to the binder *just outside* the ones we have passed
326     /// through.
327     fold_region_fn:
328         &'a mut (dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx> + 'a),
329 }
330
331 impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
332     #[inline]
333     pub fn new(
334         tcx: TyCtxt<'tcx>,
335         fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
336     ) -> RegionFolder<'a, 'tcx> {
337         RegionFolder { tcx, current_index: ty::INNERMOST, fold_region_fn }
338     }
339 }
340
341 impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
342     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
343         self.tcx
344     }
345
346     fn fold_binder<T: TypeFoldable<'tcx>>(
347         &mut self,
348         t: ty::Binder<'tcx, T>,
349     ) -> ty::Binder<'tcx, T> {
350         self.current_index.shift_in(1);
351         let t = t.super_fold_with(self);
352         self.current_index.shift_out(1);
353         t
354     }
355
356     #[instrument(skip(self), level = "debug", ret)]
357     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
358         match *r {
359             ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
360                 debug!(?self.current_index, "skipped bound region");
361                 r
362             }
363             _ => {
364                 debug!(?self.current_index, "folding free region");
365                 (self.fold_region_fn)(r, self.current_index)
366             }
367         }
368     }
369 }
370
371 ///////////////////////////////////////////////////////////////////////////
372 // Bound vars replacer
373
374 pub trait BoundVarReplacerDelegate<'tcx> {
375     fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx>;
376     fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx>;
377     fn replace_const(&mut self, bv: ty::BoundVar, ty: Ty<'tcx>) -> ty::Const<'tcx>;
378 }
379
380 pub struct FnMutDelegate<R, T, C> {
381     pub regions: R,
382     pub types: T,
383     pub consts: C,
384 }
385 impl<'tcx, R, T, C> BoundVarReplacerDelegate<'tcx> for FnMutDelegate<R, T, C>
386 where
387     R: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
388     T: FnMut(ty::BoundTy) -> Ty<'tcx>,
389     C: FnMut(ty::BoundVar, Ty<'tcx>) -> ty::Const<'tcx>,
390 {
391     fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
392         (self.regions)(br)
393     }
394     fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
395         (self.types)(bt)
396     }
397     fn replace_const(&mut self, bv: ty::BoundVar, ty: Ty<'tcx>) -> ty::Const<'tcx> {
398         (self.consts)(bv, ty)
399     }
400 }
401
402 /// Replaces the escaping bound vars (late bound regions or bound types) in a type.
403 struct BoundVarReplacer<'tcx, D> {
404     tcx: TyCtxt<'tcx>,
405
406     /// As with `RegionFolder`, represents the index of a binder *just outside*
407     /// the ones we have visited.
408     current_index: ty::DebruijnIndex,
409
410     delegate: D,
411 }
412
413 impl<'tcx, D: BoundVarReplacerDelegate<'tcx>> BoundVarReplacer<'tcx, D> {
414     fn new(tcx: TyCtxt<'tcx>, delegate: D) -> Self {
415         BoundVarReplacer { tcx, current_index: ty::INNERMOST, delegate }
416     }
417 }
418
419 impl<'tcx, D> TypeFolder<'tcx> for BoundVarReplacer<'tcx, D>
420 where
421     D: BoundVarReplacerDelegate<'tcx>,
422 {
423     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
424         self.tcx
425     }
426
427     fn fold_binder<T: TypeFoldable<'tcx>>(
428         &mut self,
429         t: ty::Binder<'tcx, T>,
430     ) -> ty::Binder<'tcx, T> {
431         self.current_index.shift_in(1);
432         let t = t.super_fold_with(self);
433         self.current_index.shift_out(1);
434         t
435     }
436
437     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
438         match *t.kind() {
439             ty::Bound(debruijn, bound_ty) if debruijn == self.current_index => {
440                 let ty = self.delegate.replace_ty(bound_ty);
441                 ty::fold::shift_vars(self.tcx, ty, self.current_index.as_u32())
442             }
443             _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
444             _ => t,
445         }
446     }
447
448     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
449         match *r {
450             ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
451                 let region = self.delegate.replace_region(br);
452                 if let ty::ReLateBound(debruijn1, br) = *region {
453                     // If the callback returns a late-bound region,
454                     // that region should always use the INNERMOST
455                     // debruijn index. Then we adjust it to the
456                     // correct depth.
457                     assert_eq!(debruijn1, ty::INNERMOST);
458                     self.tcx.reuse_or_mk_region(region, ty::ReLateBound(debruijn, br))
459                 } else {
460                     region
461                 }
462             }
463             _ => r,
464         }
465     }
466
467     fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
468         match ct.kind() {
469             ty::ConstKind::Bound(debruijn, bound_const) if debruijn == self.current_index => {
470                 let ct = self.delegate.replace_const(bound_const, ct.ty());
471                 ty::fold::shift_vars(self.tcx, ct, self.current_index.as_u32())
472             }
473             _ => ct.super_fold_with(self),
474         }
475     }
476
477     fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
478         if p.has_vars_bound_at_or_above(self.current_index) { p.super_fold_with(self) } else { p }
479     }
480 }
481
482 impl<'tcx> TyCtxt<'tcx> {
483     /// Replaces all regions bound by the given `Binder` with the
484     /// results returned by the closure; the closure is expected to
485     /// return a free region (relative to this binder), and hence the
486     /// binder is removed in the return type. The closure is invoked
487     /// once for each unique `BoundRegionKind`; multiple references to the
488     /// same `BoundRegionKind` will reuse the previous result. A map is
489     /// returned at the end with each bound region and the free region
490     /// that replaced it.
491     ///
492     /// # Panics
493     ///
494     /// This method only replaces late bound regions. Any types or
495     /// constants bound by `value` will cause an ICE.
496     pub fn replace_late_bound_regions<T, F>(
497         self,
498         value: Binder<'tcx, T>,
499         mut fld_r: F,
500     ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
501     where
502         F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
503         T: TypeFoldable<'tcx>,
504     {
505         let mut region_map = BTreeMap::new();
506         let real_fld_r = |br: ty::BoundRegion| *region_map.entry(br).or_insert_with(|| fld_r(br));
507         let value = self.replace_late_bound_regions_uncached(value, real_fld_r);
508         (value, region_map)
509     }
510
511     pub fn replace_late_bound_regions_uncached<T, F>(
512         self,
513         value: Binder<'tcx, T>,
514         replace_regions: F,
515     ) -> T
516     where
517         F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
518         T: TypeFoldable<'tcx>,
519     {
520         let value = value.skip_binder();
521         if !value.has_escaping_bound_vars() {
522             value
523         } else {
524             let delegate = FnMutDelegate {
525                 regions: replace_regions,
526                 types: |b| bug!("unexpected bound ty in binder: {b:?}"),
527                 consts: |b, ty| bug!("unexpected bound ct in binder: {b:?} {ty}"),
528             };
529             let mut replacer = BoundVarReplacer::new(self, delegate);
530             value.fold_with(&mut replacer)
531         }
532     }
533
534     /// Replaces all escaping bound vars. The `fld_r` closure replaces escaping
535     /// bound regions; the `fld_t` closure replaces escaping bound types and the `fld_c`
536     /// closure replaces escaping bound consts.
537     pub fn replace_escaping_bound_vars_uncached<T: TypeFoldable<'tcx>>(
538         self,
539         value: T,
540         delegate: impl BoundVarReplacerDelegate<'tcx>,
541     ) -> T {
542         if !value.has_escaping_bound_vars() {
543             value
544         } else {
545             let mut replacer = BoundVarReplacer::new(self, delegate);
546             value.fold_with(&mut replacer)
547         }
548     }
549
550     /// Replaces all types or regions bound by the given `Binder`. The `fld_r`
551     /// closure replaces bound regions, the `fld_t` closure replaces bound
552     /// types, and `fld_c` replaces bound constants.
553     pub fn replace_bound_vars_uncached<T: TypeFoldable<'tcx>>(
554         self,
555         value: Binder<'tcx, T>,
556         delegate: impl BoundVarReplacerDelegate<'tcx>,
557     ) -> T {
558         self.replace_escaping_bound_vars_uncached(value.skip_binder(), delegate)
559     }
560
561     /// Replaces any late-bound regions bound in `value` with
562     /// free variants attached to `all_outlive_scope`.
563     pub fn liberate_late_bound_regions<T>(
564         self,
565         all_outlive_scope: DefId,
566         value: ty::Binder<'tcx, T>,
567     ) -> T
568     where
569         T: TypeFoldable<'tcx>,
570     {
571         self.replace_late_bound_regions_uncached(value, |br| {
572             self.mk_region(ty::ReFree(ty::FreeRegion {
573                 scope: all_outlive_scope,
574                 bound_region: br.kind,
575             }))
576         })
577     }
578
579     pub fn shift_bound_var_indices<T>(self, bound_vars: usize, value: T) -> T
580     where
581         T: TypeFoldable<'tcx>,
582     {
583         let shift_bv = |bv: ty::BoundVar| ty::BoundVar::from_usize(bv.as_usize() + bound_vars);
584         self.replace_escaping_bound_vars_uncached(
585             value,
586             FnMutDelegate {
587                 regions: |r: ty::BoundRegion| {
588                     self.mk_region(ty::ReLateBound(
589                         ty::INNERMOST,
590                         ty::BoundRegion { var: shift_bv(r.var), kind: r.kind },
591                     ))
592                 },
593                 types: |t: ty::BoundTy| {
594                     self.mk_ty(ty::Bound(
595                         ty::INNERMOST,
596                         ty::BoundTy { var: shift_bv(t.var), kind: t.kind },
597                     ))
598                 },
599                 consts: |c, ty: Ty<'tcx>| {
600                     self.mk_const(ty::ConstS {
601                         kind: ty::ConstKind::Bound(ty::INNERMOST, shift_bv(c)),
602                         ty,
603                     })
604                 },
605             },
606         )
607     }
608
609     /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
610     /// method lookup and a few other places where precise region relationships are not required.
611     pub fn erase_late_bound_regions<T>(self, value: Binder<'tcx, T>) -> T
612     where
613         T: TypeFoldable<'tcx>,
614     {
615         self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
616     }
617
618     /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
619     /// assigned starting at 0 and increasing monotonically in the order traversed
620     /// by the fold operation.
621     ///
622     /// The chief purpose of this function is to canonicalize regions so that two
623     /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
624     /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
625     /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
626     pub fn anonymize_late_bound_regions<T>(self, sig: Binder<'tcx, T>) -> Binder<'tcx, T>
627     where
628         T: TypeFoldable<'tcx>,
629     {
630         let mut counter = 0;
631         let inner = self
632             .replace_late_bound_regions(sig, |_| {
633                 let br = ty::BoundRegion {
634                     var: ty::BoundVar::from_u32(counter),
635                     kind: ty::BrAnon(counter),
636                 };
637                 let r = self.mk_region(ty::ReLateBound(ty::INNERMOST, br));
638                 counter += 1;
639                 r
640             })
641             .0;
642         let bound_vars = self.mk_bound_variable_kinds(
643             (0..counter).map(|i| ty::BoundVariableKind::Region(ty::BrAnon(i))),
644         );
645         Binder::bind_with_vars(inner, bound_vars)
646     }
647
648     /// Anonymize all bound variables in `value`, this is mostly used to improve caching.
649     pub fn anonymize_bound_vars<T>(self, value: Binder<'tcx, T>) -> Binder<'tcx, T>
650     where
651         T: TypeFoldable<'tcx>,
652     {
653         struct Anonymize<'a, 'tcx> {
654             tcx: TyCtxt<'tcx>,
655             map: &'a mut FxIndexMap<ty::BoundVar, ty::BoundVariableKind>,
656         }
657         impl<'tcx> BoundVarReplacerDelegate<'tcx> for Anonymize<'_, 'tcx> {
658             fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
659                 let entry = self.map.entry(br.var);
660                 let index = entry.index();
661                 let var = ty::BoundVar::from_usize(index);
662                 let kind = entry
663                     .or_insert_with(|| ty::BoundVariableKind::Region(ty::BrAnon(index as u32)))
664                     .expect_region();
665                 let br = ty::BoundRegion { var, kind };
666                 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
667             }
668             fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
669                 let entry = self.map.entry(bt.var);
670                 let index = entry.index();
671                 let var = ty::BoundVar::from_usize(index);
672                 let kind = entry
673                     .or_insert_with(|| ty::BoundVariableKind::Ty(ty::BoundTyKind::Anon))
674                     .expect_ty();
675                 self.tcx.mk_ty(ty::Bound(ty::INNERMOST, BoundTy { var, kind }))
676             }
677             fn replace_const(&mut self, bv: ty::BoundVar, ty: Ty<'tcx>) -> ty::Const<'tcx> {
678                 let entry = self.map.entry(bv);
679                 let index = entry.index();
680                 let var = ty::BoundVar::from_usize(index);
681                 let () = entry.or_insert_with(|| ty::BoundVariableKind::Const).expect_const();
682                 self.tcx.mk_const(ty::ConstS { ty, kind: ty::ConstKind::Bound(ty::INNERMOST, var) })
683             }
684         }
685
686         let mut map = Default::default();
687         let delegate = Anonymize { tcx: self, map: &mut map };
688         let inner = self.replace_escaping_bound_vars_uncached(value.skip_binder(), delegate);
689         let bound_vars = self.mk_bound_variable_kinds(map.into_values());
690         Binder::bind_with_vars(inner, bound_vars)
691     }
692 }
693
694 ///////////////////////////////////////////////////////////////////////////
695 // Shifter
696 //
697 // Shifts the De Bruijn indices on all escaping bound vars by a
698 // fixed amount. Useful in substitution or when otherwise introducing
699 // a binding level that is not intended to capture the existing bound
700 // vars. See comment on `shift_vars_through_binders` method in
701 // `subst.rs` for more details.
702
703 struct Shifter<'tcx> {
704     tcx: TyCtxt<'tcx>,
705     current_index: ty::DebruijnIndex,
706     amount: u32,
707 }
708
709 impl<'tcx> Shifter<'tcx> {
710     pub fn new(tcx: TyCtxt<'tcx>, amount: u32) -> Self {
711         Shifter { tcx, current_index: ty::INNERMOST, amount }
712     }
713 }
714
715 impl<'tcx> TypeFolder<'tcx> for Shifter<'tcx> {
716     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
717         self.tcx
718     }
719
720     fn fold_binder<T: TypeFoldable<'tcx>>(
721         &mut self,
722         t: ty::Binder<'tcx, T>,
723     ) -> ty::Binder<'tcx, T> {
724         self.current_index.shift_in(1);
725         let t = t.super_fold_with(self);
726         self.current_index.shift_out(1);
727         t
728     }
729
730     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
731         match *r {
732             ty::ReLateBound(debruijn, br) => {
733                 if self.amount == 0 || debruijn < self.current_index {
734                     r
735                 } else {
736                     let debruijn = debruijn.shifted_in(self.amount);
737                     let shifted = ty::ReLateBound(debruijn, br);
738                     self.tcx.mk_region(shifted)
739                 }
740             }
741             _ => r,
742         }
743     }
744
745     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
746         match *ty.kind() {
747             ty::Bound(debruijn, bound_ty) => {
748                 if self.amount == 0 || debruijn < self.current_index {
749                     ty
750                 } else {
751                     let debruijn = debruijn.shifted_in(self.amount);
752                     self.tcx.mk_ty(ty::Bound(debruijn, bound_ty))
753                 }
754             }
755
756             _ => ty.super_fold_with(self),
757         }
758     }
759
760     fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
761         if let ty::ConstKind::Bound(debruijn, bound_ct) = ct.kind() {
762             if self.amount == 0 || debruijn < self.current_index {
763                 ct
764             } else {
765                 let debruijn = debruijn.shifted_in(self.amount);
766                 self.tcx.mk_const(ty::ConstS {
767                     kind: ty::ConstKind::Bound(debruijn, bound_ct),
768                     ty: ct.ty(),
769                 })
770             }
771         } else {
772             ct.super_fold_with(self)
773         }
774     }
775 }
776
777 pub fn shift_region<'tcx>(
778     tcx: TyCtxt<'tcx>,
779     region: ty::Region<'tcx>,
780     amount: u32,
781 ) -> ty::Region<'tcx> {
782     match *region {
783         ty::ReLateBound(debruijn, br) if amount > 0 => {
784             tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), br))
785         }
786         _ => region,
787     }
788 }
789
790 pub fn shift_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: T, amount: u32) -> T
791 where
792     T: TypeFoldable<'tcx>,
793 {
794     debug!("shift_vars(value={:?}, amount={})", value, amount);
795
796     value.fold_with(&mut Shifter::new(tcx, amount))
797 }