Skip to main content

rustc_middle/ty/
fold.rs

1use rustc_data_structures::fx::FxIndexMap;
2use rustc_hir::def_id::DefId;
3use rustc_span::bug;
4use rustc_type_ir::PredicateProxy;
5use rustc_type_ir::data_structures::DelayedMap;
6
7use crate::ty::{
8    self, Binder, BoundTy, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
9    TypeVisitableExt,
10};
11
12///////////////////////////////////////////////////////////////////////////
13// Some sample folders
14
15pub struct BottomUpFolder<'tcx, F, G, H>
16where
17    F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
18    G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
19    H: FnMut(ty::Const<'tcx>) -> ty::Const<'tcx>,
20{
21    pub tcx: TyCtxt<'tcx>,
22    pub ty_op: F,
23    pub lt_op: G,
24    pub ct_op: H,
25}
26
27impl<'tcx, F, G, H> TypeFolder<TyCtxt<'tcx>> for BottomUpFolder<'tcx, F, G, H>
28where
29    F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
30    G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
31    H: FnMut(ty::Const<'tcx>) -> ty::Const<'tcx>,
32{
33    fn cx(&self) -> TyCtxt<'tcx> {
34        self.tcx
35    }
36
37    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
38        let t = ty.super_fold_with(self);
39        (self.ty_op)(t)
40    }
41
42    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
43        // This one is a little different, because `super_fold_with` is not
44        // implemented on non-recursive `Region`.
45        (self.lt_op)(r)
46    }
47
48    fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
49        let ct = ct.super_fold_with(self);
50        (self.ct_op)(ct)
51    }
52}
53
54///////////////////////////////////////////////////////////////////////////
55// Bound vars replacer
56
57/// A delegate used when instantiating bound vars.
58///
59/// Any implementation must make sure that each bound variable always
60/// gets mapped to the same result. `BoundVarReplacer` caches by using
61/// a `DelayedMap` which does not cache the first few types it encounters.
62pub trait BoundVarReplacerDelegate<'tcx> {
63    fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx>;
64    fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx>;
65    fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx>;
66}
67
68/// A simple delegate taking 3 mutable functions. The used functions must
69/// always return the same result for each bound variable, no matter how
70/// frequently they are called.
71pub struct FnMutDelegate<'a, 'tcx> {
72    pub regions: &'a mut (dyn FnMut(ty::BoundRegion<'tcx>) -> ty::Region<'tcx> + 'a),
73    pub types: &'a mut (dyn FnMut(ty::BoundTy<'tcx>) -> Ty<'tcx> + 'a),
74    pub consts: &'a mut (dyn FnMut(ty::BoundConst<'tcx>) -> ty::Const<'tcx> + 'a),
75}
76
77impl<'a, 'tcx> BoundVarReplacerDelegate<'tcx> for FnMutDelegate<'a, 'tcx> {
78    fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
79        (self.regions)(br)
80    }
81    fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
82        (self.types)(bt)
83    }
84    fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
85        (self.consts)(bc)
86    }
87}
88
89/// Replaces the escaping bound vars (late bound regions or bound types) in a type.
90struct BoundVarReplacer<'tcx, D> {
91    tcx: TyCtxt<'tcx>,
92
93    /// As with `RegionFolder`, represents the index of a binder *just outside*
94    /// the ones we have visited.
95    current_index: ty::DebruijnIndex,
96
97    delegate: D,
98
99    /// This cache only tracks the `DebruijnIndex` and assumes that it does not matter
100    /// for the delegate how often its methods get used.
101    cache: DelayedMap<(ty::DebruijnIndex, Ty<'tcx>), Ty<'tcx>>,
102}
103
104impl<'tcx, D: BoundVarReplacerDelegate<'tcx>> BoundVarReplacer<'tcx, D> {
105    fn new(tcx: TyCtxt<'tcx>, delegate: D) -> Self {
106        BoundVarReplacer { tcx, current_index: ty::INNERMOST, delegate, cache: Default::default() }
107    }
108}
109
110impl<'tcx, D> TypeFolder<TyCtxt<'tcx>> for BoundVarReplacer<'tcx, D>
111where
112    D: BoundVarReplacerDelegate<'tcx>,
113{
114    fn cx(&self) -> TyCtxt<'tcx> {
115        self.tcx
116    }
117
118    fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>(
119        &mut self,
120        t: ty::Binder<'tcx, T>,
121    ) -> ty::Binder<'tcx, T> {
122        self.current_index.shift_in(1);
123        let t = t.super_fold_with(self);
124        self.current_index.shift_out(1);
125        t
126    }
127
128    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
129        match *t.kind() {
130            ty::Bound(ty::BoundVarIndexKind::Bound(debruijn), bound_ty)
131                if debruijn == self.current_index =>
132            {
133                let ty = self.delegate.replace_ty(bound_ty);
134                if true {
    if !!ty.has_vars_bound_above(ty::INNERMOST) {
        ::core::panicking::panic("assertion failed: !ty.has_vars_bound_above(ty::INNERMOST)")
    };
};debug_assert!(!ty.has_vars_bound_above(ty::INNERMOST));
135                ty::shift_vars(self.tcx, ty, self.current_index.as_u32())
136            }
137            _ => {
138                if !t.has_vars_bound_at_or_above(self.current_index) {
139                    t
140                } else if let Some(&t) = self.cache.get(&(self.current_index, t)) {
141                    t
142                } else {
143                    let res = t.super_fold_with(self);
144                    if !self.cache.insert((self.current_index, t), res) {
    ::core::panicking::panic("assertion failed: self.cache.insert((self.current_index, t), res)")
};assert!(self.cache.insert((self.current_index, t), res));
145                    res
146                }
147            }
148        }
149    }
150
151    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
152        match r.kind() {
153            ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn), br)
154                if debruijn == self.current_index =>
155            {
156                let region = self.delegate.replace_region(br);
157                if let ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn1), br) = region.kind() {
158                    // If the callback returns a bound region,
159                    // that region should always use the INNERMOST
160                    // debruijn index. Then we adjust it to the
161                    // correct depth.
162                    {
    match (&debruijn1, &ty::INNERMOST) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(debruijn1, ty::INNERMOST);
163                    ty::Region::new_bound(self.tcx, debruijn, br)
164                } else {
165                    region
166                }
167            }
168            _ => r,
169        }
170    }
171
172    fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
173        match ct.kind() {
174            ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(debruijn), bound_const)
175                if debruijn == self.current_index =>
176            {
177                let ct = self.delegate.replace_const(bound_const);
178                if true {
    if !!ct.has_vars_bound_above(ty::INNERMOST) {
        ::core::panicking::panic("assertion failed: !ct.has_vars_bound_above(ty::INNERMOST)")
    };
};debug_assert!(!ct.has_vars_bound_above(ty::INNERMOST));
179                ty::shift_vars(self.tcx, ct, self.current_index.as_u32())
180            }
181            _ => ct.super_fold_with(self),
182        }
183    }
184
185    fn fold_predicate<P: PredicateProxy<TyCtxt<'tcx>>>(&mut self, p: P) -> P {
186        if p.has_vars_bound_at_or_above(self.current_index) { p.super_fold_with(self) } else { p }
187    }
188
189    fn fold_clauses(&mut self, c: ty::Clauses<'tcx>) -> ty::Clauses<'tcx> {
190        if c.has_vars_bound_at_or_above(self.current_index) { c.super_fold_with(self) } else { c }
191    }
192}
193
194impl<'tcx> TyCtxt<'tcx> {
195    /// Replaces all regions bound by the given `Binder` with the
196    /// results returned by the closure; the closure is expected to
197    /// return a free region (relative to this binder), and hence the
198    /// binder is removed in the return type. The closure is invoked
199    /// once for each unique `BoundRegionKind`; multiple references to the
200    /// same `BoundRegionKind` will reuse the previous result. A map is
201    /// returned at the end with each bound region and the free region
202    /// that replaced it.
203    ///
204    /// # Panics
205    ///
206    /// This method only replaces late bound regions. Any types or
207    /// constants bound by `value` will cause an ICE.
208    pub fn instantiate_bound_regions<T, F>(
209        self,
210        value: Binder<'tcx, T>,
211        mut fld_r: F,
212    ) -> (T, FxIndexMap<ty::BoundRegion<'tcx>, ty::Region<'tcx>>)
213    where
214        F: FnMut(ty::BoundRegion<'tcx>) -> ty::Region<'tcx>,
215        T: TypeFoldable<TyCtxt<'tcx>>,
216    {
217        let mut region_map = FxIndexMap::default();
218        let real_fld_r =
219            |br: ty::BoundRegion<'tcx>| *region_map.entry(br).or_insert_with(|| fld_r(br));
220        let value = self.instantiate_bound_regions_uncached(value, real_fld_r);
221        (value, region_map)
222    }
223
224    pub fn instantiate_bound_regions_uncached<T, F>(
225        self,
226        value: Binder<'tcx, T>,
227        mut replace_regions: F,
228    ) -> T
229    where
230        F: FnMut(ty::BoundRegion<'tcx>) -> ty::Region<'tcx>,
231        T: TypeFoldable<TyCtxt<'tcx>>,
232    {
233        let value = value.skip_binder();
234        if !value.has_escaping_bound_vars() {
235            value
236        } else {
237            let delegate = FnMutDelegate {
238                regions: &mut replace_regions,
239                types: &mut |b| ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected bound ty in binder: {0:?}", b),
    Location::caller())bug!("unexpected bound ty in binder: {b:?}"),
240                consts: &mut |b| ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected bound ct in binder: {0:?}", b),
    Location::caller())bug!("unexpected bound ct in binder: {b:?}"),
241            };
242            let mut replacer = BoundVarReplacer::new(self, delegate);
243            value.fold_with(&mut replacer)
244        }
245    }
246
247    /// Replaces all escaping bound vars. The `fld_r` closure replaces escaping
248    /// bound regions; the `fld_t` closure replaces escaping bound types and the `fld_c`
249    /// closure replaces escaping bound consts.
250    pub fn replace_escaping_bound_vars_uncached<T: TypeFoldable<TyCtxt<'tcx>>>(
251        self,
252        value: T,
253        delegate: impl BoundVarReplacerDelegate<'tcx>,
254    ) -> T {
255        if !value.has_escaping_bound_vars() {
256            value
257        } else {
258            let mut replacer = BoundVarReplacer::new(self, delegate);
259            value.fold_with(&mut replacer)
260        }
261    }
262
263    /// Replaces all types or regions bound by the given `Binder`. The `fld_r`
264    /// closure replaces bound regions, the `fld_t` closure replaces bound
265    /// types, and `fld_c` replaces bound constants.
266    pub fn replace_bound_vars_uncached<T: TypeFoldable<TyCtxt<'tcx>>>(
267        self,
268        value: Binder<'tcx, T>,
269        delegate: impl BoundVarReplacerDelegate<'tcx>,
270    ) -> T {
271        self.replace_escaping_bound_vars_uncached(value.skip_binder(), delegate)
272    }
273
274    /// Replaces any late-bound regions bound in `value` with
275    /// free variants attached to `all_outlive_scope`.
276    pub fn liberate_late_bound_regions<T>(
277        self,
278        all_outlive_scope: DefId,
279        value: ty::Binder<'tcx, T>,
280    ) -> T
281    where
282        T: TypeFoldable<TyCtxt<'tcx>>,
283    {
284        self.instantiate_bound_regions_uncached(value, |br| {
285            let kind = ty::LateParamRegionKind::from_bound(br.var, br.kind);
286            ty::Region::new_late_param(self, all_outlive_scope, kind)
287        })
288    }
289
290    pub fn shift_bound_var_indices<T>(self, bound_vars: usize, value: T) -> T
291    where
292        T: TypeFoldable<TyCtxt<'tcx>>,
293    {
294        let shift_bv = |bv: ty::BoundVar| bv + bound_vars;
295        self.replace_escaping_bound_vars_uncached(
296            value,
297            FnMutDelegate {
298                regions: &mut |r: ty::BoundRegion<'tcx>| {
299                    ty::Region::new_bound(
300                        self,
301                        ty::INNERMOST,
302                        ty::BoundRegion { var: shift_bv(r.var), kind: r.kind },
303                    )
304                },
305                types: &mut |t: ty::BoundTy<'tcx>| {
306                    Ty::new_bound(
307                        self,
308                        ty::INNERMOST,
309                        ty::BoundTy { var: shift_bv(t.var), kind: t.kind },
310                    )
311                },
312                consts: &mut |c| {
313                    ty::Const::new_bound(self, ty::INNERMOST, ty::BoundConst::new(shift_bv(c.var)))
314                },
315            },
316        )
317    }
318
319    /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
320    /// method lookup and a few other places where precise region relationships are not required.
321    pub fn instantiate_bound_regions_with_erased<T>(self, value: Binder<'tcx, T>) -> T
322    where
323        T: TypeFoldable<TyCtxt<'tcx>>,
324    {
325        self.instantiate_bound_regions(value, |_| self.lifetimes.re_erased).0
326    }
327
328    /// Anonymize all bound variables in `value`, this is mostly used to improve caching.
329    pub fn anonymize_bound_vars<T>(self, value: Binder<'tcx, T>) -> Binder<'tcx, T>
330    where
331        T: TypeFoldable<TyCtxt<'tcx>>,
332    {
333        struct Anonymize<'a, 'tcx> {
334            tcx: TyCtxt<'tcx>,
335            map: &'a mut FxIndexMap<ty::BoundVar, ty::BoundVariableKind<'tcx>>,
336        }
337        impl<'tcx> BoundVarReplacerDelegate<'tcx> for Anonymize<'_, 'tcx> {
338            fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {
339                let entry = self.map.entry(br.var);
340                let index = entry.index();
341                let var = ty::BoundVar::from_usize(index);
342                let kind = entry
343                    .or_insert_with(|| ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon))
344                    .expect_region();
345                let br = ty::BoundRegion { var, kind };
346                ty::Region::new_bound(self.tcx, ty::INNERMOST, br)
347            }
348            fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {
349                let entry = self.map.entry(bt.var);
350                let index = entry.index();
351                let var = ty::BoundVar::from_usize(index);
352                let kind = entry
353                    .or_insert_with(|| ty::BoundVariableKind::Ty(ty::BoundTyKind::Anon))
354                    .expect_ty();
355                Ty::new_bound(self.tcx, ty::INNERMOST, BoundTy { var, kind })
356            }
357            fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {
358                let entry = self.map.entry(bc.var);
359                let index = entry.index();
360                let var = ty::BoundVar::from_usize(index);
361                let () = entry.or_insert_with(|| ty::BoundVariableKind::Const).expect_const();
362                ty::Const::new_bound(self.tcx, ty::INNERMOST, ty::BoundConst::new(var))
363            }
364        }
365
366        let mut map = Default::default();
367        let delegate = Anonymize { tcx: self, map: &mut map };
368        let inner = self.replace_escaping_bound_vars_uncached(value.skip_binder(), delegate);
369        let bound_vars = self.mk_bound_variable_kinds_from_iter(map.into_values());
370        Binder::bind_with_vars(inner, bound_vars)
371    }
372}