]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/fold.rs
Auto merge of #102596 - scottmcm:option-bool-calloc, r=Mark-Simulacrum
[rust.git] / compiler / rustc_middle / src / ty / fold.rs
1 //! A folding traversal mechanism for complex data structures that contain type
2 //! information.
3 //!
4 //! This is a modifying traversal. It consumes the data structure, producing a
5 //! (possibly) modified version of it. Both fallible and infallible versions are
6 //! available. The name is potentially confusing, because this traversal is more
7 //! like `Iterator::map` than `Iterator::fold`.
8 //!
9 //! This traversal has limited flexibility. Only a small number of "types of
10 //! interest" within the complex data structures can receive custom
11 //! modification. These are the ones containing the most important type-related
12 //! information, such as `Ty`, `Predicate`, `Region`, and `Const`.
13 //!
14 //! There are three groups of traits involved in each traversal.
15 //! - `TypeFoldable`. This is implemented once for many types, including:
16 //!   - Types of interest, for which the the methods delegate to the
17 //!     folder.
18 //!   - All other types, including generic containers like `Vec` and `Option`.
19 //!     It defines a "skeleton" of how they should be folded.
20 //! - `TypeSuperFoldable`. This is implemented only for each type of interest,
21 //!   and defines the folding "skeleton" for these types.
22 //! - `TypeFolder`/`FallibleTypeFolder. One of these is implemented for each
23 //!   folder. This defines how types of interest are folded.
24 //!
25 //! This means each fold is a mixture of (a) generic folding operations, and (b)
26 //! custom fold operations that are specific to the folder.
27 //! - The `TypeFoldable` impls handle most of the traversal, and call into
28 //!   `TypeFolder`/`FallibleTypeFolder` when they encounter a type of interest.
29 //! - A `TypeFolder`/`FallibleTypeFolder` may call into another `TypeFoldable`
30 //!   impl, because some of the types of interest are recursive and can contain
31 //!   other types of interest.
32 //! - A `TypeFolder`/`FallibleTypeFolder` may also call into a `TypeSuperFoldable`
33 //!   impl, because each folder might provide custom handling only for some types
34 //!   of interest, or only for some variants of each type of interest, and then
35 //!   use default traversal for the remaining cases.
36 //!
37 //! For example, if you have `struct S(Ty, U)` where `S: TypeFoldable` and `U:
38 //! TypeFoldable`, and an instance `s = S(ty, u)`, it would be folded like so:
39 //! ```text
40 //! s.fold_with(folder) calls
41 //! - ty.fold_with(folder) calls
42 //!   - folder.fold_ty(ty) may call
43 //!     - ty.super_fold_with(folder)
44 //! - u.fold_with(folder)
45 //! ```
46 use crate::mir;
47 use crate::ty::{self, Binder, BoundTy, Ty, TyCtxt, TypeVisitable};
48 use rustc_data_structures::fx::FxIndexMap;
49 use rustc_hir::def_id::DefId;
50
51 use std::collections::BTreeMap;
52
53 /// This trait is implemented for every type that can be folded,
54 /// providing the skeleton of the traversal.
55 ///
56 /// To implement this conveniently, use the derive macro located in
57 /// `rustc_macros`.
58 pub trait TypeFoldable<'tcx>: TypeVisitable<'tcx> {
59     /// The entry point for folding. To fold a value `t` with a folder `f`
60     /// call: `t.try_fold_with(f)`.
61     ///
62     /// For most types, this just traverses the value, calling `try_fold_with`
63     /// on each field/element.
64     ///
65     /// For types of interest (such as `Ty`), the implementation of method
66     /// calls a folder method specifically for that type (such as
67     /// `F::try_fold_ty`). This is where control transfers from `TypeFoldable`
68     /// to `TypeFolder`.
69     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error>;
70
71     /// A convenient alternative to `try_fold_with` for use with infallible
72     /// folders. Do not override this method, to ensure coherence with
73     /// `try_fold_with`.
74     fn fold_with<F: TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
75         self.try_fold_with(folder).into_ok()
76     }
77 }
78
79 // This trait is implemented for types of interest.
80 pub trait TypeSuperFoldable<'tcx>: TypeFoldable<'tcx> {
81     /// Provides a default fold for a type of interest. This should only be
82     /// called within `TypeFolder` methods, when a non-custom traversal is
83     /// desired for the value of the type of interest passed to that method.
84     /// For example, in `MyFolder::try_fold_ty(ty)`, it is valid to call
85     /// `ty.try_super_fold_with(self)`, but any other folding should be done
86     /// with `xyz.try_fold_with(self)`.
87     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
88         self,
89         folder: &mut F,
90     ) -> Result<Self, F::Error>;
91
92     /// A convenient alternative to `try_super_fold_with` for use with
93     /// infallible folders. Do not override this method, to ensure coherence
94     /// with `try_super_fold_with`.
95     fn super_fold_with<F: TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
96         self.try_super_fold_with(folder).into_ok()
97     }
98 }
99
100 /// This trait is implemented for every infallible folding traversal. There is
101 /// a fold method defined for every type of interest. Each such method has a
102 /// default that does an "identity" fold. Implementations of these methods
103 /// often fall back to a `super_fold_with` method if the primary argument
104 /// doesn't satisfy a particular condition.
105 ///
106 /// A blanket implementation of [`FallibleTypeFolder`] will defer to
107 /// the infallible methods of this trait to ensure that the two APIs
108 /// are coherent.
109 pub trait TypeFolder<'tcx>: FallibleTypeFolder<'tcx, Error = !> {
110     fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
111
112     fn fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Binder<'tcx, T>
113     where
114         T: TypeFoldable<'tcx>,
115     {
116         t.super_fold_with(self)
117     }
118
119     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
120         t.super_fold_with(self)
121     }
122
123     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
124         r.super_fold_with(self)
125     }
126
127     fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
128         c.super_fold_with(self)
129     }
130
131     fn fold_ty_unevaluated(
132         &mut self,
133         uv: ty::UnevaluatedConst<'tcx>,
134     ) -> ty::UnevaluatedConst<'tcx> {
135         uv.super_fold_with(self)
136     }
137
138     fn fold_mir_unevaluated(
139         &mut self,
140         uv: mir::UnevaluatedConst<'tcx>,
141     ) -> mir::UnevaluatedConst<'tcx> {
142         uv.super_fold_with(self)
143     }
144
145     fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
146         p.super_fold_with(self)
147     }
148
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)
151     }
152 }
153
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.
157 ///
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 {
162     type Error;
163
164     fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
165
166     fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, Self::Error>
167     where
168         T: TypeFoldable<'tcx>,
169     {
170         t.try_super_fold_with(self)
171     }
172
173     fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
174         t.try_super_fold_with(self)
175     }
176
177     fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
178         r.try_super_fold_with(self)
179     }
180
181     fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, Self::Error> {
182         c.try_super_fold_with(self)
183     }
184
185     fn try_fold_ty_unevaluated(
186         &mut self,
187         c: ty::UnevaluatedConst<'tcx>,
188     ) -> Result<ty::UnevaluatedConst<'tcx>, Self::Error> {
189         c.try_super_fold_with(self)
190     }
191
192     fn try_fold_mir_unevaluated(
193         &mut self,
194         c: mir::UnevaluatedConst<'tcx>,
195     ) -> Result<mir::UnevaluatedConst<'tcx>, Self::Error> {
196         c.try_super_fold_with(self)
197     }
198
199     fn try_fold_predicate(
200         &mut self,
201         p: ty::Predicate<'tcx>,
202     ) -> Result<ty::Predicate<'tcx>, Self::Error> {
203         p.try_super_fold_with(self)
204     }
205
206     fn try_fold_mir_const(
207         &mut self,
208         c: mir::ConstantKind<'tcx>,
209     ) -> Result<mir::ConstantKind<'tcx>, Self::Error> {
210         bug!("most type folders should not be folding MIR datastructures: {:?}", c)
211     }
212 }
213
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
217 where
218     F: TypeFolder<'tcx>,
219 {
220     type Error = !;
221
222     fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
223         TypeFolder::tcx(self)
224     }
225
226     fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, !>
227     where
228         T: TypeFoldable<'tcx>,
229     {
230         Ok(self.fold_binder(t))
231     }
232
233     fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, !> {
234         Ok(self.fold_ty(t))
235     }
236
237     fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, !> {
238         Ok(self.fold_region(r))
239     }
240
241     fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, !> {
242         Ok(self.fold_const(c))
243     }
244
245     fn try_fold_ty_unevaluated(
246         &mut self,
247         c: ty::UnevaluatedConst<'tcx>,
248     ) -> Result<ty::UnevaluatedConst<'tcx>, !> {
249         Ok(self.fold_ty_unevaluated(c))
250     }
251
252     fn try_fold_mir_unevaluated(
253         &mut self,
254         c: mir::UnevaluatedConst<'tcx>,
255     ) -> Result<mir::UnevaluatedConst<'tcx>, !> {
256         Ok(self.fold_mir_unevaluated(c))
257     }
258
259     fn try_fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> Result<ty::Predicate<'tcx>, !> {
260         Ok(self.fold_predicate(p))
261     }
262
263     fn try_fold_mir_const(
264         &mut self,
265         c: mir::ConstantKind<'tcx>,
266     ) -> Result<mir::ConstantKind<'tcx>, !> {
267         Ok(self.fold_mir_const(c))
268     }
269 }
270
271 ///////////////////////////////////////////////////////////////////////////
272 // Some sample folders
273
274 pub struct BottomUpFolder<'tcx, F, G, H>
275 where
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>,
279 {
280     pub tcx: TyCtxt<'tcx>,
281     pub ty_op: F,
282     pub lt_op: G,
283     pub ct_op: H,
284 }
285
286 impl<'tcx, F, G, H> TypeFolder<'tcx> for BottomUpFolder<'tcx, F, G, H>
287 where
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>,
291 {
292     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
293         self.tcx
294     }
295
296     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
297         let t = ty.super_fold_with(self);
298         (self.ty_op)(t)
299     }
300
301     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
302         let r = r.super_fold_with(self);
303         (self.lt_op)(r)
304     }
305
306     fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
307         let ct = ct.super_fold_with(self);
308         (self.ct_op)(ct)
309     }
310 }
311
312 ///////////////////////////////////////////////////////////////////////////
313 // Region folder
314
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
318     /// and skipped.
319     pub fn fold_regions<T>(
320         self,
321         value: T,
322         mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
323     ) -> T
324     where
325         T: TypeFoldable<'tcx>,
326     {
327         value.fold_with(&mut RegionFolder::new(self, &mut f))
328     }
329
330     pub fn super_fold_regions<T>(
331         self,
332         value: T,
333         mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
334     ) -> T
335     where
336         T: TypeSuperFoldable<'tcx>,
337     {
338         value.super_fold_with(&mut RegionFolder::new(self, &mut f))
339     }
340 }
341
342 /// Folds over the substructure of a type, visiting its component
343 /// types and all regions that occur *free* within it.
344 ///
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`.
350
351 pub struct RegionFolder<'a, 'tcx> {
352     tcx: TyCtxt<'tcx>,
353
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,
358
359     /// Callback invokes for each free region. The `DebruijnIndex`
360     /// points to the binder *just outside* the ones we have passed
361     /// through.
362     fold_region_fn:
363         &'a mut (dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx> + 'a),
364 }
365
366 impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
367     #[inline]
368     pub fn new(
369         tcx: TyCtxt<'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 }
373     }
374 }
375
376 impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
377     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
378         self.tcx
379     }
380
381     fn fold_binder<T: TypeFoldable<'tcx>>(
382         &mut self,
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);
388         t
389     }
390
391     #[instrument(skip(self), level = "debug", ret)]
392     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
393         match *r {
394             ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
395                 debug!(?self.current_index, "skipped bound region");
396                 r
397             }
398             _ => {
399                 debug!(?self.current_index, "folding free region");
400                 (self.fold_region_fn)(r, self.current_index)
401             }
402         }
403     }
404 }
405
406 ///////////////////////////////////////////////////////////////////////////
407 // Bound vars replacer
408
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>;
413 }
414
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),
419 }
420
421 impl<'a, 'tcx> BoundVarReplacerDelegate<'tcx> for FnMutDelegate<'a, 'tcx> {
422     fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> {
423         (self.regions)(br)
424     }
425     fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> {
426         (self.types)(bt)
427     }
428     fn replace_const(&mut self, bv: ty::BoundVar, ty: Ty<'tcx>) -> ty::Const<'tcx> {
429         (self.consts)(bv, ty)
430     }
431 }
432
433 /// Replaces the escaping bound vars (late bound regions or bound types) in a type.
434 struct BoundVarReplacer<'tcx, D> {
435     tcx: TyCtxt<'tcx>,
436
437     /// As with `RegionFolder`, represents the index of a binder *just outside*
438     /// the ones we have visited.
439     current_index: ty::DebruijnIndex,
440
441     delegate: D,
442 }
443
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 }
447     }
448 }
449
450 impl<'tcx, D> TypeFolder<'tcx> for BoundVarReplacer<'tcx, D>
451 where
452     D: BoundVarReplacerDelegate<'tcx>,
453 {
454     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
455         self.tcx
456     }
457
458     fn fold_binder<T: TypeFoldable<'tcx>>(
459         &mut self,
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);
465         t
466     }
467
468     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
469         match *t.kind() {
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())
473             }
474             _ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
475             _ => t,
476         }
477     }
478
479     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
480         match *r {
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
487                     // correct depth.
488                     assert_eq!(debruijn1, ty::INNERMOST);
489                     self.tcx.reuse_or_mk_region(region, ty::ReLateBound(debruijn, br))
490                 } else {
491                     region
492                 }
493             }
494             _ => r,
495         }
496     }
497
498     fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
499         match ct.kind() {
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())
503             }
504             _ => ct.super_fold_with(self),
505         }
506     }
507
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 }
510     }
511 }
512
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.
522     ///
523     /// # Panics
524     ///
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>(
528         self,
529         value: Binder<'tcx, T>,
530         mut fld_r: F,
531     ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
532     where
533         F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
534         T: TypeFoldable<'tcx>,
535     {
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);
539         (value, region_map)
540     }
541
542     pub fn replace_late_bound_regions_uncached<T, F>(
543         self,
544         value: Binder<'tcx, T>,
545         mut replace_regions: F,
546     ) -> T
547     where
548         F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
549         T: TypeFoldable<'tcx>,
550     {
551         let value = value.skip_binder();
552         if !value.has_escaping_bound_vars() {
553             value
554         } else {
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}"),
559             };
560             let mut replacer = BoundVarReplacer::new(self, delegate);
561             value.fold_with(&mut replacer)
562         }
563     }
564
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>>(
569         self,
570         value: T,
571         delegate: impl BoundVarReplacerDelegate<'tcx>,
572     ) -> T {
573         if !value.has_escaping_bound_vars() {
574             value
575         } else {
576             let mut replacer = BoundVarReplacer::new(self, delegate);
577             value.fold_with(&mut replacer)
578         }
579     }
580
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>>(
585         self,
586         value: Binder<'tcx, T>,
587         delegate: impl BoundVarReplacerDelegate<'tcx>,
588     ) -> T {
589         self.replace_escaping_bound_vars_uncached(value.skip_binder(), delegate)
590     }
591
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>(
595         self,
596         all_outlive_scope: DefId,
597         value: ty::Binder<'tcx, T>,
598     ) -> T
599     where
600         T: TypeFoldable<'tcx>,
601     {
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,
606             }))
607         })
608     }
609
610     pub fn shift_bound_var_indices<T>(self, bound_vars: usize, value: T) -> T
611     where
612         T: TypeFoldable<'tcx>,
613     {
614         let shift_bv = |bv: ty::BoundVar| ty::BoundVar::from_usize(bv.as_usize() + bound_vars);
615         self.replace_escaping_bound_vars_uncached(
616             value,
617             FnMutDelegate {
618                 regions: &mut |r: ty::BoundRegion| {
619                     self.mk_region(ty::ReLateBound(
620                         ty::INNERMOST,
621                         ty::BoundRegion { var: shift_bv(r.var), kind: r.kind },
622                     ))
623                 },
624                 types: &mut |t: ty::BoundTy| {
625                     self.mk_ty(ty::Bound(
626                         ty::INNERMOST,
627                         ty::BoundTy { var: shift_bv(t.var), kind: t.kind },
628                     ))
629                 },
630                 consts: &mut |c, ty: Ty<'tcx>| {
631                     self.mk_const(ty::ConstS {
632                         kind: ty::ConstKind::Bound(ty::INNERMOST, shift_bv(c)),
633                         ty,
634                     })
635                 },
636             },
637         )
638     }
639
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
643     where
644         T: TypeFoldable<'tcx>,
645     {
646         self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
647     }
648
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.
652     ///
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>
658     where
659         T: TypeFoldable<'tcx>,
660     {
661         let mut counter = 0;
662         let inner = self
663             .replace_late_bound_regions(sig, |_| {
664                 let br = ty::BoundRegion {
665                     var: ty::BoundVar::from_u32(counter),
666                     kind: ty::BrAnon(counter),
667                 };
668                 let r = self.mk_region(ty::ReLateBound(ty::INNERMOST, br));
669                 counter += 1;
670                 r
671             })
672             .0;
673         let bound_vars = self.mk_bound_variable_kinds(
674             (0..counter).map(|i| ty::BoundVariableKind::Region(ty::BrAnon(i))),
675         );
676         Binder::bind_with_vars(inner, bound_vars)
677     }
678
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>
681     where
682         T: TypeFoldable<'tcx>,
683     {
684         struct Anonymize<'a, 'tcx> {
685             tcx: TyCtxt<'tcx>,
686             map: &'a mut FxIndexMap<ty::BoundVar, ty::BoundVariableKind>,
687         }
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);
693                 let kind = entry
694                     .or_insert_with(|| ty::BoundVariableKind::Region(ty::BrAnon(index as u32)))
695                     .expect_region();
696                 let br = ty::BoundRegion { var, kind };
697                 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
698             }
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);
703                 let kind = entry
704                     .or_insert_with(|| ty::BoundVariableKind::Ty(ty::BoundTyKind::Anon))
705                     .expect_ty();
706                 self.tcx.mk_ty(ty::Bound(ty::INNERMOST, BoundTy { var, kind }))
707             }
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) })
714             }
715         }
716
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)
722     }
723 }
724
725 ///////////////////////////////////////////////////////////////////////////
726 // Shifter
727 //
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.
733
734 struct Shifter<'tcx> {
735     tcx: TyCtxt<'tcx>,
736     current_index: ty::DebruijnIndex,
737     amount: u32,
738 }
739
740 impl<'tcx> Shifter<'tcx> {
741     pub fn new(tcx: TyCtxt<'tcx>, amount: u32) -> Self {
742         Shifter { tcx, current_index: ty::INNERMOST, amount }
743     }
744 }
745
746 impl<'tcx> TypeFolder<'tcx> for Shifter<'tcx> {
747     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
748         self.tcx
749     }
750
751     fn fold_binder<T: TypeFoldable<'tcx>>(
752         &mut self,
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);
758         t
759     }
760
761     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
762         match *r {
763             ty::ReLateBound(debruijn, br) => {
764                 if self.amount == 0 || debruijn < self.current_index {
765                     r
766                 } else {
767                     let debruijn = debruijn.shifted_in(self.amount);
768                     let shifted = ty::ReLateBound(debruijn, br);
769                     self.tcx.mk_region(shifted)
770                 }
771             }
772             _ => r,
773         }
774     }
775
776     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
777         match *ty.kind() {
778             ty::Bound(debruijn, bound_ty) => {
779                 if self.amount == 0 || debruijn < self.current_index {
780                     ty
781                 } else {
782                     let debruijn = debruijn.shifted_in(self.amount);
783                     self.tcx.mk_ty(ty::Bound(debruijn, bound_ty))
784                 }
785             }
786
787             _ => ty.super_fold_with(self),
788         }
789     }
790
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 {
794                 ct
795             } else {
796                 let debruijn = debruijn.shifted_in(self.amount);
797                 self.tcx.mk_const(ty::ConstS {
798                     kind: ty::ConstKind::Bound(debruijn, bound_ct),
799                     ty: ct.ty(),
800                 })
801             }
802         } else {
803             ct.super_fold_with(self)
804         }
805     }
806 }
807
808 pub fn shift_region<'tcx>(
809     tcx: TyCtxt<'tcx>,
810     region: ty::Region<'tcx>,
811     amount: u32,
812 ) -> ty::Region<'tcx> {
813     match *region {
814         ty::ReLateBound(debruijn, br) if amount > 0 => {
815             tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), br))
816         }
817         _ => region,
818     }
819 }
820
821 pub fn shift_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: T, amount: u32) -> T
822 where
823     T: TypeFoldable<'tcx>,
824 {
825     debug!("shift_vars(value={:?}, amount={})", value, amount);
826
827     value.fold_with(&mut Shifter::new(tcx, amount))
828 }