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