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_unevaluated(&mut self, uv: ty::Unevaluated<'tcx>) -> ty::Unevaluated<'tcx> {
132 uv.super_fold_with(self)
135 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
136 p.super_fold_with(self)
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)
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.
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 {
154 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
156 fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, Self::Error>
158 T: TypeFoldable<'tcx>,
160 t.try_super_fold_with(self)
163 fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
164 t.try_super_fold_with(self)
167 fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
168 r.try_super_fold_with(self)
171 fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, Self::Error> {
172 c.try_super_fold_with(self)
175 fn try_fold_unevaluated(
177 c: ty::Unevaluated<'tcx>,
178 ) -> Result<ty::Unevaluated<'tcx>, Self::Error> {
179 c.try_super_fold_with(self)
182 fn try_fold_predicate(
184 p: ty::Predicate<'tcx>,
185 ) -> Result<ty::Predicate<'tcx>, Self::Error> {
186 p.try_super_fold_with(self)
189 fn try_fold_mir_const(
191 c: mir::ConstantKind<'tcx>,
192 ) -> Result<mir::ConstantKind<'tcx>, Self::Error> {
193 bug!("most type folders should not be folding MIR datastructures: {:?}", c)
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
205 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
206 TypeFolder::tcx(self)
209 fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, !>
211 T: TypeFoldable<'tcx>,
213 Ok(self.fold_binder(t))
216 fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, !> {
220 fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, !> {
221 Ok(self.fold_region(r))
224 fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, !> {
225 Ok(self.fold_const(c))
228 fn try_fold_unevaluated(
230 c: ty::Unevaluated<'tcx>,
231 ) -> Result<ty::Unevaluated<'tcx>, !> {
232 Ok(self.fold_unevaluated(c))
235 fn try_fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> Result<ty::Predicate<'tcx>, !> {
236 Ok(self.fold_predicate(p))
239 fn try_fold_mir_const(
241 c: mir::ConstantKind<'tcx>,
242 ) -> Result<mir::ConstantKind<'tcx>, !> {
243 Ok(self.fold_mir_const(c))
247 ///////////////////////////////////////////////////////////////////////////
248 // Some sample folders
250 pub struct BottomUpFolder<'tcx, F, G, H>
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>,
256 pub tcx: TyCtxt<'tcx>,
262 impl<'tcx, F, G, H> TypeFolder<'tcx> for BottomUpFolder<'tcx, F, G, H>
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>,
268 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
272 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
273 let t = ty.super_fold_with(self);
277 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
278 let r = r.super_fold_with(self);
282 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
283 let ct = ct.super_fold_with(self);
288 ///////////////////////////////////////////////////////////////////////////
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
295 pub fn fold_regions<T>(
298 mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
301 T: TypeFoldable<'tcx>,
303 value.fold_with(&mut RegionFolder::new(self, &mut f))
307 /// Folds over the substructure of a type, visiting its component
308 /// types and all regions that occur *free* within it.
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`.
316 pub struct RegionFolder<'a, 'tcx> {
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,
324 /// Callback invokes for each free region. The `DebruijnIndex`
325 /// points to the binder *just outside* the ones we have passed
328 &'a mut (dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx> + 'a),
331 impl<'a, 'tcx> RegionFolder<'a, '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 }
341 impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
342 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
346 fn fold_binder<T: TypeFoldable<'tcx>>(
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);
356 #[instrument(skip(self), level = "debug", ret)]
357 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
359 ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
360 debug!(?self.current_index, "skipped bound region");
364 debug!(?self.current_index, "folding free region");
365 (self.fold_region_fn)(r, self.current_index)
371 ///////////////////////////////////////////////////////////////////////////
372 // Bound vars replacer
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>;
380 pub struct FnMutDelegate<R, T, C> {
385 impl<'tcx, R, T, C> BoundVarReplacerDelegate<'tcx> for FnMutDelegate<R, T, C>
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>,
391 fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
394 fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
397 fn replace_const(&mut self, bv: ty::BoundVar, ty: Ty<'tcx>) -> ty::Const<'tcx> {
398 (self.consts)(bv, ty)
402 /// Replaces the escaping bound vars (late bound regions or bound types) in a type.
403 struct BoundVarReplacer<'tcx, D> {
406 /// As with `RegionFolder`, represents the index of a binder *just outside*
407 /// the ones we have visited.
408 current_index: ty::DebruijnIndex,
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 }
419 impl<'tcx, D> TypeFolder<'tcx> for BoundVarReplacer<'tcx, D>
421 D: BoundVarReplacerDelegate<'tcx>,
423 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
427 fn fold_binder<T: TypeFoldable<'tcx>>(
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);
437 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
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())
443 _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
448 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
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
457 assert_eq!(debruijn1, ty::INNERMOST);
458 self.tcx.reuse_or_mk_region(region, ty::ReLateBound(debruijn, br))
467 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
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())
473 _ => ct.super_fold_with(self),
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 }
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.
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>(
498 value: Binder<'tcx, T>,
500 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
502 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
503 T: TypeFoldable<'tcx>,
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);
511 pub fn replace_late_bound_regions_uncached<T, F>(
513 value: Binder<'tcx, T>,
517 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
518 T: TypeFoldable<'tcx>,
520 let value = value.skip_binder();
521 if !value.has_escaping_bound_vars() {
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}"),
529 let mut replacer = BoundVarReplacer::new(self, delegate);
530 value.fold_with(&mut replacer)
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>>(
540 delegate: impl BoundVarReplacerDelegate<'tcx>,
542 if !value.has_escaping_bound_vars() {
545 let mut replacer = BoundVarReplacer::new(self, delegate);
546 value.fold_with(&mut replacer)
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>>(
555 value: Binder<'tcx, T>,
556 delegate: impl BoundVarReplacerDelegate<'tcx>,
558 self.replace_escaping_bound_vars_uncached(value.skip_binder(), delegate)
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>(
565 all_outlive_scope: DefId,
566 value: ty::Binder<'tcx, T>,
569 T: TypeFoldable<'tcx>,
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,
579 pub fn shift_bound_var_indices<T>(self, bound_vars: usize, value: T) -> T
581 T: TypeFoldable<'tcx>,
583 let shift_bv = |bv: ty::BoundVar| ty::BoundVar::from_usize(bv.as_usize() + bound_vars);
584 self.replace_escaping_bound_vars_uncached(
587 regions: |r: ty::BoundRegion| {
588 self.mk_region(ty::ReLateBound(
590 ty::BoundRegion { var: shift_bv(r.var), kind: r.kind },
593 types: |t: ty::BoundTy| {
594 self.mk_ty(ty::Bound(
596 ty::BoundTy { var: shift_bv(t.var), kind: t.kind },
599 consts: |c, ty: Ty<'tcx>| {
600 self.mk_const(ty::ConstS {
601 kind: ty::ConstKind::Bound(ty::INNERMOST, shift_bv(c)),
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
613 T: TypeFoldable<'tcx>,
615 self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
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.
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>
628 T: TypeFoldable<'tcx>,
632 .replace_late_bound_regions(sig, |_| {
633 let br = ty::BoundRegion {
634 var: ty::BoundVar::from_u32(counter),
635 kind: ty::BrAnon(counter),
637 let r = self.mk_region(ty::ReLateBound(ty::INNERMOST, br));
642 let bound_vars = self.mk_bound_variable_kinds(
643 (0..counter).map(|i| ty::BoundVariableKind::Region(ty::BrAnon(i))),
645 Binder::bind_with_vars(inner, bound_vars)
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>
651 T: TypeFoldable<'tcx>,
653 struct Anonymize<'a, 'tcx> {
655 map: &'a mut FxIndexMap<ty::BoundVar, ty::BoundVariableKind>,
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);
663 .or_insert_with(|| ty::BoundVariableKind::Region(ty::BrAnon(index as u32)))
665 let br = ty::BoundRegion { var, kind };
666 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
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);
673 .or_insert_with(|| ty::BoundVariableKind::Ty(ty::BoundTyKind::Anon))
675 self.tcx.mk_ty(ty::Bound(ty::INNERMOST, BoundTy { var, kind }))
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) })
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)
694 ///////////////////////////////////////////////////////////////////////////
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.
703 struct Shifter<'tcx> {
705 current_index: ty::DebruijnIndex,
709 impl<'tcx> Shifter<'tcx> {
710 pub fn new(tcx: TyCtxt<'tcx>, amount: u32) -> Self {
711 Shifter { tcx, current_index: ty::INNERMOST, amount }
715 impl<'tcx> TypeFolder<'tcx> for Shifter<'tcx> {
716 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
720 fn fold_binder<T: TypeFoldable<'tcx>>(
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);
730 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
732 ty::ReLateBound(debruijn, br) => {
733 if self.amount == 0 || debruijn < self.current_index {
736 let debruijn = debruijn.shifted_in(self.amount);
737 let shifted = ty::ReLateBound(debruijn, br);
738 self.tcx.mk_region(shifted)
745 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
747 ty::Bound(debruijn, bound_ty) => {
748 if self.amount == 0 || debruijn < self.current_index {
751 let debruijn = debruijn.shifted_in(self.amount);
752 self.tcx.mk_ty(ty::Bound(debruijn, bound_ty))
756 _ => ty.super_fold_with(self),
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 {
765 let debruijn = debruijn.shifted_in(self.amount);
766 self.tcx.mk_const(ty::ConstS {
767 kind: ty::ConstKind::Bound(debruijn, bound_ct),
772 ct.super_fold_with(self)
777 pub fn shift_region<'tcx>(
779 region: ty::Region<'tcx>,
781 ) -> ty::Region<'tcx> {
783 ty::ReLateBound(debruijn, br) if amount > 0 => {
784 tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), br))
790 pub fn shift_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: T, amount: u32) -> T
792 T: TypeFoldable<'tcx>,
794 debug!("shift_vars(value={:?}, amount={})", value, amount);
796 value.fold_with(&mut Shifter::new(tcx, amount))