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