1 //! Generalized type folding mechanism. The setup is a bit convoluted
2 //! but allows for convenient usage. Let T be an instance of some
3 //! "foldable type" (one which implements `TypeFoldable`) and F be an
4 //! instance of a "folder" (a type which implements `TypeFolder`). Then
5 //! the setup is intended to be:
7 //! T.fold_with(F) --calls--> F.fold_T(T) --calls--> T.super_fold_with(F)
9 //! This way, when you define a new folder F, you can override
10 //! `fold_T()` to customize the behavior, and invoke `T.super_fold_with()`
11 //! to get the original behavior. Meanwhile, to actually fold
12 //! something, you can just write `T.fold_with(F)`, which is
13 //! convenient. (Note that `fold_with` will also transparently handle
14 //! things like a `Vec<T>` where T is foldable and so on.)
16 //! In this ideal setup, the only function that actually *does*
17 //! anything is `T.super_fold_with()`, which traverses the type `T`.
18 //! Moreover, `T.super_fold_with()` should only ever call `T.fold_with()`.
20 //! In some cases, we follow a degenerate pattern where we do not have
21 //! a `fold_T` method. Instead, `T.fold_with` traverses the structure directly.
22 //! This is suboptimal because the behavior cannot be overridden, but it's
23 //! much less work to implement. If you ever *do* need an override that
24 //! doesn't exist, it's not hard to convert the degenerate pattern into the
27 //! A `TypeFoldable` T can also be visited by a `TypeVisitor` V using similar setup:
29 //! T.visit_with(V) --calls--> V.visit_T(T) --calls--> T.super_visit_with(V).
31 //! These methods return true to indicate that the visitor has found what it is
32 //! looking for, and does not need to visit anything else.
34 use crate::ty::{self, flags::FlagComputation, Binder, Ty, TyCtxt, TypeFlags};
35 use rustc_hir::def_id::DefId;
37 use rustc_data_structures::fx::FxHashSet;
38 use std::collections::BTreeMap;
41 /// This trait is implemented for every type that can be folded.
42 /// Basically, every type that has a corresponding method in `TypeFolder`.
44 /// To implement this conveniently, use the derive macro located in librustc_macros.
45 pub trait TypeFoldable<'tcx>: fmt::Debug + Clone {
46 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self;
47 fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
48 self.super_fold_with(folder)
51 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool;
52 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
53 self.super_visit_with(visitor)
56 /// Returns `true` if `self` has any late-bound regions that are either
57 /// bound by `binder` or bound by some binder outside of `binder`.
58 /// If `binder` is `ty::INNERMOST`, this indicates whether
59 /// there are any late-bound regions that appear free.
60 fn has_vars_bound_at_or_above(&self, binder: ty::DebruijnIndex) -> bool {
61 self.visit_with(&mut HasEscapingVarsVisitor { outer_index: binder })
64 /// Returns `true` if this `self` has any regions that escape `binder` (and
65 /// hence are not bound by it).
66 fn has_vars_bound_above(&self, binder: ty::DebruijnIndex) -> bool {
67 self.has_vars_bound_at_or_above(binder.shifted_in(1))
70 fn has_escaping_bound_vars(&self) -> bool {
71 self.has_vars_bound_at_or_above(ty::INNERMOST)
74 fn has_type_flags(&self, flags: TypeFlags) -> bool {
75 self.visit_with(&mut HasTypeFlagsVisitor { flags })
77 fn has_projections(&self) -> bool {
78 self.has_type_flags(TypeFlags::HAS_PROJECTION)
80 fn references_error(&self) -> bool {
81 self.has_type_flags(TypeFlags::HAS_TY_ERR)
83 fn has_param_types(&self) -> bool {
84 self.has_type_flags(TypeFlags::HAS_PARAMS)
86 fn has_infer_types(&self) -> bool {
87 self.has_type_flags(TypeFlags::HAS_TY_INFER)
89 fn has_infer_consts(&self) -> bool {
90 self.has_type_flags(TypeFlags::HAS_CT_INFER)
92 fn has_local_value(&self) -> bool {
93 self.has_type_flags(TypeFlags::KEEP_IN_LOCAL_TCX)
95 fn needs_infer(&self) -> bool {
97 TypeFlags::HAS_TY_INFER | TypeFlags::HAS_RE_INFER | TypeFlags::HAS_CT_INFER,
100 fn has_placeholders(&self) -> bool {
102 TypeFlags::HAS_RE_PLACEHOLDER
103 | TypeFlags::HAS_TY_PLACEHOLDER
104 | TypeFlags::HAS_CT_PLACEHOLDER,
107 fn needs_subst(&self) -> bool {
108 self.has_type_flags(TypeFlags::NEEDS_SUBST)
110 fn has_re_placeholders(&self) -> bool {
111 self.has_type_flags(TypeFlags::HAS_RE_PLACEHOLDER)
113 fn has_closure_types(&self) -> bool {
114 self.has_type_flags(TypeFlags::HAS_TY_CLOSURE)
116 /// "Free" regions in this context means that it has any region
117 /// that is not (a) erased or (b) late-bound.
118 fn has_free_regions(&self) -> bool {
119 self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
122 /// True if there are any un-erased free regions.
123 fn has_erasable_regions(&self) -> bool {
124 self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
127 /// Indicates whether this value references only 'global'
128 /// generic parameters that are the same regardless of what fn we are
129 /// in. This is used for caching.
130 fn is_global(&self) -> bool {
131 !self.has_type_flags(TypeFlags::HAS_FREE_LOCAL_NAMES)
134 /// True if there are any late-bound regions
135 fn has_late_bound_regions(&self) -> bool {
136 self.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND)
139 /// A visitor that does not recurse into types, works like `fn walk_shallow` in `Ty`.
140 fn visit_tys_shallow(&self, visit: impl FnMut(Ty<'tcx>) -> bool) -> bool {
141 pub struct Visitor<F>(F);
143 impl<'tcx, F: FnMut(Ty<'tcx>) -> bool> TypeVisitor<'tcx> for Visitor<F> {
144 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
149 self.visit_with(&mut Visitor(visit))
153 /// The `TypeFolder` trait defines the actual *folding*. There is a
154 /// method defined for every foldable type. Each of these has a
155 /// default implementation that does an "identity" fold. Within each
156 /// identity fold, it should invoke `foo.fold_with(self)` to fold each
158 pub trait TypeFolder<'tcx>: Sized {
159 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
161 fn fold_binder<T>(&mut self, t: &Binder<T>) -> Binder<T>
163 T: TypeFoldable<'tcx>,
165 t.super_fold_with(self)
168 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
169 t.super_fold_with(self)
172 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
173 r.super_fold_with(self)
176 fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
177 c.super_fold_with(self)
181 pub trait TypeVisitor<'tcx>: Sized {
182 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
183 t.super_visit_with(self)
186 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
187 t.super_visit_with(self)
190 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
191 r.super_visit_with(self)
194 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
195 c.super_visit_with(self)
199 ///////////////////////////////////////////////////////////////////////////
200 // Some sample folders
202 pub struct BottomUpFolder<'tcx, F, G, H>
204 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
205 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
206 H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>,
208 pub tcx: TyCtxt<'tcx>,
214 impl<'tcx, F, G, H> TypeFolder<'tcx> for BottomUpFolder<'tcx, F, G, H>
216 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
217 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
218 H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>,
220 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
224 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
225 let t = ty.super_fold_with(self);
229 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
230 let r = r.super_fold_with(self);
234 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
235 let ct = ct.super_fold_with(self);
240 ///////////////////////////////////////////////////////////////////////////
243 impl<'tcx> TyCtxt<'tcx> {
244 /// Collects the free and escaping regions in `value` into `region_set`. Returns
245 /// whether any late-bound regions were skipped
246 pub fn collect_regions<T>(self, value: &T, region_set: &mut FxHashSet<ty::Region<'tcx>>) -> bool
248 T: TypeFoldable<'tcx>,
250 let mut have_bound_regions = false;
251 self.fold_regions(value, &mut have_bound_regions, |r, d| {
252 region_set.insert(self.mk_region(r.shifted_out_to_binder(d)));
258 /// Folds the escaping and free regions in `value` using `f`, and
259 /// sets `skipped_regions` to true if any late-bound region was found
261 pub fn fold_regions<T>(
264 skipped_regions: &mut bool,
265 mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
268 T: TypeFoldable<'tcx>,
270 value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f))
273 /// Invoke `callback` on every region appearing free in `value`.
274 pub fn for_each_free_region(
276 value: &impl TypeFoldable<'tcx>,
277 mut callback: impl FnMut(ty::Region<'tcx>),
279 self.any_free_region_meets(value, |r| {
285 /// Returns `true` if `callback` returns true for every region appearing free in `value`.
286 pub fn all_free_regions_meet(
288 value: &impl TypeFoldable<'tcx>,
289 mut callback: impl FnMut(ty::Region<'tcx>) -> bool,
291 !self.any_free_region_meets(value, |r| !callback(r))
294 /// Returns `true` if `callback` returns true for some region appearing free in `value`.
295 pub fn any_free_region_meets(
297 value: &impl TypeFoldable<'tcx>,
298 callback: impl FnMut(ty::Region<'tcx>) -> bool,
300 return value.visit_with(&mut RegionVisitor { outer_index: ty::INNERMOST, callback });
302 struct RegionVisitor<F> {
303 /// The index of a binder *just outside* the things we have
304 /// traversed. If we encounter a bound region bound by this
305 /// binder or one outer to it, it appears free. Example:
308 /// for<'a> fn(for<'b> fn(), T)
310 /// | | | | here, would be shifted in 1
311 /// | | | here, would be shifted in 2
312 /// | | here, would be `INNERMOST` shifted in by 1
313 /// | here, initially, binder would be `INNERMOST`
316 /// You see that, initially, *any* bound value is free,
317 /// because we've not traversed any binders. As we pass
318 /// through a binder, we shift the `outer_index` by 1 to
319 /// account for the new binder that encloses us.
320 outer_index: ty::DebruijnIndex,
324 impl<'tcx, F> TypeVisitor<'tcx> for RegionVisitor<F>
326 F: FnMut(ty::Region<'tcx>) -> bool,
328 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
329 self.outer_index.shift_in(1);
330 let result = t.skip_binder().visit_with(self);
331 self.outer_index.shift_out(1);
335 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
337 ty::ReLateBound(debruijn, _) if debruijn < self.outer_index => {
338 false // ignore bound regions, keep visiting
340 _ => (self.callback)(r),
344 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
345 // We're only interested in types involving regions
346 if ty.flags.intersects(TypeFlags::HAS_FREE_REGIONS) {
347 ty.super_visit_with(self)
349 false // keep visiting
356 /// Folds over the substructure of a type, visiting its component
357 /// types and all regions that occur *free* within it.
359 /// That is, `Ty` can contain function or method types that bind
360 /// regions at the call site (`ReLateBound`), and occurrences of
361 /// regions (aka "lifetimes") that are bound within a type are not
362 /// visited by this folder; only regions that occur free will be
363 /// visited by `fld_r`.
365 pub struct RegionFolder<'a, 'tcx> {
367 skipped_regions: &'a mut bool,
369 /// Stores the index of a binder *just outside* the stuff we have
370 /// visited. So this begins as INNERMOST; when we pass through a
371 /// binder, it is incremented (via `shift_in`).
372 current_index: ty::DebruijnIndex,
374 /// Callback invokes for each free region. The `DebruijnIndex`
375 /// points to the binder *just outside* the ones we have passed
378 &'a mut (dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx> + 'a),
381 impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
385 skipped_regions: &'a mut bool,
386 fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
387 ) -> RegionFolder<'a, 'tcx> {
388 RegionFolder { tcx, skipped_regions, current_index: ty::INNERMOST, fold_region_fn }
392 impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
393 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
397 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
398 self.current_index.shift_in(1);
399 let t = t.super_fold_with(self);
400 self.current_index.shift_out(1);
404 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
406 ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
408 "RegionFolder.fold_region({:?}) skipped bound region (current index={:?})",
409 r, self.current_index
411 *self.skipped_regions = true;
416 "RegionFolder.fold_region({:?}) folding free region (current_index={:?})",
417 r, self.current_index
419 (self.fold_region_fn)(r, self.current_index)
425 ///////////////////////////////////////////////////////////////////////////
426 // Bound vars replacer
428 /// Replaces the escaping bound vars (late bound regions or bound types) in a type.
429 struct BoundVarReplacer<'a, 'tcx> {
432 /// As with `RegionFolder`, represents the index of a binder *just outside*
433 /// the ones we have visited.
434 current_index: ty::DebruijnIndex,
436 fld_r: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
437 fld_t: &'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a),
438 fld_c: &'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx> + 'a),
441 impl<'a, 'tcx> BoundVarReplacer<'a, 'tcx> {
442 fn new<F, G, H>(tcx: TyCtxt<'tcx>, fld_r: &'a mut F, fld_t: &'a mut G, fld_c: &'a mut H) -> Self
444 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
445 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
446 H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
448 BoundVarReplacer { tcx, current_index: ty::INNERMOST, fld_r, fld_t, fld_c }
452 impl<'a, 'tcx> TypeFolder<'tcx> for BoundVarReplacer<'a, 'tcx> {
453 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
457 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
458 self.current_index.shift_in(1);
459 let t = t.super_fold_with(self);
460 self.current_index.shift_out(1);
464 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
466 ty::Bound(debruijn, bound_ty) => {
467 if debruijn == self.current_index {
468 let fld_t = &mut self.fld_t;
469 let ty = fld_t(bound_ty);
470 ty::fold::shift_vars(self.tcx, &ty, self.current_index.as_u32())
476 if !t.has_vars_bound_at_or_above(self.current_index) {
477 // Nothing more to substitute.
480 t.super_fold_with(self)
486 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
488 ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
489 let fld_r = &mut self.fld_r;
490 let region = fld_r(br);
491 if let ty::ReLateBound(debruijn1, br) = *region {
492 // If the callback returns a late-bound region,
493 // that region should always use the INNERMOST
494 // debruijn index. Then we adjust it to the
496 assert_eq!(debruijn1, ty::INNERMOST);
497 self.tcx.mk_region(ty::ReLateBound(debruijn, br))
506 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
507 if let ty::Const { val: ty::ConstKind::Bound(debruijn, bound_const), ty } = *ct {
508 if debruijn == self.current_index {
509 let fld_c = &mut self.fld_c;
510 let ct = fld_c(bound_const, ty);
511 ty::fold::shift_vars(self.tcx, &ct, self.current_index.as_u32())
516 if !ct.has_vars_bound_at_or_above(self.current_index) {
517 // Nothing more to substitute.
520 ct.super_fold_with(self)
526 impl<'tcx> TyCtxt<'tcx> {
527 /// Replaces all regions bound by the given `Binder` with the
528 /// results returned by the closure; the closure is expected to
529 /// return a free region (relative to this binder), and hence the
530 /// binder is removed in the return type. The closure is invoked
531 /// once for each unique `BoundRegion`; multiple references to the
532 /// same `BoundRegion` will reuse the previous result. A map is
533 /// returned at the end with each bound region and the free region
534 /// that replaced it.
536 /// This method only replaces late bound regions and the result may still
537 /// contain escaping bound types.
538 pub fn replace_late_bound_regions<T, F>(
542 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
544 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
545 T: TypeFoldable<'tcx>,
547 // identity for bound types and consts
548 let fld_t = |bound_ty| self.mk_ty(ty::Bound(ty::INNERMOST, bound_ty));
549 let fld_c = |bound_ct, ty| {
550 self.mk_const(ty::Const { val: ty::ConstKind::Bound(ty::INNERMOST, bound_ct), ty })
552 self.replace_escaping_bound_vars(value.skip_binder(), fld_r, fld_t, fld_c)
555 /// Replaces all escaping bound vars. The `fld_r` closure replaces escaping
556 /// bound regions; the `fld_t` closure replaces escaping bound types and the `fld_c`
557 /// closure replaces escaping bound consts.
558 pub fn replace_escaping_bound_vars<T, F, G, H>(
564 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
566 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
567 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
568 H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
569 T: TypeFoldable<'tcx>,
571 use rustc_data_structures::fx::FxHashMap;
573 let mut region_map = BTreeMap::new();
574 let mut type_map = FxHashMap::default();
575 let mut const_map = FxHashMap::default();
577 if !value.has_escaping_bound_vars() {
578 (value.clone(), region_map)
580 let mut real_fld_r = |br| *region_map.entry(br).or_insert_with(|| fld_r(br));
583 |bound_ty| *type_map.entry(bound_ty).or_insert_with(|| fld_t(bound_ty));
586 |bound_ct, ty| *const_map.entry(bound_ct).or_insert_with(|| fld_c(bound_ct, ty));
589 BoundVarReplacer::new(self, &mut real_fld_r, &mut real_fld_t, &mut real_fld_c);
590 let result = value.fold_with(&mut replacer);
595 /// Replaces all types or regions bound by the given `Binder`. The `fld_r`
596 /// closure replaces bound regions while the `fld_t` closure replaces bound
598 pub fn replace_bound_vars<T, F, G, H>(
604 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
606 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
607 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
608 H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
609 T: TypeFoldable<'tcx>,
611 self.replace_escaping_bound_vars(value.skip_binder(), fld_r, fld_t, fld_c)
614 /// Replaces any late-bound regions bound in `value` with
615 /// free variants attached to `all_outlive_scope`.
616 pub fn liberate_late_bound_regions<T>(
618 all_outlive_scope: DefId,
619 value: &ty::Binder<T>,
622 T: TypeFoldable<'tcx>,
624 self.replace_late_bound_regions(value, |br| {
625 self.mk_region(ty::ReFree(ty::FreeRegion {
626 scope: all_outlive_scope,
633 /// Returns a set of all late-bound regions that are constrained
634 /// by `value`, meaning that if we instantiate those LBR with
635 /// variables and equate `value` with something else, those
636 /// variables will also be equated.
637 pub fn collect_constrained_late_bound_regions<T>(
640 ) -> FxHashSet<ty::BoundRegion>
642 T: TypeFoldable<'tcx>,
644 self.collect_late_bound_regions(value, true)
647 /// Returns a set of all late-bound regions that appear in `value` anywhere.
648 pub fn collect_referenced_late_bound_regions<T>(
651 ) -> FxHashSet<ty::BoundRegion>
653 T: TypeFoldable<'tcx>,
655 self.collect_late_bound_regions(value, false)
658 fn collect_late_bound_regions<T>(
661 just_constraint: bool,
662 ) -> FxHashSet<ty::BoundRegion>
664 T: TypeFoldable<'tcx>,
666 let mut collector = LateBoundRegionsCollector::new(just_constraint);
667 let result = value.skip_binder().visit_with(&mut collector);
668 assert!(!result); // should never have stopped early
672 /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
673 /// method lookup and a few other places where precise region relationships are not required.
674 pub fn erase_late_bound_regions<T>(self, value: &Binder<T>) -> T
676 T: TypeFoldable<'tcx>,
678 self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
681 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
682 /// assigned starting at 1 and increasing monotonically in the order traversed
683 /// by the fold operation.
685 /// The chief purpose of this function is to canonicalize regions so that two
686 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
687 /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
688 /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
689 pub fn anonymize_late_bound_regions<T>(self, sig: &Binder<T>) -> Binder<T>
691 T: TypeFoldable<'tcx>,
695 self.replace_late_bound_regions(sig, |_| {
697 self.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(counter)))
704 ///////////////////////////////////////////////////////////////////////////
707 // Shifts the De Bruijn indices on all escaping bound vars by a
708 // fixed amount. Useful in substitution or when otherwise introducing
709 // a binding level that is not intended to capture the existing bound
710 // vars. See comment on `shift_vars_through_binders` method in
711 // `subst.rs` for more details.
718 struct Shifter<'tcx> {
720 current_index: ty::DebruijnIndex,
722 direction: Direction,
726 pub fn new(tcx: TyCtxt<'tcx>, amount: u32, direction: Direction) -> Self {
727 Shifter { tcx, current_index: ty::INNERMOST, amount, direction }
731 impl TypeFolder<'tcx> for Shifter<'tcx> {
732 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
736 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
737 self.current_index.shift_in(1);
738 let t = t.super_fold_with(self);
739 self.current_index.shift_out(1);
743 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
745 ty::ReLateBound(debruijn, br) => {
746 if self.amount == 0 || debruijn < self.current_index {
749 let debruijn = match self.direction {
750 Direction::In => debruijn.shifted_in(self.amount),
752 assert!(debruijn.as_u32() >= self.amount);
753 debruijn.shifted_out(self.amount)
756 let shifted = ty::ReLateBound(debruijn, br);
757 self.tcx.mk_region(shifted)
764 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
766 ty::Bound(debruijn, bound_ty) => {
767 if self.amount == 0 || debruijn < self.current_index {
770 let debruijn = match self.direction {
771 Direction::In => debruijn.shifted_in(self.amount),
773 assert!(debruijn.as_u32() >= self.amount);
774 debruijn.shifted_out(self.amount)
777 self.tcx.mk_ty(ty::Bound(debruijn, bound_ty))
781 _ => ty.super_fold_with(self),
785 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
786 if let ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty } = *ct {
787 if self.amount == 0 || debruijn < self.current_index {
790 let debruijn = match self.direction {
791 Direction::In => debruijn.shifted_in(self.amount),
793 assert!(debruijn.as_u32() >= self.amount);
794 debruijn.shifted_out(self.amount)
797 self.tcx.mk_const(ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty })
800 ct.super_fold_with(self)
805 pub fn shift_region<'tcx>(
807 region: ty::Region<'tcx>,
809 ) -> ty::Region<'tcx> {
811 ty::ReLateBound(debruijn, br) if amount > 0 => {
812 tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), *br))
818 pub fn shift_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: &T, amount: u32) -> T
820 T: TypeFoldable<'tcx>,
822 debug!("shift_vars(value={:?}, amount={})", value, amount);
824 value.fold_with(&mut Shifter::new(tcx, amount, Direction::In))
827 pub fn shift_out_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: &T, amount: u32) -> T
829 T: TypeFoldable<'tcx>,
831 debug!("shift_out_vars(value={:?}, amount={})", value, amount);
833 value.fold_with(&mut Shifter::new(tcx, amount, Direction::Out))
836 /// An "escaping var" is a bound var whose binder is not part of `t`. A bound var can be a
837 /// bound region or a bound type.
839 /// So, for example, consider a type like the following, which has two binders:
841 /// for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
842 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
843 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
845 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
846 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
847 /// fn type*, that type has an escaping region: `'a`.
849 /// Note that what I'm calling an "escaping var" is often just called a "free var". However,
850 /// we already use the term "free var". It refers to the regions or types that we use to represent
851 /// bound regions or type params on a fn definition while we are type checking its body.
853 /// To clarify, conceptually there is no particular difference between
854 /// an "escaping" var and a "free" var. However, there is a big
855 /// difference in practice. Basically, when "entering" a binding
856 /// level, one is generally required to do some sort of processing to
857 /// a bound var, such as replacing it with a fresh/placeholder
858 /// var, or making an entry in the environment to represent the
859 /// scope to which it is attached, etc. An escaping var represents
860 /// a bound var for which this processing has not yet been done.
861 struct HasEscapingVarsVisitor {
862 /// Anything bound by `outer_index` or "above" is escaping.
863 outer_index: ty::DebruijnIndex,
866 impl<'tcx> TypeVisitor<'tcx> for HasEscapingVarsVisitor {
867 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
868 self.outer_index.shift_in(1);
869 let result = t.super_visit_with(self);
870 self.outer_index.shift_out(1);
874 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
875 // If the outer-exclusive-binder is *strictly greater* than
876 // `outer_index`, that means that `t` contains some content
877 // bound at `outer_index` or above (because
878 // `outer_exclusive_binder` is always 1 higher than the
879 // content in `t`). Therefore, `t` has some escaping vars.
880 t.outer_exclusive_binder > self.outer_index
883 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
884 // If the region is bound by `outer_index` or anything outside
885 // of outer index, then it escapes the binders we have
887 r.bound_at_or_above_binder(self.outer_index)
890 fn visit_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> bool {
891 // we don't have a `visit_infer_const` callback, so we have to
892 // hook in here to catch this case (annoying...), but
893 // otherwise we do want to remember to visit the rest of the
894 // const, as it has types/regions embedded in a lot of other
897 ty::ConstKind::Bound(debruijn, _) if debruijn >= self.outer_index => true,
898 _ => ct.super_visit_with(self),
903 // FIXME: Optimize for checking for infer flags
904 struct HasTypeFlagsVisitor {
905 flags: ty::TypeFlags,
908 impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor {
909 fn visit_ty(&mut self, t: Ty<'_>) -> bool {
910 debug!("HasTypeFlagsVisitor: t={:?} t.flags={:?} self.flags={:?}", t, t.flags, self.flags);
911 t.flags.intersects(self.flags)
914 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
915 let flags = r.type_flags();
916 debug!("HasTypeFlagsVisitor: r={:?} r.flags={:?} self.flags={:?}", r, flags, self.flags);
917 flags.intersects(self.flags)
920 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
921 let flags = FlagComputation::for_const(c);
922 debug!("HasTypeFlagsVisitor: c={:?} c.flags={:?} self.flags={:?}", c, flags, self.flags);
923 flags.intersects(self.flags)
927 /// Collects all the late-bound regions at the innermost binding level
929 struct LateBoundRegionsCollector {
930 current_index: ty::DebruijnIndex,
931 regions: FxHashSet<ty::BoundRegion>,
933 /// `true` if we only want regions that are known to be
934 /// "constrained" when you equate this type with another type. In
935 /// particular, if you have e.g., `&'a u32` and `&'b u32`, equating
936 /// them constraints `'a == 'b`. But if you have `<&'a u32 as
937 /// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those
938 /// types may mean that `'a` and `'b` don't appear in the results,
939 /// so they are not considered *constrained*.
940 just_constrained: bool,
943 impl LateBoundRegionsCollector {
944 fn new(just_constrained: bool) -> Self {
945 LateBoundRegionsCollector {
946 current_index: ty::INNERMOST,
947 regions: Default::default(),
953 impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector {
954 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
955 self.current_index.shift_in(1);
956 let result = t.super_visit_with(self);
957 self.current_index.shift_out(1);
961 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
962 // if we are only looking for "constrained" region, we have to
963 // ignore the inputs to a projection, as they may not appear
964 // in the normalized form
965 if self.just_constrained {
967 ty::Projection(..) | ty::Opaque(..) => {
974 t.super_visit_with(self)
977 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
978 if let ty::ReLateBound(debruijn, br) = *r {
979 if debruijn == self.current_index {
980 self.regions.insert(br);