1 //! A folding traversal mechanism for complex data structures that contain type
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`.
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`.
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
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.
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.
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:
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)
47 use crate::ty::{self, Binder, BoundTy, Ty, TyCtxt, TypeVisitable};
48 use rustc_data_structures::fx::FxIndexMap;
49 use rustc_hir::def_id::DefId;
51 use std::collections::BTreeMap;
53 /// This trait is implemented for every type that can be folded,
54 /// providing the skeleton of the traversal.
56 /// To implement this conveniently, use the derive macro located in
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)`.
62 /// For most types, this just traverses the value, calling `try_fold_with`
63 /// on each field/element.
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`
69 fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error>;
71 /// A convenient alternative to `try_fold_with` for use with infallible
72 /// folders. Do not override this method, to ensure coherence with
74 fn fold_with<F: TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
75 self.try_fold_with(folder).into_ok()
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>>(
90 ) -> Result<Self, F::Error>;
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()
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.
106 /// A blanket implementation of [`FallibleTypeFolder`] will defer to
107 /// the infallible methods of this trait to ensure that the two APIs
109 pub trait TypeFolder<'tcx>: FallibleTypeFolder<'tcx, Error = !> {
110 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
112 fn fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Binder<'tcx, T>
114 T: TypeFoldable<'tcx>,
116 t.super_fold_with(self)
119 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
120 t.super_fold_with(self)
123 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
124 r.super_fold_with(self)
127 fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
128 c.super_fold_with(self)
131 fn fold_ty_unevaluated(
133 uv: ty::UnevaluatedConst<'tcx>,
134 ) -> ty::UnevaluatedConst<'tcx> {
135 uv.super_fold_with(self)
138 fn fold_mir_unevaluated(
140 uv: mir::UnevaluatedConst<'tcx>,
141 ) -> mir::UnevaluatedConst<'tcx> {
142 uv.super_fold_with(self)
145 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
146 p.super_fold_with(self)
149 fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx> {
150 bug!("most type folders should not be folding MIR datastructures: {:?}", c)
154 /// This trait is implemented for every folding traversal. There is a fold
155 /// method defined for every type of interest. Each such method has a default
156 /// that does an "identity" fold.
158 /// A blanket implementation of this trait (that defers to the relevant
159 /// method of [`TypeFolder`]) is provided for all infallible folders in
160 /// order to ensure the two APIs are coherent.
161 pub trait FallibleTypeFolder<'tcx>: Sized {
164 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
166 fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, Self::Error>
168 T: TypeFoldable<'tcx>,
170 t.try_super_fold_with(self)
173 fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
174 t.try_super_fold_with(self)
177 fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
178 r.try_super_fold_with(self)
181 fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, Self::Error> {
182 c.try_super_fold_with(self)
185 fn try_fold_ty_unevaluated(
187 c: ty::UnevaluatedConst<'tcx>,
188 ) -> Result<ty::UnevaluatedConst<'tcx>, Self::Error> {
189 c.try_super_fold_with(self)
192 fn try_fold_mir_unevaluated(
194 c: mir::UnevaluatedConst<'tcx>,
195 ) -> Result<mir::UnevaluatedConst<'tcx>, Self::Error> {
196 c.try_super_fold_with(self)
199 fn try_fold_predicate(
201 p: ty::Predicate<'tcx>,
202 ) -> Result<ty::Predicate<'tcx>, Self::Error> {
203 p.try_super_fold_with(self)
206 fn try_fold_mir_const(
208 c: mir::ConstantKind<'tcx>,
209 ) -> Result<mir::ConstantKind<'tcx>, Self::Error> {
210 bug!("most type folders should not be folding MIR datastructures: {:?}", c)
214 // This blanket implementation of the fallible trait for infallible folders
215 // delegates to infallible methods to ensure coherence.
216 impl<'tcx, F> FallibleTypeFolder<'tcx> for F
222 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
223 TypeFolder::tcx(self)
226 fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, !>
228 T: TypeFoldable<'tcx>,
230 Ok(self.fold_binder(t))
233 fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, !> {
237 fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, !> {
238 Ok(self.fold_region(r))
241 fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, !> {
242 Ok(self.fold_const(c))
245 fn try_fold_ty_unevaluated(
247 c: ty::UnevaluatedConst<'tcx>,
248 ) -> Result<ty::UnevaluatedConst<'tcx>, !> {
249 Ok(self.fold_ty_unevaluated(c))
252 fn try_fold_mir_unevaluated(
254 c: mir::UnevaluatedConst<'tcx>,
255 ) -> Result<mir::UnevaluatedConst<'tcx>, !> {
256 Ok(self.fold_mir_unevaluated(c))
259 fn try_fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> Result<ty::Predicate<'tcx>, !> {
260 Ok(self.fold_predicate(p))
263 fn try_fold_mir_const(
265 c: mir::ConstantKind<'tcx>,
266 ) -> Result<mir::ConstantKind<'tcx>, !> {
267 Ok(self.fold_mir_const(c))
271 ///////////////////////////////////////////////////////////////////////////
272 // Some sample folders
274 pub struct BottomUpFolder<'tcx, F, G, H>
276 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
277 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
278 H: FnMut(ty::Const<'tcx>) -> ty::Const<'tcx>,
280 pub tcx: TyCtxt<'tcx>,
286 impl<'tcx, F, G, H> TypeFolder<'tcx> for BottomUpFolder<'tcx, F, G, H>
288 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
289 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
290 H: FnMut(ty::Const<'tcx>) -> ty::Const<'tcx>,
292 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
296 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
297 let t = ty.super_fold_with(self);
301 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
302 let r = r.super_fold_with(self);
306 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
307 let ct = ct.super_fold_with(self);
312 ///////////////////////////////////////////////////////////////////////////
315 impl<'tcx> TyCtxt<'tcx> {
316 /// Folds the escaping and free regions in `value` using `f`, and
317 /// sets `skipped_regions` to true if any late-bound region was found
319 pub fn fold_regions<T>(
322 mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
325 T: TypeFoldable<'tcx>,
327 value.fold_with(&mut RegionFolder::new(self, &mut f))
330 pub fn super_fold_regions<T>(
333 mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
336 T: TypeSuperFoldable<'tcx>,
338 value.super_fold_with(&mut RegionFolder::new(self, &mut f))
342 /// Folds over the substructure of a type, visiting its component
343 /// types and all regions that occur *free* within it.
345 /// That is, `Ty` can contain function or method types that bind
346 /// regions at the call site (`ReLateBound`), and occurrences of
347 /// regions (aka "lifetimes") that are bound within a type are not
348 /// visited by this folder; only regions that occur free will be
349 /// visited by `fld_r`.
351 pub struct RegionFolder<'a, 'tcx> {
354 /// Stores the index of a binder *just outside* the stuff we have
355 /// visited. So this begins as INNERMOST; when we pass through a
356 /// binder, it is incremented (via `shift_in`).
357 current_index: ty::DebruijnIndex,
359 /// Callback invokes for each free region. The `DebruijnIndex`
360 /// points to the binder *just outside* the ones we have passed
363 &'a mut (dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx> + 'a),
366 impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
370 fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
371 ) -> RegionFolder<'a, 'tcx> {
372 RegionFolder { tcx, current_index: ty::INNERMOST, fold_region_fn }
376 impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
377 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
381 fn fold_binder<T: TypeFoldable<'tcx>>(
383 t: ty::Binder<'tcx, T>,
384 ) -> ty::Binder<'tcx, T> {
385 self.current_index.shift_in(1);
386 let t = t.super_fold_with(self);
387 self.current_index.shift_out(1);
391 #[instrument(skip(self), level = "debug", ret)]
392 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
394 ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
395 debug!(?self.current_index, "skipped bound region");
399 debug!(?self.current_index, "folding free region");
400 (self.fold_region_fn)(r, self.current_index)
406 ///////////////////////////////////////////////////////////////////////////
407 // Bound vars replacer
409 pub trait BoundVarReplacerDelegate<'tcx> {
410 fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx>;
411 fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx>;
412 fn replace_const(&mut self, bv: ty::BoundVar, ty: Ty<'tcx>) -> ty::Const<'tcx>;
415 pub struct FnMutDelegate<'a, 'tcx> {
416 pub regions: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
417 pub types: &'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a),
418 pub consts: &'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> ty::Const<'tcx> + 'a),
421 impl<'a, 'tcx> BoundVarReplacerDelegate<'tcx> for FnMutDelegate<'a, 'tcx> {
422 fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
425 fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
428 fn replace_const(&mut self, bv: ty::BoundVar, ty: Ty<'tcx>) -> ty::Const<'tcx> {
429 (self.consts)(bv, ty)
433 /// Replaces the escaping bound vars (late bound regions or bound types) in a type.
434 struct BoundVarReplacer<'tcx, D> {
437 /// As with `RegionFolder`, represents the index of a binder *just outside*
438 /// the ones we have visited.
439 current_index: ty::DebruijnIndex,
444 impl<'tcx, D: BoundVarReplacerDelegate<'tcx>> BoundVarReplacer<'tcx, D> {
445 fn new(tcx: TyCtxt<'tcx>, delegate: D) -> Self {
446 BoundVarReplacer { tcx, current_index: ty::INNERMOST, delegate }
450 impl<'tcx, D> TypeFolder<'tcx> for BoundVarReplacer<'tcx, D>
452 D: BoundVarReplacerDelegate<'tcx>,
454 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
458 fn fold_binder<T: TypeFoldable<'tcx>>(
460 t: ty::Binder<'tcx, T>,
461 ) -> ty::Binder<'tcx, T> {
462 self.current_index.shift_in(1);
463 let t = t.super_fold_with(self);
464 self.current_index.shift_out(1);
468 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
470 ty::Bound(debruijn, bound_ty) if debruijn == self.current_index => {
471 let ty = self.delegate.replace_ty(bound_ty);
472 ty::fold::shift_vars(self.tcx, ty, self.current_index.as_u32())
474 _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
479 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
481 ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
482 let region = self.delegate.replace_region(br);
483 if let ty::ReLateBound(debruijn1, br) = *region {
484 // If the callback returns a late-bound region,
485 // that region should always use the INNERMOST
486 // debruijn index. Then we adjust it to the
488 assert_eq!(debruijn1, ty::INNERMOST);
489 self.tcx.reuse_or_mk_region(region, ty::ReLateBound(debruijn, br))
498 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
500 ty::ConstKind::Bound(debruijn, bound_const) if debruijn == self.current_index => {
501 let ct = self.delegate.replace_const(bound_const, ct.ty());
502 ty::fold::shift_vars(self.tcx, ct, self.current_index.as_u32())
504 _ => ct.super_fold_with(self),
508 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
509 if p.has_vars_bound_at_or_above(self.current_index) { p.super_fold_with(self) } else { p }
513 impl<'tcx> TyCtxt<'tcx> {
514 /// Replaces all regions bound by the given `Binder` with the
515 /// results returned by the closure; the closure is expected to
516 /// return a free region (relative to this binder), and hence the
517 /// binder is removed in the return type. The closure is invoked
518 /// once for each unique `BoundRegionKind`; multiple references to the
519 /// same `BoundRegionKind` will reuse the previous result. A map is
520 /// returned at the end with each bound region and the free region
521 /// that replaced it.
525 /// This method only replaces late bound regions. Any types or
526 /// constants bound by `value` will cause an ICE.
527 pub fn replace_late_bound_regions<T, F>(
529 value: Binder<'tcx, T>,
531 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
533 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
534 T: TypeFoldable<'tcx>,
536 let mut region_map = BTreeMap::new();
537 let real_fld_r = |br: ty::BoundRegion| *region_map.entry(br).or_insert_with(|| fld_r(br));
538 let value = self.replace_late_bound_regions_uncached(value, real_fld_r);
542 pub fn replace_late_bound_regions_uncached<T, F>(
544 value: Binder<'tcx, T>,
545 mut replace_regions: F,
548 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
549 T: TypeFoldable<'tcx>,
551 let value = value.skip_binder();
552 if !value.has_escaping_bound_vars() {
555 let delegate = FnMutDelegate {
556 regions: &mut replace_regions,
557 types: &mut |b| bug!("unexpected bound ty in binder: {b:?}"),
558 consts: &mut |b, ty| bug!("unexpected bound ct in binder: {b:?} {ty}"),
560 let mut replacer = BoundVarReplacer::new(self, delegate);
561 value.fold_with(&mut replacer)
565 /// Replaces all escaping bound vars. The `fld_r` closure replaces escaping
566 /// bound regions; the `fld_t` closure replaces escaping bound types and the `fld_c`
567 /// closure replaces escaping bound consts.
568 pub fn replace_escaping_bound_vars_uncached<T: TypeFoldable<'tcx>>(
571 delegate: impl BoundVarReplacerDelegate<'tcx>,
573 if !value.has_escaping_bound_vars() {
576 let mut replacer = BoundVarReplacer::new(self, delegate);
577 value.fold_with(&mut replacer)
581 /// Replaces all types or regions bound by the given `Binder`. The `fld_r`
582 /// closure replaces bound regions, the `fld_t` closure replaces bound
583 /// types, and `fld_c` replaces bound constants.
584 pub fn replace_bound_vars_uncached<T: TypeFoldable<'tcx>>(
586 value: Binder<'tcx, T>,
587 delegate: impl BoundVarReplacerDelegate<'tcx>,
589 self.replace_escaping_bound_vars_uncached(value.skip_binder(), delegate)
592 /// Replaces any late-bound regions bound in `value` with
593 /// free variants attached to `all_outlive_scope`.
594 pub fn liberate_late_bound_regions<T>(
596 all_outlive_scope: DefId,
597 value: ty::Binder<'tcx, T>,
600 T: TypeFoldable<'tcx>,
602 self.replace_late_bound_regions_uncached(value, |br| {
603 self.mk_region(ty::ReFree(ty::FreeRegion {
604 scope: all_outlive_scope,
605 bound_region: br.kind,
610 pub fn shift_bound_var_indices<T>(self, bound_vars: usize, value: T) -> T
612 T: TypeFoldable<'tcx>,
614 let shift_bv = |bv: ty::BoundVar| ty::BoundVar::from_usize(bv.as_usize() + bound_vars);
615 self.replace_escaping_bound_vars_uncached(
618 regions: &mut |r: ty::BoundRegion| {
619 self.mk_region(ty::ReLateBound(
621 ty::BoundRegion { var: shift_bv(r.var), kind: r.kind },
624 types: &mut |t: ty::BoundTy| {
625 self.mk_ty(ty::Bound(
627 ty::BoundTy { var: shift_bv(t.var), kind: t.kind },
630 consts: &mut |c, ty: Ty<'tcx>| {
631 self.mk_const(ty::ConstS {
632 kind: ty::ConstKind::Bound(ty::INNERMOST, shift_bv(c)),
640 /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
641 /// method lookup and a few other places where precise region relationships are not required.
642 pub fn erase_late_bound_regions<T>(self, value: Binder<'tcx, T>) -> T
644 T: TypeFoldable<'tcx>,
646 self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
649 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
650 /// assigned starting at 0 and increasing monotonically in the order traversed
651 /// by the fold operation.
653 /// The chief purpose of this function is to canonicalize regions so that two
654 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
655 /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
656 /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
657 pub fn anonymize_late_bound_regions<T>(self, sig: Binder<'tcx, T>) -> Binder<'tcx, T>
659 T: TypeFoldable<'tcx>,
663 .replace_late_bound_regions(sig, |_| {
664 let br = ty::BoundRegion {
665 var: ty::BoundVar::from_u32(counter),
666 kind: ty::BrAnon(counter),
668 let r = self.mk_region(ty::ReLateBound(ty::INNERMOST, br));
673 let bound_vars = self.mk_bound_variable_kinds(
674 (0..counter).map(|i| ty::BoundVariableKind::Region(ty::BrAnon(i))),
676 Binder::bind_with_vars(inner, bound_vars)
679 /// Anonymize all bound variables in `value`, this is mostly used to improve caching.
680 pub fn anonymize_bound_vars<T>(self, value: Binder<'tcx, T>) -> Binder<'tcx, T>
682 T: TypeFoldable<'tcx>,
684 struct Anonymize<'a, 'tcx> {
686 map: &'a mut FxIndexMap<ty::BoundVar, ty::BoundVariableKind>,
688 impl<'tcx> BoundVarReplacerDelegate<'tcx> for Anonymize<'_, 'tcx> {
689 fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
690 let entry = self.map.entry(br.var);
691 let index = entry.index();
692 let var = ty::BoundVar::from_usize(index);
694 .or_insert_with(|| ty::BoundVariableKind::Region(ty::BrAnon(index as u32)))
696 let br = ty::BoundRegion { var, kind };
697 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
699 fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
700 let entry = self.map.entry(bt.var);
701 let index = entry.index();
702 let var = ty::BoundVar::from_usize(index);
704 .or_insert_with(|| ty::BoundVariableKind::Ty(ty::BoundTyKind::Anon))
706 self.tcx.mk_ty(ty::Bound(ty::INNERMOST, BoundTy { var, kind }))
708 fn replace_const(&mut self, bv: ty::BoundVar, ty: Ty<'tcx>) -> ty::Const<'tcx> {
709 let entry = self.map.entry(bv);
710 let index = entry.index();
711 let var = ty::BoundVar::from_usize(index);
712 let () = entry.or_insert_with(|| ty::BoundVariableKind::Const).expect_const();
713 self.tcx.mk_const(ty::ConstS { ty, kind: ty::ConstKind::Bound(ty::INNERMOST, var) })
717 let mut map = Default::default();
718 let delegate = Anonymize { tcx: self, map: &mut map };
719 let inner = self.replace_escaping_bound_vars_uncached(value.skip_binder(), delegate);
720 let bound_vars = self.mk_bound_variable_kinds(map.into_values());
721 Binder::bind_with_vars(inner, bound_vars)
725 ///////////////////////////////////////////////////////////////////////////
728 // Shifts the De Bruijn indices on all escaping bound vars by a
729 // fixed amount. Useful in substitution or when otherwise introducing
730 // a binding level that is not intended to capture the existing bound
731 // vars. See comment on `shift_vars_through_binders` method in
732 // `subst.rs` for more details.
734 struct Shifter<'tcx> {
736 current_index: ty::DebruijnIndex,
740 impl<'tcx> Shifter<'tcx> {
741 pub fn new(tcx: TyCtxt<'tcx>, amount: u32) -> Self {
742 Shifter { tcx, current_index: ty::INNERMOST, amount }
746 impl<'tcx> TypeFolder<'tcx> for Shifter<'tcx> {
747 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
751 fn fold_binder<T: TypeFoldable<'tcx>>(
753 t: ty::Binder<'tcx, T>,
754 ) -> ty::Binder<'tcx, T> {
755 self.current_index.shift_in(1);
756 let t = t.super_fold_with(self);
757 self.current_index.shift_out(1);
761 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
763 ty::ReLateBound(debruijn, br) => {
764 if self.amount == 0 || debruijn < self.current_index {
767 let debruijn = debruijn.shifted_in(self.amount);
768 let shifted = ty::ReLateBound(debruijn, br);
769 self.tcx.mk_region(shifted)
776 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
778 ty::Bound(debruijn, bound_ty) => {
779 if self.amount == 0 || debruijn < self.current_index {
782 let debruijn = debruijn.shifted_in(self.amount);
783 self.tcx.mk_ty(ty::Bound(debruijn, bound_ty))
787 _ => ty.super_fold_with(self),
791 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
792 if let ty::ConstKind::Bound(debruijn, bound_ct) = ct.kind() {
793 if self.amount == 0 || debruijn < self.current_index {
796 let debruijn = debruijn.shifted_in(self.amount);
797 self.tcx.mk_const(ty::ConstS {
798 kind: ty::ConstKind::Bound(debruijn, bound_ct),
803 ct.super_fold_with(self)
808 pub fn shift_region<'tcx>(
810 region: ty::Region<'tcx>,
812 ) -> ty::Region<'tcx> {
814 ty::ReLateBound(debruijn, br) if amount > 0 => {
815 tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), br))
821 pub fn shift_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: T, amount: u32) -> T
823 T: TypeFoldable<'tcx>,
825 debug!("shift_vars(value={:?}, amount={})", value, amount);
827 value.fold_with(&mut Shifter::new(tcx, amount))